blob: c3e41658c29aaf050b20329a25e74e1c6fc027a6 [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
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000051#define DEBUG_TYPE "exprconstant"
52
Anders Carlsson7a241ba2008-07-03 04:20:39 +000053using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000054using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000055using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000056
Richard Smithb228a862012-02-15 02:18:13 +000057static bool IsGlobalLValue(APValue::LValueBase B);
58
John McCall93d91dc2010-05-07 17:22:02 +000059namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000060 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000061 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000062 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000063
Richard Smithb228a862012-02-15 02:18:13 +000064 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000065 if (!B) return QualType();
66 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
Richard Smith6f4f0f12017-10-20 22:56:25 +000067 // FIXME: It's unclear where we're supposed to take the type from, and
68 // this actually matters for arrays of unknown bound. Using the type of
69 // the most recent declaration isn't clearly correct in general. Eg:
70 //
71 // extern int arr[]; void f() { extern int arr[3]; };
72 // constexpr int *p = &arr[1]; // valid?
73 return cast<ValueDecl>(D->getMostRecentDecl())->getType();
Richard Smith84401042013-06-03 05:03:02 +000074
75 const Expr *Base = B.get<const Expr*>();
76
77 // For a materialized temporary, the type of the temporary we materialized
78 // may not be the type of the expression.
79 if (const MaterializeTemporaryExpr *MTE =
80 dyn_cast<MaterializeTemporaryExpr>(Base)) {
81 SmallVector<const Expr *, 2> CommaLHSs;
82 SmallVector<SubobjectAdjustment, 2> Adjustments;
83 const Expr *Temp = MTE->GetTemporaryExpr();
84 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
85 Adjustments);
86 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000087 // for it directly. Otherwise use the type after adjustment.
88 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000089 return Inner->getType();
90 }
91
92 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000093 }
94
Richard Smithd62306a2011-11-10 06:34:14 +000095 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000096 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000097 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000098 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000099 APValue::BaseOrMemberType Value;
100 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +0000101 return Value;
102 }
103
104 /// Get an LValue path entry, which is known to not be an array index, as a
105 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000106 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000107 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000108 }
109 /// Get an LValue path entry, which is known to not be an array index, as a
110 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000111 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000112 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000113 }
114 /// Determine whether this LValue path entry for a base class names a virtual
115 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000116 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000117 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000118 }
119
George Burgess IVe3763372016-12-22 02:50:20 +0000120 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
121 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
122 const FunctionDecl *Callee = CE->getDirectCallee();
123 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
124 }
125
126 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
127 /// This will look through a single cast.
128 ///
129 /// Returns null if we couldn't unwrap a function with alloc_size.
130 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
131 if (!E->getType()->isPointerType())
132 return nullptr;
133
134 E = E->IgnoreParens();
135 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000136 // probably be a cast of some kind. In exotic cases, we might also see a
137 // top-level ExprWithCleanups. Ignore them either way.
138 if (const auto *EC = dyn_cast<ExprWithCleanups>(E))
139 E = EC->getSubExpr()->IgnoreParens();
140
George Burgess IVe3763372016-12-22 02:50:20 +0000141 if (const auto *Cast = dyn_cast<CastExpr>(E))
142 E = Cast->getSubExpr()->IgnoreParens();
143
144 if (const auto *CE = dyn_cast<CallExpr>(E))
145 return getAllocSizeAttr(CE) ? CE : nullptr;
146 return nullptr;
147 }
148
149 /// Determines whether or not the given Base contains a call to a function
150 /// with the alloc_size attribute.
151 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
152 const auto *E = Base.dyn_cast<const Expr *>();
153 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
154 }
155
Richard Smith6f4f0f12017-10-20 22:56:25 +0000156 /// The bound to claim that an array of unknown bound has.
157 /// The value in MostDerivedArraySize is undefined in this case. So, set it
158 /// to an arbitrary value that's likely to loudly break things if it's used.
159 static const uint64_t AssumedSizeForUnsizedArray =
160 std::numeric_limits<uint64_t>::max() / 2;
161
George Burgess IVe3763372016-12-22 02:50:20 +0000162 /// Determines if an LValue with the given LValueBase will have an unsized
163 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000164 /// Find the path length and type of the most-derived subobject in the given
165 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000166 static unsigned
167 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
168 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000169 uint64_t &ArraySize, QualType &Type, bool &IsArray,
170 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000171 // This only accepts LValueBases from APValues, and APValues don't support
172 // arrays that lack size info.
173 assert(!isBaseAnAllocSizeCall(Base) &&
174 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000175 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000176 Type = getType(Base);
177
Richard Smith80815602011-11-07 05:07:52 +0000178 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000179 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000180 const ArrayType *AT = Ctx.getAsArrayType(Type);
181 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000182 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000183 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000184
185 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
186 ArraySize = CAT->getSize().getZExtValue();
187 } else {
188 assert(I == 0 && "unexpected unsized array designator");
189 FirstEntryIsUnsizedArray = true;
190 ArraySize = AssumedSizeForUnsizedArray;
191 }
Richard Smith66c96992012-02-18 22:04:06 +0000192 } else if (Type->isAnyComplexType()) {
193 const ComplexType *CT = Type->castAs<ComplexType>();
194 Type = CT->getElementType();
195 ArraySize = 2;
196 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000197 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000198 } else if (const FieldDecl *FD = getAsField(Path[I])) {
199 Type = FD->getType();
200 ArraySize = 0;
201 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000202 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000203 } else {
Richard Smith80815602011-11-07 05:07:52 +0000204 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000205 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000206 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000207 }
Richard Smith80815602011-11-07 05:07:52 +0000208 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000209 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000210 }
211
Richard Smitha8105bc2012-01-06 16:39:00 +0000212 // The order of this enum is important for diagnostics.
213 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000214 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000215 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000216 };
217
Richard Smith96e0c102011-11-04 02:25:55 +0000218 /// A path from a glvalue to a subobject of that glvalue.
219 struct SubobjectDesignator {
220 /// True if the subobject was named in a manner not supported by C++11. Such
221 /// lvalues can still be folded, but they are not core constant expressions
222 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000223 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000224
Richard Smitha8105bc2012-01-06 16:39:00 +0000225 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000226 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000227
Daniel Jasperffdee092017-05-02 19:21:42 +0000228 /// Indicator of whether the first entry is an unsized array.
229 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000230
George Burgess IVa51c4072015-10-16 01:49:01 +0000231 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000232 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000233
Richard Smitha8105bc2012-01-06 16:39:00 +0000234 /// The length of the path to the most-derived object of which this is a
235 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000236 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000237
George Burgess IVa51c4072015-10-16 01:49:01 +0000238 /// The size of the array of which the most-derived object is an element.
239 /// This will always be 0 if the most-derived object is not an array
240 /// element. 0 is not an indicator of whether or not the most-derived object
241 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000242 ///
243 /// If the current array is an unsized array, the value of this is
244 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000245 uint64_t MostDerivedArraySize;
246
247 /// The type of the most derived object referred to by this address.
248 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000249
Richard Smith80815602011-11-07 05:07:52 +0000250 typedef APValue::LValuePathEntry PathEntry;
251
Richard Smith96e0c102011-11-04 02:25:55 +0000252 /// The entries on the path from the glvalue to the designated subobject.
253 SmallVector<PathEntry, 8> Entries;
254
Richard Smitha8105bc2012-01-06 16:39:00 +0000255 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000256
Richard Smitha8105bc2012-01-06 16:39:00 +0000257 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000258 : Invalid(false), 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 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000262
263 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000264 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000265 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000266 MostDerivedPathLength(0), MostDerivedArraySize(0) {
267 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000268 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000269 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000270 ArrayRef<PathEntry> VEntries = V.getLValuePath();
271 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000272 if (V.getLValueBase()) {
273 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000274 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000275 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000276 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000277 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000278 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000279 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000280 }
Richard Smith80815602011-11-07 05:07:52 +0000281 }
282 }
283
Richard Smith96e0c102011-11-04 02:25:55 +0000284 void setInvalid() {
285 Invalid = true;
286 Entries.clear();
287 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000288
George Burgess IVe3763372016-12-22 02:50:20 +0000289 /// Determine whether the most derived subobject is an array without a
290 /// known bound.
291 bool isMostDerivedAnUnsizedArray() const {
292 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000293 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000294 }
295
296 /// Determine what the most derived array's size is. Results in an assertion
297 /// failure if the most derived array lacks a size.
298 uint64_t getMostDerivedArraySize() const {
299 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
300 return MostDerivedArraySize;
301 }
302
Richard Smitha8105bc2012-01-06 16:39:00 +0000303 /// Determine whether this is a one-past-the-end pointer.
304 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000305 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000306 if (IsOnePastTheEnd)
307 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000308 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000309 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
310 return true;
311 return false;
312 }
313
314 /// Check that this refers to a valid subobject.
315 bool isValidSubobject() const {
316 if (Invalid)
317 return false;
318 return !isOnePastTheEnd();
319 }
320 /// Check that this refers to a valid subobject, and if not, produce a
321 /// relevant diagnostic and set the designator as invalid.
322 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
323
324 /// Update this designator to refer to the first element within this array.
325 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000326 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000327 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000328 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000329
330 // This is a most-derived object.
331 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000332 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000333 MostDerivedArraySize = CAT->getSize().getZExtValue();
334 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000335 }
George Burgess IVe3763372016-12-22 02:50:20 +0000336 /// Update this designator to refer to the first element within the array of
337 /// elements of type T. This is an array of unknown size.
338 void addUnsizedArrayUnchecked(QualType ElemTy) {
339 PathEntry Entry;
340 Entry.ArrayIndex = 0;
341 Entries.push_back(Entry);
342
343 MostDerivedType = ElemTy;
344 MostDerivedIsArrayElement = true;
345 // The value in MostDerivedArraySize is undefined in this case. So, set it
346 // to an arbitrary value that's likely to loudly break things if it's
347 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000348 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000349 MostDerivedPathLength = Entries.size();
350 }
Richard Smith96e0c102011-11-04 02:25:55 +0000351 /// Update this designator to refer to the given base or member of this
352 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000353 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000354 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000355 APValue::BaseOrMemberType Value(D, Virtual);
356 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000357 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000358
359 // If this isn't a base class, it's a new most-derived object.
360 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
361 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000362 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000363 MostDerivedArraySize = 0;
364 MostDerivedPathLength = Entries.size();
365 }
Richard Smith96e0c102011-11-04 02:25:55 +0000366 }
Richard Smith66c96992012-02-18 22:04:06 +0000367 /// Update this designator to refer to the given complex component.
368 void addComplexUnchecked(QualType EltTy, bool Imag) {
369 PathEntry Entry;
370 Entry.ArrayIndex = Imag;
371 Entries.push_back(Entry);
372
373 // This is technically a most-derived object, though in practice this
374 // is unlikely to matter.
375 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000376 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000377 MostDerivedArraySize = 2;
378 MostDerivedPathLength = Entries.size();
379 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000380 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000381 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
382 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000383 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000384 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
385 if (Invalid || !N) return;
386 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
387 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000388 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000389 // Can't verify -- trust that the user is doing the right thing (or if
390 // not, trust that the caller will catch the bad behavior).
391 // FIXME: Should we reject if this overflows, at least?
392 Entries.back().ArrayIndex += TruncatedN;
393 return;
394 }
395
396 // [expr.add]p4: For the purposes of these operators, a pointer to a
397 // nonarray object behaves the same as a pointer to the first element of
398 // an array of length one with the type of the object as its element type.
399 bool IsArray = MostDerivedPathLength == Entries.size() &&
400 MostDerivedIsArrayElement;
401 uint64_t ArrayIndex =
402 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
403 uint64_t ArraySize =
404 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
405
406 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
407 // Calculate the actual index in a wide enough type, so we can include
408 // it in the note.
409 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
410 (llvm::APInt&)N += ArrayIndex;
411 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
412 diagnosePointerArithmetic(Info, E, N);
413 setInvalid();
414 return;
415 }
416
417 ArrayIndex += TruncatedN;
418 assert(ArrayIndex <= ArraySize &&
419 "bounds check succeeded for out-of-bounds index");
420
421 if (IsArray)
422 Entries.back().ArrayIndex = ArrayIndex;
423 else
424 IsOnePastTheEnd = (ArrayIndex != 0);
425 }
Richard Smith96e0c102011-11-04 02:25:55 +0000426 };
427
Richard Smith254a73d2011-10-28 22:34:42 +0000428 /// A stack frame in the constexpr call stack.
429 struct CallStackFrame {
430 EvalInfo &Info;
431
432 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000433 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000434
Richard Smithf6f003a2011-12-16 19:06:07 +0000435 /// Callee - The function which was called.
436 const FunctionDecl *Callee;
437
Richard Smithd62306a2011-11-10 06:34:14 +0000438 /// This - The binding for the this pointer in this call, if any.
439 const LValue *This;
440
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000441 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000442 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000443 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000444
Eli Friedman4830ec82012-06-25 21:21:08 +0000445 // Note that we intentionally use std::map here so that references to
446 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000447 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000448 typedef MapTy::const_iterator temp_iterator;
449 /// Temporaries - Temporary lvalues materialized within this stack frame.
450 MapTy Temporaries;
451
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000452 /// CallLoc - The location of the call expression for this call.
453 SourceLocation CallLoc;
454
455 /// Index - The call index of this call.
456 unsigned Index;
457
Faisal Vali051e3a22017-02-16 04:12:21 +0000458 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
459 // on the overall stack usage of deeply-recursing constexpr evaluataions.
460 // (We should cache this map rather than recomputing it repeatedly.)
461 // But let's try this and see how it goes; we can look into caching the map
462 // as a later change.
463
464 /// LambdaCaptureFields - Mapping from captured variables/this to
465 /// corresponding data members in the closure class.
466 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
467 FieldDecl *LambdaThisCaptureField;
468
Richard Smithf6f003a2011-12-16 19:06:07 +0000469 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
470 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000471 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000472 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000473
474 APValue *getTemporary(const void *Key) {
475 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000476 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000477 }
478 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000479 };
480
Richard Smith852c9db2013-04-20 22:23:05 +0000481 /// Temporarily override 'this'.
482 class ThisOverrideRAII {
483 public:
484 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
485 : Frame(Frame), OldThis(Frame.This) {
486 if (Enable)
487 Frame.This = NewThis;
488 }
489 ~ThisOverrideRAII() {
490 Frame.This = OldThis;
491 }
492 private:
493 CallStackFrame &Frame;
494 const LValue *OldThis;
495 };
496
Richard Smith92b1ce02011-12-12 09:28:41 +0000497 /// A partial diagnostic which we might know in advance that we are not going
498 /// to emit.
499 class OptionalDiagnostic {
500 PartialDiagnostic *Diag;
501
502 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000503 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
504 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000505
506 template<typename T>
507 OptionalDiagnostic &operator<<(const T &v) {
508 if (Diag)
509 *Diag << v;
510 return *this;
511 }
Richard Smithfe800032012-01-31 04:08:20 +0000512
513 OptionalDiagnostic &operator<<(const APSInt &I) {
514 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000515 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000516 I.toString(Buffer);
517 *Diag << StringRef(Buffer.data(), Buffer.size());
518 }
519 return *this;
520 }
521
522 OptionalDiagnostic &operator<<(const APFloat &F) {
523 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000524 // FIXME: Force the precision of the source value down so we don't
525 // print digits which are usually useless (we don't really care here if
526 // we truncate a digit by accident in edge cases). Ideally,
Daniel Jasperffdee092017-05-02 19:21:42 +0000527 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000528 // representation which rounds to the correct value, but it's a bit
529 // tricky to implement.
530 unsigned precision =
531 llvm::APFloat::semanticsPrecision(F.getSemantics());
532 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000533 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000534 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000535 *Diag << StringRef(Buffer.data(), Buffer.size());
536 }
537 return *this;
538 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000539 };
540
Richard Smith08d6a2c2013-07-24 07:11:57 +0000541 /// A cleanup, and a flag indicating whether it is lifetime-extended.
542 class Cleanup {
543 llvm::PointerIntPair<APValue*, 1, bool> Value;
544
545 public:
546 Cleanup(APValue *Val, bool IsLifetimeExtended)
547 : Value(Val, IsLifetimeExtended) {}
548
549 bool isLifetimeExtended() const { return Value.getInt(); }
550 void endLifetime() {
551 *Value.getPointer() = APValue();
552 }
553 };
554
Richard Smithb228a862012-02-15 02:18:13 +0000555 /// EvalInfo - This is a private struct used by the evaluator to capture
556 /// information about a subexpression as it is folded. It retains information
557 /// about the AST context, but also maintains information about the folded
558 /// expression.
559 ///
560 /// If an expression could be evaluated, it is still possible it is not a C
561 /// "integer constant expression" or constant expression. If not, this struct
562 /// captures information about how and why not.
563 ///
564 /// One bit of information passed *into* the request for constant folding
565 /// indicates whether the subexpression is "evaluated" or not according to C
566 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
567 /// evaluate the expression regardless of what the RHS is, but C only allows
568 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000569 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000570 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000571
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000572 /// EvalStatus - Contains information about the evaluation.
573 Expr::EvalStatus &EvalStatus;
574
575 /// CurrentCall - The top of the constexpr call stack.
576 CallStackFrame *CurrentCall;
577
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000578 /// CallStackDepth - The number of calls in the call stack right now.
579 unsigned CallStackDepth;
580
Richard Smithb228a862012-02-15 02:18:13 +0000581 /// NextCallIndex - The next call index to assign.
582 unsigned NextCallIndex;
583
Richard Smitha3d3bd22013-05-08 02:12:03 +0000584 /// StepsLeft - The remaining number of evaluation steps we're permitted
585 /// to perform. This is essentially a limit for the number of statements
586 /// we will evaluate.
587 unsigned StepsLeft;
588
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000589 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000590 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000591 CallStackFrame BottomFrame;
592
Richard Smith08d6a2c2013-07-24 07:11:57 +0000593 /// A stack of values whose lifetimes end at the end of some surrounding
594 /// evaluation frame.
595 llvm::SmallVector<Cleanup, 16> CleanupStack;
596
Richard Smithd62306a2011-11-10 06:34:14 +0000597 /// EvaluatingDecl - This is the declaration whose initializer is being
598 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000599 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000600
601 /// EvaluatingDeclValue - This is the value being constructed for the
602 /// declaration whose initializer is being evaluated, if any.
603 APValue *EvaluatingDeclValue;
604
Erik Pilkington42925492017-10-04 00:18:55 +0000605 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
606 /// the call index that that lvalue was allocated in.
607 typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject;
608
609 /// EvaluatingConstructors - Set of objects that are currently being
610 /// constructed.
611 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
612
613 struct EvaluatingConstructorRAII {
614 EvalInfo &EI;
615 EvaluatingObject Object;
616 bool DidInsert;
617 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
618 : EI(EI), Object(Object) {
619 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
620 }
621 ~EvaluatingConstructorRAII() {
622 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
623 }
624 };
625
626 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) {
627 return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex));
628 }
629
Richard Smith410306b2016-12-12 02:53:20 +0000630 /// The current array initialization index, if we're performing array
631 /// initialization.
632 uint64_t ArrayInitIndex = -1;
633
Richard Smith357362d2011-12-13 06:39:58 +0000634 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
635 /// notes attached to it will also be stored, otherwise they will not be.
636 bool HasActiveDiagnostic;
637
Richard Smith0c6124b2015-12-03 01:36:22 +0000638 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
639 /// fold (not just why it's not strictly a constant expression)?
640 bool HasFoldFailureDiagnostic;
641
George Burgess IV8c892b52016-05-25 22:31:54 +0000642 /// \brief Whether or not we're currently speculatively evaluating.
643 bool IsSpeculativelyEvaluating;
644
Richard Smith6d4c6582013-11-05 22:18:15 +0000645 enum EvaluationMode {
646 /// Evaluate as a constant expression. Stop if we find that the expression
647 /// is not a constant expression.
648 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000649
Richard Smith6d4c6582013-11-05 22:18:15 +0000650 /// Evaluate as a potential constant expression. Keep going if we hit a
651 /// construct that we can't evaluate yet (because we don't yet know the
652 /// value of something) but stop if we hit something that could never be
653 /// a constant expression.
654 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000655
Richard Smith6d4c6582013-11-05 22:18:15 +0000656 /// Fold the expression to a constant. Stop if we hit a side-effect that
657 /// we can't model.
658 EM_ConstantFold,
659
660 /// Evaluate the expression looking for integer overflow and similar
661 /// issues. Don't worry about side-effects, and try to visit all
662 /// subexpressions.
663 EM_EvaluateForOverflow,
664
665 /// Evaluate in any way we know how. Don't worry about side-effects that
666 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000667 EM_IgnoreSideEffects,
668
669 /// Evaluate as a constant expression. Stop if we find that the expression
670 /// is not a constant expression. Some expressions can be retried in the
671 /// optimizer if we don't constant fold them here, but in an unevaluated
672 /// context we try to fold them immediately since the optimizer never
673 /// gets a chance to look at it.
674 EM_ConstantExpressionUnevaluated,
675
676 /// Evaluate as a potential constant expression. Keep going if we hit a
677 /// construct that we can't evaluate yet (because we don't yet know the
678 /// value of something) but stop if we hit something that could never be
679 /// a constant expression. Some expressions can be retried in the
680 /// optimizer if we don't constant fold them here, but in an unevaluated
681 /// context we try to fold them immediately since the optimizer never
682 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000683 EM_PotentialConstantExpressionUnevaluated,
684
George Burgess IVf9013bf2017-02-10 22:52:29 +0000685 /// Evaluate as a constant expression. In certain scenarios, if:
686 /// - we find a MemberExpr with a base that can't be evaluated, or
687 /// - we find a variable initialized with a call to a function that has
688 /// the alloc_size attribute on it
689 /// then we may consider evaluation to have succeeded.
690 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000691 /// In either case, the LValue returned shall have an invalid base; in the
692 /// former, the base will be the invalid MemberExpr, in the latter, the
693 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
694 /// said CallExpr.
695 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000696 } EvalMode;
697
698 /// Are we checking whether the expression is a potential constant
699 /// expression?
700 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000701 return EvalMode == EM_PotentialConstantExpression ||
702 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000703 }
704
705 /// Are we checking an expression for overflow?
706 // FIXME: We should check for any kind of undefined or suspicious behavior
707 // in such constructs, not just overflow.
708 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
709
710 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000711 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000712 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000713 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000714 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
715 EvaluatingDecl((const ValueDecl *)nullptr),
716 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000717 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
718 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000719
Richard Smith7525ff62013-05-09 07:14:00 +0000720 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
721 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000722 EvaluatingDeclValue = &Value;
Erik Pilkington42925492017-10-04 00:18:55 +0000723 EvaluatingConstructors.insert({Base, 0});
Richard Smithd62306a2011-11-10 06:34:14 +0000724 }
725
David Blaikiebbafb8a2012-03-11 07:00:24 +0000726 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000727
Richard Smith357362d2011-12-13 06:39:58 +0000728 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000729 // Don't perform any constexpr calls (other than the call we're checking)
730 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000731 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000732 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000733 if (NextCallIndex == 0) {
734 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000735 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000736 return false;
737 }
Richard Smith357362d2011-12-13 06:39:58 +0000738 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
739 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000740 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000741 << getLangOpts().ConstexprCallDepth;
742 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000743 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000744
Richard Smithb228a862012-02-15 02:18:13 +0000745 CallStackFrame *getCallFrame(unsigned CallIndex) {
746 assert(CallIndex && "no call index in getCallFrame");
747 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
748 // be null in this loop.
749 CallStackFrame *Frame = CurrentCall;
750 while (Frame->Index > CallIndex)
751 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000752 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000753 }
754
Richard Smitha3d3bd22013-05-08 02:12:03 +0000755 bool nextStep(const Stmt *S) {
756 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000757 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000758 return false;
759 }
760 --StepsLeft;
761 return true;
762 }
763
Richard Smith357362d2011-12-13 06:39:58 +0000764 private:
765 /// Add a diagnostic to the diagnostics list.
766 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
767 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
768 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
769 return EvalStatus.Diag->back().second;
770 }
771
Richard Smithf6f003a2011-12-16 19:06:07 +0000772 /// Add notes containing a call stack to the current point of evaluation.
773 void addCallStack(unsigned Limit);
774
Faisal Valie690b7a2016-07-02 22:34:24 +0000775 private:
776 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
777 unsigned ExtraNotes, bool IsCCEDiag) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000778
Richard Smith92b1ce02011-12-12 09:28:41 +0000779 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000780 // If we have a prior diagnostic, it will be noting that the expression
781 // isn't a constant expression. This diagnostic is more important,
782 // unless we require this evaluation to produce a constant expression.
783 //
784 // FIXME: We might want to show both diagnostics to the user in
785 // EM_ConstantFold mode.
786 if (!EvalStatus.Diag->empty()) {
787 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000788 case EM_ConstantFold:
789 case EM_IgnoreSideEffects:
790 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000791 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000792 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000793 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000794 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000795 case EM_ConstantExpression:
796 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000797 case EM_ConstantExpressionUnevaluated:
798 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000799 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000800 HasActiveDiagnostic = false;
801 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000802 }
803 }
804
Richard Smithf6f003a2011-12-16 19:06:07 +0000805 unsigned CallStackNotes = CallStackDepth - 1;
806 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
807 if (Limit)
808 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000809 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000810 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000811
Richard Smith357362d2011-12-13 06:39:58 +0000812 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000813 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000814 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000815 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
816 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000817 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000818 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000819 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000820 }
Richard Smith357362d2011-12-13 06:39:58 +0000821 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000822 return OptionalDiagnostic();
823 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000824 public:
825 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
826 OptionalDiagnostic
827 FFDiag(SourceLocation Loc,
828 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
829 unsigned ExtraNotes = 0) {
830 return Diag(Loc, DiagId, ExtraNotes, false);
831 }
Daniel Jasperffdee092017-05-02 19:21:42 +0000832
Faisal Valie690b7a2016-07-02 22:34:24 +0000833 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000834 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000835 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000836 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000837 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000838 HasActiveDiagnostic = false;
839 return OptionalDiagnostic();
840 }
841
Richard Smith92b1ce02011-12-12 09:28:41 +0000842 /// Diagnose that the evaluation does not produce a C++11 core constant
843 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000844 ///
845 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
846 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000847 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000848 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000849 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000850 // Don't override a previous diagnostic. Don't bother collecting
851 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000852 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000853 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000854 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000855 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000856 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000857 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000858 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
859 = diag::note_invalid_subexpr_in_const_expr,
860 unsigned ExtraNotes = 0) {
861 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
862 }
Richard Smith357362d2011-12-13 06:39:58 +0000863 /// Add a note to a prior diagnostic.
864 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
865 if (!HasActiveDiagnostic)
866 return OptionalDiagnostic();
867 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000868 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000869
870 /// Add a stack of notes to a prior diagnostic.
871 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
872 if (HasActiveDiagnostic) {
873 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
874 Diags.begin(), Diags.end());
875 }
876 }
Richard Smith253c2a32012-01-27 01:14:48 +0000877
Richard Smith6d4c6582013-11-05 22:18:15 +0000878 /// Should we continue evaluation after encountering a side-effect that we
879 /// couldn't model?
880 bool keepEvaluatingAfterSideEffect() {
881 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000882 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000883 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000884 case EM_EvaluateForOverflow:
885 case EM_IgnoreSideEffects:
886 return true;
887
Richard Smith6d4c6582013-11-05 22:18:15 +0000888 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000889 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000890 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000891 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000892 return false;
893 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000894 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000895 }
896
897 /// Note that we have had a side-effect, and determine whether we should
898 /// keep evaluating.
899 bool noteSideEffect() {
900 EvalStatus.HasSideEffects = true;
901 return keepEvaluatingAfterSideEffect();
902 }
903
Richard Smithce8eca52015-12-08 03:21:47 +0000904 /// Should we continue evaluation after encountering undefined behavior?
905 bool keepEvaluatingAfterUndefinedBehavior() {
906 switch (EvalMode) {
907 case EM_EvaluateForOverflow:
908 case EM_IgnoreSideEffects:
909 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000910 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000911 return true;
912
913 case EM_PotentialConstantExpression:
914 case EM_PotentialConstantExpressionUnevaluated:
915 case EM_ConstantExpression:
916 case EM_ConstantExpressionUnevaluated:
917 return false;
918 }
919 llvm_unreachable("Missed EvalMode case");
920 }
921
922 /// Note that we hit something that was technically undefined behavior, but
923 /// that we can evaluate past it (such as signed overflow or floating-point
924 /// division by zero.)
925 bool noteUndefinedBehavior() {
926 EvalStatus.HasUndefinedBehavior = true;
927 return keepEvaluatingAfterUndefinedBehavior();
928 }
929
Richard Smith253c2a32012-01-27 01:14:48 +0000930 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000931 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000932 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000933 if (!StepsLeft)
934 return false;
935
936 switch (EvalMode) {
937 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000938 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000939 case EM_EvaluateForOverflow:
940 return true;
941
942 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000943 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000944 case EM_ConstantFold:
945 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000946 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000947 return false;
948 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000949 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000950 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000951
George Burgess IV8c892b52016-05-25 22:31:54 +0000952 /// Notes that we failed to evaluate an expression that other expressions
953 /// directly depend on, and determine if we should keep evaluating. This
954 /// should only be called if we actually intend to keep evaluating.
955 ///
956 /// Call noteSideEffect() instead if we may be able to ignore the value that
957 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
958 ///
959 /// (Foo(), 1) // use noteSideEffect
960 /// (Foo() || true) // use noteSideEffect
961 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000962 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000963 // Failure when evaluating some expression often means there is some
964 // subexpression whose evaluation was skipped. Therefore, (because we
965 // don't track whether we skipped an expression when unwinding after an
966 // evaluation failure) every evaluation failure that bubbles up from a
967 // subexpression implies that a side-effect has potentially happened. We
968 // skip setting the HasSideEffects flag to true until we decide to
969 // continue evaluating after that point, which happens here.
970 bool KeepGoing = keepEvaluatingAfterFailure();
971 EvalStatus.HasSideEffects |= KeepGoing;
972 return KeepGoing;
973 }
974
Richard Smith410306b2016-12-12 02:53:20 +0000975 class ArrayInitLoopIndex {
976 EvalInfo &Info;
977 uint64_t OuterIndex;
978
979 public:
980 ArrayInitLoopIndex(EvalInfo &Info)
981 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
982 Info.ArrayInitIndex = 0;
983 }
984 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
985
986 operator uint64_t&() { return Info.ArrayInitIndex; }
987 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000988 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000989
990 /// Object used to treat all foldable expressions as constant expressions.
991 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000992 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000993 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000994 bool HadNoPriorDiags;
995 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000996
Richard Smith6d4c6582013-11-05 22:18:15 +0000997 explicit FoldConstant(EvalInfo &Info, bool Enabled)
998 : Info(Info),
999 Enabled(Enabled),
1000 HadNoPriorDiags(Info.EvalStatus.Diag &&
1001 Info.EvalStatus.Diag->empty() &&
1002 !Info.EvalStatus.HasSideEffects),
1003 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001004 if (Enabled &&
1005 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1006 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001007 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001008 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001009 void keepDiagnostics() { Enabled = false; }
1010 ~FoldConstant() {
1011 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001012 !Info.EvalStatus.HasSideEffects)
1013 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001014 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001015 }
1016 };
Richard Smith17100ba2012-02-16 02:46:34 +00001017
George Burgess IV3a03fab2015-09-04 21:28:13 +00001018 /// RAII object used to treat the current evaluation as the correct pointer
1019 /// offset fold for the current EvalMode
1020 struct FoldOffsetRAII {
1021 EvalInfo &Info;
1022 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +00001023 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001024 : Info(Info), OldMode(Info.EvalMode) {
1025 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +00001026 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001027 }
1028
1029 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1030 };
1031
George Burgess IV8c892b52016-05-25 22:31:54 +00001032 /// RAII object used to optionally suppress diagnostics and side-effects from
1033 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001034 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001035 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001036 Expr::EvalStatus OldStatus;
1037 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001038
George Burgess IV8c892b52016-05-25 22:31:54 +00001039 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001040 Info = Other.Info;
1041 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001042 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001043 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001044 }
1045
1046 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001047 if (!Info)
1048 return;
1049
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001050 Info->EvalStatus = OldStatus;
1051 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001052 }
1053
Richard Smith17100ba2012-02-16 02:46:34 +00001054 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001055 SpeculativeEvaluationRAII() = default;
1056
1057 SpeculativeEvaluationRAII(
1058 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001059 : Info(&Info), OldStatus(Info.EvalStatus),
1060 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001061 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001062 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001063 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001064
1065 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1066 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1067 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001068 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001069
1070 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1071 maybeRestoreState();
1072 moveFromAndCancel(std::move(Other));
1073 return *this;
1074 }
1075
1076 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001077 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001078
1079 /// RAII object wrapping a full-expression or block scope, and handling
1080 /// the ending of the lifetime of temporaries created within it.
1081 template<bool IsFullExpression>
1082 class ScopeRAII {
1083 EvalInfo &Info;
1084 unsigned OldStackSize;
1085 public:
1086 ScopeRAII(EvalInfo &Info)
1087 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1088 ~ScopeRAII() {
1089 // Body moved to a static method to encourage the compiler to inline away
1090 // instances of this class.
1091 cleanup(Info, OldStackSize);
1092 }
1093 private:
1094 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1095 unsigned NewEnd = OldStackSize;
1096 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1097 I != N; ++I) {
1098 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1099 // Full-expression cleanup of a lifetime-extended temporary: nothing
1100 // to do, just move this cleanup to the right place in the stack.
1101 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1102 ++NewEnd;
1103 } else {
1104 // End the lifetime of the object.
1105 Info.CleanupStack[I].endLifetime();
1106 }
1107 }
1108 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1109 Info.CleanupStack.end());
1110 }
1111 };
1112 typedef ScopeRAII<false> BlockScopeRAII;
1113 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001114}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001115
Richard Smitha8105bc2012-01-06 16:39:00 +00001116bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1117 CheckSubobjectKind CSK) {
1118 if (Invalid)
1119 return false;
1120 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001121 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001122 << CSK;
1123 setInvalid();
1124 return false;
1125 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001126 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1127 // must actually be at least one array element; even a VLA cannot have a
1128 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001129 return true;
1130}
1131
Richard Smith6f4f0f12017-10-20 22:56:25 +00001132void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1133 const Expr *E) {
1134 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1135 // Do not set the designator as invalid: we can represent this situation,
1136 // and correct handling of __builtin_object_size requires us to do so.
1137}
1138
Richard Smitha8105bc2012-01-06 16:39:00 +00001139void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001140 const Expr *E,
1141 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001142 // If we're complaining, we must be able to statically determine the size of
1143 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001144 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001145 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001146 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001147 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001148 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001149 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001150 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001151 setInvalid();
1152}
1153
Richard Smithf6f003a2011-12-16 19:06:07 +00001154CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1155 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001156 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001157 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1158 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001159 Info.CurrentCall = this;
1160 ++Info.CallStackDepth;
1161}
1162
1163CallStackFrame::~CallStackFrame() {
1164 assert(Info.CurrentCall == this && "calls retired out of order");
1165 --Info.CallStackDepth;
1166 Info.CurrentCall = Caller;
1167}
1168
Richard Smith08d6a2c2013-07-24 07:11:57 +00001169APValue &CallStackFrame::createTemporary(const void *Key,
1170 bool IsLifetimeExtended) {
1171 APValue &Result = Temporaries[Key];
1172 assert(Result.isUninit() && "temporary created multiple times");
1173 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1174 return Result;
1175}
1176
Richard Smith84401042013-06-03 05:03:02 +00001177static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001178
1179void EvalInfo::addCallStack(unsigned Limit) {
1180 // Determine which calls to skip, if any.
1181 unsigned ActiveCalls = CallStackDepth - 1;
1182 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1183 if (Limit && Limit < ActiveCalls) {
1184 SkipStart = Limit / 2 + Limit % 2;
1185 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001186 }
1187
Richard Smithf6f003a2011-12-16 19:06:07 +00001188 // Walk the call stack and add the diagnostics.
1189 unsigned CallIdx = 0;
1190 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1191 Frame = Frame->Caller, ++CallIdx) {
1192 // Skip this call?
1193 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1194 if (CallIdx == SkipStart) {
1195 // Note that we're skipping calls.
1196 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1197 << unsigned(ActiveCalls - Limit);
1198 }
1199 continue;
1200 }
1201
Richard Smith5179eb72016-06-28 19:03:57 +00001202 // Use a different note for an inheriting constructor, because from the
1203 // user's perspective it's not really a function at all.
1204 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1205 if (CD->isInheritingConstructor()) {
1206 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1207 << CD->getParent();
1208 continue;
1209 }
1210 }
1211
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001212 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001213 llvm::raw_svector_ostream Out(Buffer);
1214 describeCall(Frame, Out);
1215 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1216 }
1217}
1218
1219namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001220 struct ComplexValue {
1221 private:
1222 bool IsInt;
1223
1224 public:
1225 APSInt IntReal, IntImag;
1226 APFloat FloatReal, FloatImag;
1227
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001228 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001229
1230 void makeComplexFloat() { IsInt = false; }
1231 bool isComplexFloat() const { return !IsInt; }
1232 APFloat &getComplexFloatReal() { return FloatReal; }
1233 APFloat &getComplexFloatImag() { return FloatImag; }
1234
1235 void makeComplexInt() { IsInt = true; }
1236 bool isComplexInt() const { return IsInt; }
1237 APSInt &getComplexIntReal() { return IntReal; }
1238 APSInt &getComplexIntImag() { return IntImag; }
1239
Richard Smith2e312c82012-03-03 22:46:17 +00001240 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001241 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001242 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001243 else
Richard Smith2e312c82012-03-03 22:46:17 +00001244 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001245 }
Richard Smith2e312c82012-03-03 22:46:17 +00001246 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001247 assert(v.isComplexFloat() || v.isComplexInt());
1248 if (v.isComplexFloat()) {
1249 makeComplexFloat();
1250 FloatReal = v.getComplexFloatReal();
1251 FloatImag = v.getComplexFloatImag();
1252 } else {
1253 makeComplexInt();
1254 IntReal = v.getComplexIntReal();
1255 IntImag = v.getComplexIntImag();
1256 }
1257 }
John McCall93d91dc2010-05-07 17:22:02 +00001258 };
John McCall45d55e42010-05-07 21:00:08 +00001259
1260 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001261 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001262 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001263 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001264 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001265 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001266 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001267
Richard Smithce40ad62011-11-12 22:28:03 +00001268 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001269 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001270 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001271 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001272 SubobjectDesignator &getLValueDesignator() { return Designator; }
1273 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001274 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001275
Richard Smith2e312c82012-03-03 22:46:17 +00001276 void moveInto(APValue &V) const {
1277 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001278 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1279 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001280 else {
1281 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001282 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001283 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001284 }
John McCall45d55e42010-05-07 21:00:08 +00001285 }
Richard Smith2e312c82012-03-03 22:46:17 +00001286 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001287 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001288 Base = V.getLValueBase();
1289 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001290 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001291 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001292 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001293 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001294 }
1295
Tim Northover01503332017-05-26 02:16:00 +00001296 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001297#ifndef NDEBUG
1298 // We only allow a few types of invalid bases. Enforce that here.
1299 if (BInvalid) {
1300 const auto *E = B.get<const Expr *>();
1301 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1302 "Unexpected type of invalid base");
1303 }
1304#endif
1305
Richard Smithce40ad62011-11-12 22:28:03 +00001306 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001307 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001308 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001309 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001310 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001311 IsNullPtr = false;
1312 }
1313
1314 void setNull(QualType PointerTy, uint64_t TargetVal) {
1315 Base = (Expr *)nullptr;
1316 Offset = CharUnits::fromQuantity(TargetVal);
1317 InvalidBase = false;
1318 CallIndex = 0;
1319 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1320 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001321 }
1322
George Burgess IV3a03fab2015-09-04 21:28:13 +00001323 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1324 set(B, I, true);
1325 }
1326
Richard Smitha8105bc2012-01-06 16:39:00 +00001327 // Check that this LValue is not based on a null pointer. If it is, produce
1328 // a diagnostic and mark the designator as invalid.
1329 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1330 CheckSubobjectKind CSK) {
1331 if (Designator.Invalid)
1332 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001333 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001334 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001335 << CSK;
1336 Designator.setInvalid();
1337 return false;
1338 }
1339 return true;
1340 }
1341
1342 // Check this LValue refers to an object. If not, set the designator to be
1343 // invalid and emit a diagnostic.
1344 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001345 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001346 Designator.checkSubobject(Info, E, CSK);
1347 }
1348
1349 void addDecl(EvalInfo &Info, const Expr *E,
1350 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001351 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1352 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001353 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001354 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1355 if (!Designator.Entries.empty()) {
1356 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1357 Designator.setInvalid();
1358 return;
1359 }
Richard Smithefdb5032017-11-15 03:03:56 +00001360 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1361 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1362 Designator.FirstEntryIsAnUnsizedArray = true;
1363 Designator.addUnsizedArrayUnchecked(ElemTy);
1364 }
George Burgess IVe3763372016-12-22 02:50:20 +00001365 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001366 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001367 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1368 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001369 }
Richard Smith66c96992012-02-18 22:04:06 +00001370 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001371 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1372 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001373 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001374 void clearIsNullPointer() {
1375 IsNullPtr = false;
1376 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001377 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1378 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001379 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1380 // but we're not required to diagnose it and it's valid in C++.)
1381 if (!Index)
1382 return;
1383
1384 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1385 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1386 // offsets.
1387 uint64_t Offset64 = Offset.getQuantity();
1388 uint64_t ElemSize64 = ElementSize.getQuantity();
1389 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1390 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1391
1392 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001393 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001394 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001395 }
1396 void adjustOffset(CharUnits N) {
1397 Offset += N;
1398 if (N.getQuantity())
1399 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001400 }
John McCall45d55e42010-05-07 21:00:08 +00001401 };
Richard Smith027bf112011-11-17 22:56:20 +00001402
1403 struct MemberPtr {
1404 MemberPtr() {}
1405 explicit MemberPtr(const ValueDecl *Decl) :
1406 DeclAndIsDerivedMember(Decl, false), Path() {}
1407
1408 /// The member or (direct or indirect) field referred to by this member
1409 /// pointer, or 0 if this is a null member pointer.
1410 const ValueDecl *getDecl() const {
1411 return DeclAndIsDerivedMember.getPointer();
1412 }
1413 /// Is this actually a member of some type derived from the relevant class?
1414 bool isDerivedMember() const {
1415 return DeclAndIsDerivedMember.getInt();
1416 }
1417 /// Get the class which the declaration actually lives in.
1418 const CXXRecordDecl *getContainingRecord() const {
1419 return cast<CXXRecordDecl>(
1420 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1421 }
1422
Richard Smith2e312c82012-03-03 22:46:17 +00001423 void moveInto(APValue &V) const {
1424 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001425 }
Richard Smith2e312c82012-03-03 22:46:17 +00001426 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001427 assert(V.isMemberPointer());
1428 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1429 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1430 Path.clear();
1431 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1432 Path.insert(Path.end(), P.begin(), P.end());
1433 }
1434
1435 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1436 /// whether the member is a member of some class derived from the class type
1437 /// of the member pointer.
1438 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1439 /// Path - The path of base/derived classes from the member declaration's
1440 /// class (exclusive) to the class type of the member pointer (inclusive).
1441 SmallVector<const CXXRecordDecl*, 4> Path;
1442
1443 /// Perform a cast towards the class of the Decl (either up or down the
1444 /// hierarchy).
1445 bool castBack(const CXXRecordDecl *Class) {
1446 assert(!Path.empty());
1447 const CXXRecordDecl *Expected;
1448 if (Path.size() >= 2)
1449 Expected = Path[Path.size() - 2];
1450 else
1451 Expected = getContainingRecord();
1452 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1453 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1454 // if B does not contain the original member and is not a base or
1455 // derived class of the class containing the original member, the result
1456 // of the cast is undefined.
1457 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1458 // (D::*). We consider that to be a language defect.
1459 return false;
1460 }
1461 Path.pop_back();
1462 return true;
1463 }
1464 /// Perform a base-to-derived member pointer cast.
1465 bool castToDerived(const CXXRecordDecl *Derived) {
1466 if (!getDecl())
1467 return true;
1468 if (!isDerivedMember()) {
1469 Path.push_back(Derived);
1470 return true;
1471 }
1472 if (!castBack(Derived))
1473 return false;
1474 if (Path.empty())
1475 DeclAndIsDerivedMember.setInt(false);
1476 return true;
1477 }
1478 /// Perform a derived-to-base member pointer cast.
1479 bool castToBase(const CXXRecordDecl *Base) {
1480 if (!getDecl())
1481 return true;
1482 if (Path.empty())
1483 DeclAndIsDerivedMember.setInt(true);
1484 if (isDerivedMember()) {
1485 Path.push_back(Base);
1486 return true;
1487 }
1488 return castBack(Base);
1489 }
1490 };
Richard Smith357362d2011-12-13 06:39:58 +00001491
Richard Smith7bb00672012-02-01 01:42:44 +00001492 /// Compare two member pointers, which are assumed to be of the same type.
1493 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1494 if (!LHS.getDecl() || !RHS.getDecl())
1495 return !LHS.getDecl() && !RHS.getDecl();
1496 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1497 return false;
1498 return LHS.Path == RHS.Path;
1499 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001500}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001501
Richard Smith2e312c82012-03-03 22:46:17 +00001502static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001503static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1504 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001505 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001506static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1507 bool InvalidBaseOK = false);
1508static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1509 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001510static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1511 EvalInfo &Info);
1512static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001513static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001514static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001515 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001516static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001517static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001518static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1519 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001520static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001521
1522//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001523// Misc utilities
1524//===----------------------------------------------------------------------===//
1525
Richard Smithd6cc1982017-01-31 02:23:02 +00001526/// Negate an APSInt in place, converting it to a signed form if necessary, and
1527/// preserving its value (by extending by up to one bit as needed).
1528static void negateAsSigned(APSInt &Int) {
1529 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1530 Int = Int.extend(Int.getBitWidth() + 1);
1531 Int.setIsSigned(true);
1532 }
1533 Int = -Int;
1534}
1535
Richard Smith84401042013-06-03 05:03:02 +00001536/// Produce a string describing the given constexpr call.
1537static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1538 unsigned ArgIndex = 0;
1539 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1540 !isa<CXXConstructorDecl>(Frame->Callee) &&
1541 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1542
1543 if (!IsMemberCall)
1544 Out << *Frame->Callee << '(';
1545
1546 if (Frame->This && IsMemberCall) {
1547 APValue Val;
1548 Frame->This->moveInto(Val);
1549 Val.printPretty(Out, Frame->Info.Ctx,
1550 Frame->This->Designator.MostDerivedType);
1551 // FIXME: Add parens around Val if needed.
1552 Out << "->" << *Frame->Callee << '(';
1553 IsMemberCall = false;
1554 }
1555
1556 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1557 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1558 if (ArgIndex > (unsigned)IsMemberCall)
1559 Out << ", ";
1560
1561 const ParmVarDecl *Param = *I;
1562 const APValue &Arg = Frame->Arguments[ArgIndex];
1563 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1564
1565 if (ArgIndex == 0 && IsMemberCall)
1566 Out << "->" << *Frame->Callee << '(';
1567 }
1568
1569 Out << ')';
1570}
1571
Richard Smithd9f663b2013-04-22 15:31:51 +00001572/// Evaluate an expression to see if it had side-effects, and discard its
1573/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001574/// \return \c true if the caller should keep evaluating.
1575static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001576 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001577 if (!Evaluate(Scratch, Info, E))
1578 // We don't need the value, but we might have skipped a side effect here.
1579 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001580 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001581}
1582
Richard Smithd62306a2011-11-10 06:34:14 +00001583/// Should this call expression be treated as a string literal?
1584static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001585 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001586 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1587 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1588}
1589
Richard Smithce40ad62011-11-12 22:28:03 +00001590static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001591 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1592 // constant expression of pointer type that evaluates to...
1593
1594 // ... a null pointer value, or a prvalue core constant expression of type
1595 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001596 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001597
Richard Smithce40ad62011-11-12 22:28:03 +00001598 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1599 // ... the address of an object with static storage duration,
1600 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1601 return VD->hasGlobalStorage();
1602 // ... the address of a function,
1603 return isa<FunctionDecl>(D);
1604 }
1605
1606 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001607 switch (E->getStmtClass()) {
1608 default:
1609 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001610 case Expr::CompoundLiteralExprClass: {
1611 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1612 return CLE->isFileScope() && CLE->isLValue();
1613 }
Richard Smithe6c01442013-06-05 00:46:14 +00001614 case Expr::MaterializeTemporaryExprClass:
1615 // A materialized temporary might have been lifetime-extended to static
1616 // storage duration.
1617 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001618 // A string literal has static storage duration.
1619 case Expr::StringLiteralClass:
1620 case Expr::PredefinedExprClass:
1621 case Expr::ObjCStringLiteralClass:
1622 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001623 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001624 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001625 return true;
1626 case Expr::CallExprClass:
1627 return IsStringLiteralCall(cast<CallExpr>(E));
1628 // For GCC compatibility, &&label has static storage duration.
1629 case Expr::AddrLabelExprClass:
1630 return true;
1631 // A Block literal expression may be used as the initialization value for
1632 // Block variables at global or local static scope.
1633 case Expr::BlockExprClass:
1634 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001635 case Expr::ImplicitValueInitExprClass:
1636 // FIXME:
1637 // We can never form an lvalue with an implicit value initialization as its
1638 // base through expression evaluation, so these only appear in one case: the
1639 // implicit variable declaration we invent when checking whether a constexpr
1640 // constructor can produce a constant expression. We must assume that such
1641 // an expression might be a global lvalue.
1642 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001643 }
John McCall95007602010-05-10 23:27:23 +00001644}
1645
Richard Smithb228a862012-02-15 02:18:13 +00001646static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1647 assert(Base && "no location for a null lvalue");
1648 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1649 if (VD)
1650 Info.Note(VD->getLocation(), diag::note_declared_at);
1651 else
Ted Kremenek28831752012-08-23 20:46:57 +00001652 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001653 diag::note_constexpr_temporary_here);
1654}
1655
Richard Smith80815602011-11-07 05:07:52 +00001656/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001657/// value for an address or reference constant expression. Return true if we
1658/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001659static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1660 QualType Type, const LValue &LVal) {
1661 bool IsReferenceType = Type->isReferenceType();
1662
Richard Smith357362d2011-12-13 06:39:58 +00001663 APValue::LValueBase Base = LVal.getLValueBase();
1664 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1665
Richard Smith0dea49e2012-02-18 04:58:18 +00001666 // Check that the object is a global. Note that the fake 'this' object we
1667 // manufacture when checking potential constant expressions is conservatively
1668 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001669 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001670 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001671 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001672 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001673 << IsReferenceType << !Designator.Entries.empty()
1674 << !!VD << VD;
1675 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001676 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001677 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001678 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001679 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001680 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001681 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001682 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001683 LVal.getLValueCallIndex() == 0) &&
1684 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001685
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001686 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1687 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001688 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001689 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001690 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001691
Hans Wennborg82dd8772014-06-25 22:19:48 +00001692 // A dllimport variable never acts like a constant.
1693 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001694 return false;
1695 }
1696 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1697 // __declspec(dllimport) must be handled very carefully:
1698 // We must never initialize an expression with the thunk in C++.
1699 // Doing otherwise would allow the same id-expression to yield
1700 // different addresses for the same function in different translation
1701 // units. However, this means that we must dynamically initialize the
1702 // expression with the contents of the import address table at runtime.
1703 //
1704 // The C language has no notion of ODR; furthermore, it has no notion of
1705 // dynamic initialization. This means that we are permitted to
1706 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001707 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001708 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001709 }
1710 }
1711
Richard Smitha8105bc2012-01-06 16:39:00 +00001712 // Allow address constant expressions to be past-the-end pointers. This is
1713 // an extension: the standard requires them to point to an object.
1714 if (!IsReferenceType)
1715 return true;
1716
1717 // A reference constant expression must refer to an object.
1718 if (!Base) {
1719 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001720 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001721 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001722 }
1723
Richard Smith357362d2011-12-13 06:39:58 +00001724 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001725 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001726 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001727 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001728 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001729 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001730 }
1731
Richard Smith80815602011-11-07 05:07:52 +00001732 return true;
1733}
1734
Reid Klecknercd016d82017-07-07 22:04:29 +00001735/// Member pointers are constant expressions unless they point to a
1736/// non-virtual dllimport member function.
1737static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1738 SourceLocation Loc,
1739 QualType Type,
1740 const APValue &Value) {
1741 const ValueDecl *Member = Value.getMemberPointerDecl();
1742 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1743 if (!FD)
1744 return true;
1745 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1746}
1747
Richard Smithfddd3842011-12-30 21:15:51 +00001748/// Check that this core constant expression is of literal type, and if not,
1749/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001750static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001751 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001752 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001753 return true;
1754
Richard Smith7525ff62013-05-09 07:14:00 +00001755 // C++1y: A constant initializer for an object o [...] may also invoke
1756 // constexpr constructors for o and its subobjects even if those objects
1757 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001758 //
1759 // C++11 missed this detail for aggregates, so classes like this:
1760 // struct foo_t { union { int i; volatile int j; } u; };
1761 // are not (obviously) initializable like so:
1762 // __attribute__((__require_constant_initialization__))
1763 // static const foo_t x = {{0}};
1764 // because "i" is a subobject with non-literal initialization (due to the
1765 // volatile member of the union). See:
1766 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1767 // Therefore, we use the C++1y behavior.
1768 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001769 return true;
1770
Richard Smithfddd3842011-12-30 21:15:51 +00001771 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001772 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001773 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001774 << E->getType();
1775 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001776 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001777 return false;
1778}
1779
Richard Smith0b0a0b62011-10-29 20:57:55 +00001780/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001781/// constant expression. If not, report an appropriate diagnostic. Does not
1782/// check that the expression is of literal type.
1783static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1784 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001785 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001786 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001787 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001788 return false;
1789 }
1790
Richard Smith77be48a2014-07-31 06:31:19 +00001791 // We allow _Atomic(T) to be initialized from anything that T can be
1792 // initialized from.
1793 if (const AtomicType *AT = Type->getAs<AtomicType>())
1794 Type = AT->getValueType();
1795
Richard Smithb228a862012-02-15 02:18:13 +00001796 // Core issue 1454: For a literal constant expression of array or class type,
1797 // each subobject of its value shall have been initialized by a constant
1798 // expression.
1799 if (Value.isArray()) {
1800 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1801 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1802 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1803 Value.getArrayInitializedElt(I)))
1804 return false;
1805 }
1806 if (!Value.hasArrayFiller())
1807 return true;
1808 return CheckConstantExpression(Info, DiagLoc, EltTy,
1809 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001810 }
Richard Smithb228a862012-02-15 02:18:13 +00001811 if (Value.isUnion() && Value.getUnionField()) {
1812 return CheckConstantExpression(Info, DiagLoc,
1813 Value.getUnionField()->getType(),
1814 Value.getUnionValue());
1815 }
1816 if (Value.isStruct()) {
1817 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1818 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1819 unsigned BaseIndex = 0;
1820 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1821 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1822 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1823 Value.getStructBase(BaseIndex)))
1824 return false;
1825 }
1826 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001827 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001828 if (I->isUnnamedBitfield())
1829 continue;
1830
David Blaikie2d7c57e2012-04-30 02:36:29 +00001831 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1832 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001833 return false;
1834 }
1835 }
1836
1837 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001838 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001839 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001840 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1841 }
1842
Reid Klecknercd016d82017-07-07 22:04:29 +00001843 if (Value.isMemberPointer())
1844 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1845
Richard Smithb228a862012-02-15 02:18:13 +00001846 // Everything else is fine.
1847 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001848}
1849
Benjamin Kramer8407df72015-03-09 16:47:52 +00001850static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001851 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001852}
1853
1854static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001855 if (Value.CallIndex)
1856 return false;
1857 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1858 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001859}
1860
Richard Smithcecf1842011-11-01 21:06:14 +00001861static bool IsWeakLValue(const LValue &Value) {
1862 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001863 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001864}
1865
David Majnemerb5116032014-12-09 23:32:34 +00001866static bool isZeroSized(const LValue &Value) {
1867 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001868 if (Decl && isa<VarDecl>(Decl)) {
1869 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001870 if (Ty->isArrayType())
1871 return Ty->isIncompleteType() ||
1872 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001873 }
1874 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001875}
1876
Richard Smith2e312c82012-03-03 22:46:17 +00001877static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001878 // A null base expression indicates a null pointer. These are always
1879 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001880 if (!Value.getLValueBase()) {
1881 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001882 return true;
1883 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001884
Richard Smith027bf112011-11-17 22:56:20 +00001885 // We have a non-null base. These are generally known to be true, but if it's
1886 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001887 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001888 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001889 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001890}
1891
Richard Smith2e312c82012-03-03 22:46:17 +00001892static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001893 switch (Val.getKind()) {
1894 case APValue::Uninitialized:
1895 return false;
1896 case APValue::Int:
1897 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001898 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001899 case APValue::Float:
1900 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001901 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001902 case APValue::ComplexInt:
1903 Result = Val.getComplexIntReal().getBoolValue() ||
1904 Val.getComplexIntImag().getBoolValue();
1905 return true;
1906 case APValue::ComplexFloat:
1907 Result = !Val.getComplexFloatReal().isZero() ||
1908 !Val.getComplexFloatImag().isZero();
1909 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001910 case APValue::LValue:
1911 return EvalPointerValueAsBool(Val, Result);
1912 case APValue::MemberPointer:
1913 Result = Val.getMemberPointerDecl();
1914 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001915 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001916 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001917 case APValue::Struct:
1918 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001919 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001920 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001921 }
1922
Richard Smith11562c52011-10-28 17:51:58 +00001923 llvm_unreachable("unknown APValue kind");
1924}
1925
1926static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1927 EvalInfo &Info) {
1928 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001929 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001930 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001931 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001932 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001933}
1934
Richard Smith357362d2011-12-13 06:39:58 +00001935template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001936static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001937 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001938 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001939 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001940 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001941}
1942
1943static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1944 QualType SrcType, const APFloat &Value,
1945 QualType DestType, APSInt &Result) {
1946 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001947 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001948 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001949
Richard Smith357362d2011-12-13 06:39:58 +00001950 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001951 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001952 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1953 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001954 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001955 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001956}
1957
Richard Smith357362d2011-12-13 06:39:58 +00001958static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1959 QualType SrcType, QualType DestType,
1960 APFloat &Result) {
1961 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001962 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001963 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1964 APFloat::rmNearestTiesToEven, &ignored)
1965 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001966 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001967 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001968}
1969
Richard Smith911e1422012-01-30 22:27:01 +00001970static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1971 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001972 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001973 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001974 APSInt Result = Value;
1975 // Figure out if this is a truncate, extend or noop cast.
1976 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001977 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001978 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001979 return Result;
1980}
1981
Richard Smith357362d2011-12-13 06:39:58 +00001982static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1983 QualType SrcType, const APSInt &Value,
1984 QualType DestType, APFloat &Result) {
1985 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1986 if (Result.convertFromAPInt(Value, Value.isSigned(),
1987 APFloat::rmNearestTiesToEven)
1988 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001989 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001990 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001991}
1992
Richard Smith49ca8aa2013-08-06 07:09:20 +00001993static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1994 APValue &Value, const FieldDecl *FD) {
1995 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1996
1997 if (!Value.isInt()) {
1998 // Trying to store a pointer-cast-to-integer into a bitfield.
1999 // FIXME: In this case, we should provide the diagnostic for casting
2000 // a pointer to an integer.
2001 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002002 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002003 return false;
2004 }
2005
2006 APSInt &Int = Value.getInt();
2007 unsigned OldBitWidth = Int.getBitWidth();
2008 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2009 if (NewBitWidth < OldBitWidth)
2010 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2011 return true;
2012}
2013
Eli Friedman803acb32011-12-22 03:51:45 +00002014static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2015 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002016 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002017 if (!Evaluate(SVal, Info, E))
2018 return false;
2019 if (SVal.isInt()) {
2020 Res = SVal.getInt();
2021 return true;
2022 }
2023 if (SVal.isFloat()) {
2024 Res = SVal.getFloat().bitcastToAPInt();
2025 return true;
2026 }
2027 if (SVal.isVector()) {
2028 QualType VecTy = E->getType();
2029 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2030 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2031 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2032 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2033 Res = llvm::APInt::getNullValue(VecSize);
2034 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2035 APValue &Elt = SVal.getVectorElt(i);
2036 llvm::APInt EltAsInt;
2037 if (Elt.isInt()) {
2038 EltAsInt = Elt.getInt();
2039 } else if (Elt.isFloat()) {
2040 EltAsInt = Elt.getFloat().bitcastToAPInt();
2041 } else {
2042 // Don't try to handle vectors of anything other than int or float
2043 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002044 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002045 return false;
2046 }
2047 unsigned BaseEltSize = EltAsInt.getBitWidth();
2048 if (BigEndian)
2049 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2050 else
2051 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2052 }
2053 return true;
2054 }
2055 // Give up if the input isn't an int, float, or vector. For example, we
2056 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002057 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002058 return false;
2059}
2060
Richard Smith43e77732013-05-07 04:50:00 +00002061/// Perform the given integer operation, which is known to need at most BitWidth
2062/// bits, and check for overflow in the original type (if that type was not an
2063/// unsigned type).
2064template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002065static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2066 const APSInt &LHS, const APSInt &RHS,
2067 unsigned BitWidth, Operation Op,
2068 APSInt &Result) {
2069 if (LHS.isUnsigned()) {
2070 Result = Op(LHS, RHS);
2071 return true;
2072 }
Richard Smith43e77732013-05-07 04:50:00 +00002073
2074 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002075 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002076 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002077 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002078 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002079 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002080 << Result.toString(10) << E->getType();
2081 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002082 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002083 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002084 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002085}
2086
2087/// Perform the given binary integer operation.
2088static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2089 BinaryOperatorKind Opcode, APSInt RHS,
2090 APSInt &Result) {
2091 switch (Opcode) {
2092 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002093 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002094 return false;
2095 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002096 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2097 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002098 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002099 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2100 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002101 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002102 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2103 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002104 case BO_And: Result = LHS & RHS; return true;
2105 case BO_Xor: Result = LHS ^ RHS; return true;
2106 case BO_Or: Result = LHS | RHS; return true;
2107 case BO_Div:
2108 case BO_Rem:
2109 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002110 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002111 return false;
2112 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002113 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2114 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2115 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002116 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2117 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002118 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2119 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002120 return true;
2121 case BO_Shl: {
2122 if (Info.getLangOpts().OpenCL)
2123 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2124 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2125 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2126 RHS.isUnsigned());
2127 else if (RHS.isSigned() && RHS.isNegative()) {
2128 // During constant-folding, a negative shift is an opposite shift. Such
2129 // a shift is not a constant expression.
2130 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2131 RHS = -RHS;
2132 goto shift_right;
2133 }
2134 shift_left:
2135 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2136 // the shifted type.
2137 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2138 if (SA != RHS) {
2139 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2140 << RHS << E->getType() << LHS.getBitWidth();
2141 } else if (LHS.isSigned()) {
2142 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2143 // operand, and must not overflow the corresponding unsigned type.
2144 if (LHS.isNegative())
2145 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2146 else if (LHS.countLeadingZeros() < SA)
2147 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2148 }
2149 Result = LHS << SA;
2150 return true;
2151 }
2152 case BO_Shr: {
2153 if (Info.getLangOpts().OpenCL)
2154 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2155 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2156 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2157 RHS.isUnsigned());
2158 else if (RHS.isSigned() && RHS.isNegative()) {
2159 // During constant-folding, a negative shift is an opposite shift. Such a
2160 // shift is not a constant expression.
2161 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2162 RHS = -RHS;
2163 goto shift_left;
2164 }
2165 shift_right:
2166 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2167 // shifted type.
2168 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2169 if (SA != RHS)
2170 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2171 << RHS << E->getType() << LHS.getBitWidth();
2172 Result = LHS >> SA;
2173 return true;
2174 }
2175
2176 case BO_LT: Result = LHS < RHS; return true;
2177 case BO_GT: Result = LHS > RHS; return true;
2178 case BO_LE: Result = LHS <= RHS; return true;
2179 case BO_GE: Result = LHS >= RHS; return true;
2180 case BO_EQ: Result = LHS == RHS; return true;
2181 case BO_NE: Result = LHS != RHS; return true;
2182 }
2183}
2184
Richard Smith861b5b52013-05-07 23:34:45 +00002185/// Perform the given binary floating-point operation, in-place, on LHS.
2186static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2187 APFloat &LHS, BinaryOperatorKind Opcode,
2188 const APFloat &RHS) {
2189 switch (Opcode) {
2190 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002191 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002192 return false;
2193 case BO_Mul:
2194 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2195 break;
2196 case BO_Add:
2197 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2198 break;
2199 case BO_Sub:
2200 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2201 break;
2202 case BO_Div:
2203 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2204 break;
2205 }
2206
Richard Smith0c6124b2015-12-03 01:36:22 +00002207 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002208 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002209 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002210 }
Richard Smith861b5b52013-05-07 23:34:45 +00002211 return true;
2212}
2213
Richard Smitha8105bc2012-01-06 16:39:00 +00002214/// Cast an lvalue referring to a base subobject to a derived class, by
2215/// truncating the lvalue's path to the given length.
2216static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2217 const RecordDecl *TruncatedType,
2218 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002219 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002220
2221 // Check we actually point to a derived class object.
2222 if (TruncatedElements == D.Entries.size())
2223 return true;
2224 assert(TruncatedElements >= D.MostDerivedPathLength &&
2225 "not casting to a derived class");
2226 if (!Result.checkSubobject(Info, E, CSK_Derived))
2227 return false;
2228
2229 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002230 const RecordDecl *RD = TruncatedType;
2231 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002232 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002233 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2234 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002235 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002236 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002237 else
Richard Smithd62306a2011-11-10 06:34:14 +00002238 Result.Offset -= Layout.getBaseClassOffset(Base);
2239 RD = Base;
2240 }
Richard Smith027bf112011-11-17 22:56:20 +00002241 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002242 return true;
2243}
2244
John McCalld7bca762012-05-01 00:38:49 +00002245static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002246 const CXXRecordDecl *Derived,
2247 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002248 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002249 if (!RL) {
2250 if (Derived->isInvalidDecl()) return false;
2251 RL = &Info.Ctx.getASTRecordLayout(Derived);
2252 }
2253
Richard Smithd62306a2011-11-10 06:34:14 +00002254 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002255 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002256 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002257}
2258
Richard Smitha8105bc2012-01-06 16:39:00 +00002259static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002260 const CXXRecordDecl *DerivedDecl,
2261 const CXXBaseSpecifier *Base) {
2262 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2263
John McCalld7bca762012-05-01 00:38:49 +00002264 if (!Base->isVirtual())
2265 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002266
Richard Smitha8105bc2012-01-06 16:39:00 +00002267 SubobjectDesignator &D = Obj.Designator;
2268 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002269 return false;
2270
Richard Smitha8105bc2012-01-06 16:39:00 +00002271 // Extract most-derived object and corresponding type.
2272 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2273 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2274 return false;
2275
2276 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002277 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002278 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2279 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002280 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002281 return true;
2282}
2283
Richard Smith84401042013-06-03 05:03:02 +00002284static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2285 QualType Type, LValue &Result) {
2286 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2287 PathE = E->path_end();
2288 PathI != PathE; ++PathI) {
2289 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2290 *PathI))
2291 return false;
2292 Type = (*PathI)->getType();
2293 }
2294 return true;
2295}
2296
Richard Smithd62306a2011-11-10 06:34:14 +00002297/// Update LVal to refer to the given field, which must be a member of the type
2298/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002299static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002300 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002301 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002302 if (!RL) {
2303 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002304 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002305 }
Richard Smithd62306a2011-11-10 06:34:14 +00002306
2307 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002308 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002309 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002310 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002311}
2312
Richard Smith1b78b3d2012-01-25 22:15:11 +00002313/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002314static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002315 LValue &LVal,
2316 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002317 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002318 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002319 return false;
2320 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002321}
2322
Richard Smithd62306a2011-11-10 06:34:14 +00002323/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002324static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2325 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002326 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2327 // extension.
2328 if (Type->isVoidType() || Type->isFunctionType()) {
2329 Size = CharUnits::One();
2330 return true;
2331 }
2332
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002333 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002334 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002335 return false;
2336 }
2337
Richard Smithd62306a2011-11-10 06:34:14 +00002338 if (!Type->isConstantSizeType()) {
2339 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002340 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002341 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002342 return false;
2343 }
2344
2345 Size = Info.Ctx.getTypeSizeInChars(Type);
2346 return true;
2347}
2348
2349/// Update a pointer value to model pointer arithmetic.
2350/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002351/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002352/// \param LVal - The pointer value to be updated.
2353/// \param EltTy - The pointee type represented by LVal.
2354/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002355static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2356 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002357 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002358 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002359 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002360 return false;
2361
Yaxun Liu402804b2016-12-15 08:09:08 +00002362 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002363 return true;
2364}
2365
Richard Smithd6cc1982017-01-31 02:23:02 +00002366static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2367 LValue &LVal, QualType EltTy,
2368 int64_t Adjustment) {
2369 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2370 APSInt::get(Adjustment));
2371}
2372
Richard Smith66c96992012-02-18 22:04:06 +00002373/// Update an lvalue to refer to a component of a complex number.
2374/// \param Info - Information about the ongoing evaluation.
2375/// \param LVal - The lvalue to be updated.
2376/// \param EltTy - The complex number's component type.
2377/// \param Imag - False for the real component, true for the imaginary.
2378static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2379 LValue &LVal, QualType EltTy,
2380 bool Imag) {
2381 if (Imag) {
2382 CharUnits SizeOfComponent;
2383 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2384 return false;
2385 LVal.Offset += SizeOfComponent;
2386 }
2387 LVal.addComplex(Info, E, EltTy, Imag);
2388 return true;
2389}
2390
Faisal Vali051e3a22017-02-16 04:12:21 +00002391static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2392 QualType Type, const LValue &LVal,
2393 APValue &RVal);
2394
Richard Smith27908702011-10-24 17:54:18 +00002395/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002396///
2397/// \param Info Information about the ongoing evaluation.
2398/// \param E An expression to be used when printing diagnostics.
2399/// \param VD The variable whose initializer should be obtained.
2400/// \param Frame The frame in which the variable was created. Must be null
2401/// if this variable is not local to the evaluation.
2402/// \param Result Filled in with a pointer to the value of the variable.
2403static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2404 const VarDecl *VD, CallStackFrame *Frame,
2405 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002406
Richard Smith254a73d2011-10-28 22:34:42 +00002407 // If this is a parameter to an active constexpr function call, perform
2408 // argument substitution.
2409 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002410 // Assume arguments of a potential constant expression are unknown
2411 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002412 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002413 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002414 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002415 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002416 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002417 }
Richard Smith3229b742013-05-05 21:17:10 +00002418 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002419 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002420 }
Richard Smith27908702011-10-24 17:54:18 +00002421
Richard Smithd9f663b2013-04-22 15:31:51 +00002422 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002423 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002424 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002425 if (!Result) {
2426 // Assume variables referenced within a lambda's call operator that were
2427 // not declared within the call operator are captures and during checking
2428 // of a potential constant expression, assume they are unknown constant
2429 // expressions.
2430 assert(isLambdaCallOperator(Frame->Callee) &&
2431 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2432 "missing value for local variable");
2433 if (Info.checkingPotentialConstantExpression())
2434 return false;
2435 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002436 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002437 diag::note_unimplemented_constexpr_lambda_feature_ast)
2438 << "captures not currently allowed";
2439 return false;
2440 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002441 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002442 }
2443
Richard Smithd0b4dd62011-12-19 06:19:21 +00002444 // Dig out the initializer, and use the declaration which it's attached to.
2445 const Expr *Init = VD->getAnyInitializer(VD);
2446 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002447 // If we're checking a potential constant expression, the variable could be
2448 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002449 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002450 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002451 return false;
2452 }
2453
Richard Smithd62306a2011-11-10 06:34:14 +00002454 // If we're currently evaluating the initializer of this declaration, use that
2455 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002456 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002457 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002458 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002459 }
2460
Richard Smithcecf1842011-11-01 21:06:14 +00002461 // Never evaluate the initializer of a weak variable. We can't be sure that
2462 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002463 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002464 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002465 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002466 }
Richard Smithcecf1842011-11-01 21:06:14 +00002467
Richard Smithd0b4dd62011-12-19 06:19:21 +00002468 // Check that we can fold the initializer. In C++, we will have already done
2469 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002470 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002471 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002472 Info.FFDiag(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 Smith0b0a0b62011-10-29 20:57:55 +00002476 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002477 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002478 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002479 Notes.size() + 1) << VD;
2480 Info.Note(VD->getLocation(), diag::note_declared_at);
2481 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002482 }
Richard Smith27908702011-10-24 17:54:18 +00002483
Richard Smith3229b742013-05-05 21:17:10 +00002484 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002485 return true;
Richard Smith27908702011-10-24 17:54:18 +00002486}
2487
Richard Smith11562c52011-10-28 17:51:58 +00002488static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002489 Qualifiers Quals = T.getQualifiers();
2490 return Quals.hasConst() && !Quals.hasVolatile();
2491}
2492
Richard Smithe97cbd72011-11-11 04:05:33 +00002493/// Get the base index of the given base class within an APValue representing
2494/// the given derived class.
2495static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2496 const CXXRecordDecl *Base) {
2497 Base = Base->getCanonicalDecl();
2498 unsigned Index = 0;
2499 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2500 E = Derived->bases_end(); I != E; ++I, ++Index) {
2501 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2502 return Index;
2503 }
2504
2505 llvm_unreachable("base class missing from derived class's bases list");
2506}
2507
Richard Smith3da88fa2013-04-26 14:36:30 +00002508/// Extract the value of a character from a string literal.
2509static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2510 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002511 // FIXME: Support MakeStringConstant
2512 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2513 std::string Str;
2514 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2515 assert(Index <= Str.size() && "Index too large");
2516 return APSInt::getUnsigned(Str.c_str()[Index]);
2517 }
2518
Alexey Bataevec474782014-10-09 08:45:04 +00002519 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2520 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002521 const StringLiteral *S = cast<StringLiteral>(Lit);
2522 const ConstantArrayType *CAT =
2523 Info.Ctx.getAsConstantArrayType(S->getType());
2524 assert(CAT && "string literal isn't an array");
2525 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002526 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002527
2528 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002529 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002530 if (Index < S->getLength())
2531 Value = S->getCodeUnit(Index);
2532 return Value;
2533}
2534
Richard Smith3da88fa2013-04-26 14:36:30 +00002535// Expand a string literal into an array of characters.
2536static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2537 APValue &Result) {
2538 const StringLiteral *S = cast<StringLiteral>(Lit);
2539 const ConstantArrayType *CAT =
2540 Info.Ctx.getAsConstantArrayType(S->getType());
2541 assert(CAT && "string literal isn't an array");
2542 QualType CharType = CAT->getElementType();
2543 assert(CharType->isIntegerType() && "unexpected character type");
2544
2545 unsigned Elts = CAT->getSize().getZExtValue();
2546 Result = APValue(APValue::UninitArray(),
2547 std::min(S->getLength(), Elts), Elts);
2548 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2549 CharType->isUnsignedIntegerType());
2550 if (Result.hasArrayFiller())
2551 Result.getArrayFiller() = APValue(Value);
2552 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2553 Value = S->getCodeUnit(I);
2554 Result.getArrayInitializedElt(I) = APValue(Value);
2555 }
2556}
2557
2558// Expand an array so that it has more than Index filled elements.
2559static void expandArray(APValue &Array, unsigned Index) {
2560 unsigned Size = Array.getArraySize();
2561 assert(Index < Size);
2562
2563 // Always at least double the number of elements for which we store a value.
2564 unsigned OldElts = Array.getArrayInitializedElts();
2565 unsigned NewElts = std::max(Index+1, OldElts * 2);
2566 NewElts = std::min(Size, std::max(NewElts, 8u));
2567
2568 // Copy the data across.
2569 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2570 for (unsigned I = 0; I != OldElts; ++I)
2571 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2572 for (unsigned I = OldElts; I != NewElts; ++I)
2573 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2574 if (NewValue.hasArrayFiller())
2575 NewValue.getArrayFiller() = Array.getArrayFiller();
2576 Array.swap(NewValue);
2577}
2578
Richard Smithb01fe402014-09-16 01:24:02 +00002579/// Determine whether a type would actually be read by an lvalue-to-rvalue
2580/// conversion. If it's of class type, we may assume that the copy operation
2581/// is trivial. Note that this is never true for a union type with fields
2582/// (because the copy always "reads" the active member) and always true for
2583/// a non-class type.
2584static bool isReadByLvalueToRvalueConversion(QualType T) {
2585 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2586 if (!RD || (RD->isUnion() && !RD->field_empty()))
2587 return true;
2588 if (RD->isEmpty())
2589 return false;
2590
2591 for (auto *Field : RD->fields())
2592 if (isReadByLvalueToRvalueConversion(Field->getType()))
2593 return true;
2594
2595 for (auto &BaseSpec : RD->bases())
2596 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2597 return true;
2598
2599 return false;
2600}
2601
2602/// Diagnose an attempt to read from any unreadable field within the specified
2603/// type, which might be a class type.
2604static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2605 QualType T) {
2606 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2607 if (!RD)
2608 return false;
2609
2610 if (!RD->hasMutableFields())
2611 return false;
2612
2613 for (auto *Field : RD->fields()) {
2614 // If we're actually going to read this field in some way, then it can't
2615 // be mutable. If we're in a union, then assigning to a mutable field
2616 // (even an empty one) can change the active member, so that's not OK.
2617 // FIXME: Add core issue number for the union case.
2618 if (Field->isMutable() &&
2619 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002620 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002621 Info.Note(Field->getLocation(), diag::note_declared_at);
2622 return true;
2623 }
2624
2625 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2626 return true;
2627 }
2628
2629 for (auto &BaseSpec : RD->bases())
2630 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2631 return true;
2632
2633 // All mutable fields were empty, and thus not actually read.
2634 return false;
2635}
2636
Richard Smith861b5b52013-05-07 23:34:45 +00002637/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002638enum AccessKinds {
2639 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002640 AK_Assign,
2641 AK_Increment,
2642 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002643};
2644
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002645namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002646/// A handle to a complete object (an object that is not a subobject of
2647/// another object).
2648struct CompleteObject {
2649 /// The value of the complete object.
2650 APValue *Value;
2651 /// The type of the complete object.
2652 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002653 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002654
Craig Topper36250ad2014-05-12 05:36:57 +00002655 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002656 CompleteObject(APValue *Value, QualType Type,
2657 bool LifetimeStartedInEvaluation)
2658 : Value(Value), Type(Type),
2659 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002660 assert(Value && "missing value for complete object");
2661 }
2662
Aaron Ballman67347662015-02-15 22:00:28 +00002663 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002664};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002665} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002666
Richard Smith3da88fa2013-04-26 14:36:30 +00002667/// Find the designated sub-object of an rvalue.
2668template<typename SubobjectHandler>
2669typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002670findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002671 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002672 if (Sub.Invalid)
2673 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002674 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002675 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002676 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002677 Info.FFDiag(E, Sub.isOnePastTheEnd()
2678 ? diag::note_constexpr_access_past_end
2679 : diag::note_constexpr_access_unsized_array)
2680 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002681 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002682 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002683 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002684 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002685
Richard Smith3229b742013-05-05 21:17:10 +00002686 APValue *O = Obj.Value;
2687 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002688 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002689 const bool MayReadMutableMembers =
2690 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002691
Richard Smithd62306a2011-11-10 06:34:14 +00002692 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002693 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2694 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002695 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002696 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002697 return handler.failed();
2698 }
2699
Richard Smith49ca8aa2013-08-06 07:09:20 +00002700 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002701 // If we are reading an object of class type, there may still be more
2702 // things we need to check: if there are any mutable subobjects, we
2703 // cannot perform this read. (This only happens when performing a trivial
2704 // copy or assignment.)
2705 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002706 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002707 return handler.failed();
2708
Richard Smith49ca8aa2013-08-06 07:09:20 +00002709 if (!handler.found(*O, ObjType))
2710 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002711
Richard Smith49ca8aa2013-08-06 07:09:20 +00002712 // If we modified a bit-field, truncate it to the right width.
2713 if (handler.AccessKind != AK_Read &&
2714 LastField && LastField->isBitField() &&
2715 !truncateBitfieldValue(Info, E, *O, LastField))
2716 return false;
2717
2718 return true;
2719 }
2720
Craig Topper36250ad2014-05-12 05:36:57 +00002721 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002722 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002723 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002724 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002725 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002726 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002727 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002728 // Note, it should not be possible to form a pointer with a valid
2729 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002730 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002731 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002732 << handler.AccessKind;
2733 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002734 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002735 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002736 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002737
2738 ObjType = CAT->getElementType();
2739
Richard Smith14a94132012-02-17 03:35:37 +00002740 // An array object is represented as either an Array APValue or as an
2741 // LValue which refers to a string literal.
2742 if (O->isLValue()) {
2743 assert(I == N - 1 && "extracting subobject of character?");
2744 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002745 if (handler.AccessKind != AK_Read)
2746 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2747 *O);
2748 else
2749 return handler.foundString(*O, ObjType, Index);
2750 }
2751
2752 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002753 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002754 else if (handler.AccessKind != AK_Read) {
2755 expandArray(*O, Index);
2756 O = &O->getArrayInitializedElt(Index);
2757 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002758 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002759 } else if (ObjType->isAnyComplexType()) {
2760 // Next subobject is a complex number.
2761 uint64_t Index = Sub.Entries[I].ArrayIndex;
2762 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002763 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002764 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002765 << handler.AccessKind;
2766 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002767 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002768 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002769 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002770
2771 bool WasConstQualified = ObjType.isConstQualified();
2772 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2773 if (WasConstQualified)
2774 ObjType.addConst();
2775
Richard Smith66c96992012-02-18 22:04:06 +00002776 assert(I == N - 1 && "extracting subobject of scalar?");
2777 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002778 return handler.found(Index ? O->getComplexIntImag()
2779 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002780 } else {
2781 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002782 return handler.found(Index ? O->getComplexFloatImag()
2783 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002784 }
Richard Smithd62306a2011-11-10 06:34:14 +00002785 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002786 // In C++14 onwards, it is permitted to read a mutable member whose
2787 // lifetime began within the evaluation.
2788 // FIXME: Should we also allow this in C++11?
2789 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2790 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002791 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002792 << Field;
2793 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002794 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002795 }
2796
Richard Smithd62306a2011-11-10 06:34:14 +00002797 // Next subobject is a class, struct or union field.
2798 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2799 if (RD->isUnion()) {
2800 const FieldDecl *UnionField = O->getUnionField();
2801 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002802 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002803 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002804 << handler.AccessKind << Field << !UnionField << UnionField;
2805 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002806 }
Richard Smithd62306a2011-11-10 06:34:14 +00002807 O = &O->getUnionValue();
2808 } else
2809 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002810
2811 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002812 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002813 if (WasConstQualified && !Field->isMutable())
2814 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002815
2816 if (ObjType.isVolatileQualified()) {
2817 if (Info.getLangOpts().CPlusPlus) {
2818 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002819 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002820 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002821 Info.Note(Field->getLocation(), diag::note_declared_at);
2822 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002823 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002824 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002825 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002826 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002827
2828 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002829 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002830 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002831 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2832 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2833 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002834
2835 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002836 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002837 if (WasConstQualified)
2838 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002839 }
2840 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002841}
2842
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002843namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002844struct ExtractSubobjectHandler {
2845 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002846 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002847
2848 static const AccessKinds AccessKind = AK_Read;
2849
2850 typedef bool result_type;
2851 bool failed() { return false; }
2852 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002853 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002854 return true;
2855 }
2856 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002857 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002858 return true;
2859 }
2860 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002861 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002862 return true;
2863 }
2864 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002865 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002866 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2867 return true;
2868 }
2869};
Richard Smith3229b742013-05-05 21:17:10 +00002870} // end anonymous namespace
2871
Richard Smith3da88fa2013-04-26 14:36:30 +00002872const AccessKinds ExtractSubobjectHandler::AccessKind;
2873
2874/// Extract the designated sub-object of an rvalue.
2875static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002876 const CompleteObject &Obj,
2877 const SubobjectDesignator &Sub,
2878 APValue &Result) {
2879 ExtractSubobjectHandler Handler = { Info, Result };
2880 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002881}
2882
Richard Smith3229b742013-05-05 21:17:10 +00002883namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002884struct ModifySubobjectHandler {
2885 EvalInfo &Info;
2886 APValue &NewVal;
2887 const Expr *E;
2888
2889 typedef bool result_type;
2890 static const AccessKinds AccessKind = AK_Assign;
2891
2892 bool checkConst(QualType QT) {
2893 // Assigning to a const object has undefined behavior.
2894 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002895 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002896 return false;
2897 }
2898 return true;
2899 }
2900
2901 bool failed() { return false; }
2902 bool found(APValue &Subobj, QualType SubobjType) {
2903 if (!checkConst(SubobjType))
2904 return false;
2905 // We've been given ownership of NewVal, so just swap it in.
2906 Subobj.swap(NewVal);
2907 return true;
2908 }
2909 bool found(APSInt &Value, QualType SubobjType) {
2910 if (!checkConst(SubobjType))
2911 return false;
2912 if (!NewVal.isInt()) {
2913 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002914 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002915 return false;
2916 }
2917 Value = NewVal.getInt();
2918 return true;
2919 }
2920 bool found(APFloat &Value, QualType SubobjType) {
2921 if (!checkConst(SubobjType))
2922 return false;
2923 Value = NewVal.getFloat();
2924 return true;
2925 }
2926 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2927 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2928 }
2929};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002930} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002931
Richard Smith3229b742013-05-05 21:17:10 +00002932const AccessKinds ModifySubobjectHandler::AccessKind;
2933
Richard Smith3da88fa2013-04-26 14:36:30 +00002934/// Update the designated sub-object of an rvalue to the given value.
2935static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002936 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002937 const SubobjectDesignator &Sub,
2938 APValue &NewVal) {
2939 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002940 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002941}
2942
Richard Smith84f6dcf2012-02-02 01:16:57 +00002943/// Find the position where two subobject designators diverge, or equivalently
2944/// the length of the common initial subsequence.
2945static unsigned FindDesignatorMismatch(QualType ObjType,
2946 const SubobjectDesignator &A,
2947 const SubobjectDesignator &B,
2948 bool &WasArrayIndex) {
2949 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2950 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002951 if (!ObjType.isNull() &&
2952 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002953 // Next subobject is an array element.
2954 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2955 WasArrayIndex = true;
2956 return I;
2957 }
Richard Smith66c96992012-02-18 22:04:06 +00002958 if (ObjType->isAnyComplexType())
2959 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2960 else
2961 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002962 } else {
2963 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2964 WasArrayIndex = false;
2965 return I;
2966 }
2967 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2968 // Next subobject is a field.
2969 ObjType = FD->getType();
2970 else
2971 // Next subobject is a base class.
2972 ObjType = QualType();
2973 }
2974 }
2975 WasArrayIndex = false;
2976 return I;
2977}
2978
2979/// Determine whether the given subobject designators refer to elements of the
2980/// same array object.
2981static bool AreElementsOfSameArray(QualType ObjType,
2982 const SubobjectDesignator &A,
2983 const SubobjectDesignator &B) {
2984 if (A.Entries.size() != B.Entries.size())
2985 return false;
2986
George Burgess IVa51c4072015-10-16 01:49:01 +00002987 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002988 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2989 // A is a subobject of the array element.
2990 return false;
2991
2992 // If A (and B) designates an array element, the last entry will be the array
2993 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2994 // of length 1' case, and the entire path must match.
2995 bool WasArrayIndex;
2996 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2997 return CommonLength >= A.Entries.size() - IsArray;
2998}
2999
Richard Smith3229b742013-05-05 21:17:10 +00003000/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003001static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3002 AccessKinds AK, const LValue &LVal,
3003 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003004 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003005 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003006 return CompleteObject();
3007 }
3008
Craig Topper36250ad2014-05-12 05:36:57 +00003009 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00003010 if (LVal.CallIndex) {
3011 Frame = Info.getCallFrame(LVal.CallIndex);
3012 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003013 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003014 << AK << LVal.Base.is<const ValueDecl*>();
3015 NoteLValueLocation(Info, LVal.Base);
3016 return CompleteObject();
3017 }
Richard Smith3229b742013-05-05 21:17:10 +00003018 }
3019
3020 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3021 // is not a constant expression (even if the object is non-volatile). We also
3022 // apply this rule to C++98, in order to conform to the expected 'volatile'
3023 // semantics.
3024 if (LValType.isVolatileQualified()) {
3025 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003026 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003027 << AK << LValType;
3028 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003029 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003030 return CompleteObject();
3031 }
3032
3033 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003034 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003035 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003036 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003037
3038 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3039 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3040 // In C++11, constexpr, non-volatile variables initialized with constant
3041 // expressions are constant expressions too. Inside constexpr functions,
3042 // parameters are constant expressions even if they're non-const.
3043 // In C++1y, objects local to a constant expression (those with a Frame) are
3044 // both readable and writable inside constant expressions.
3045 // In C, such things can also be folded, although they are not ICEs.
3046 const VarDecl *VD = dyn_cast<VarDecl>(D);
3047 if (VD) {
3048 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3049 VD = VDef;
3050 }
3051 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003052 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003053 return CompleteObject();
3054 }
3055
3056 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003057 if (BaseType.isVolatileQualified()) {
3058 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003059 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003060 << AK << 1 << VD;
3061 Info.Note(VD->getLocation(), diag::note_declared_at);
3062 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003063 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003064 }
3065 return CompleteObject();
3066 }
3067
3068 // Unless we're looking at a local variable or argument in a constexpr call,
3069 // the variable we're reading must be const.
3070 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003071 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003072 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3073 // OK, we can read and modify an object if we're in the process of
3074 // evaluating its initializer, because its lifetime began in this
3075 // evaluation.
3076 } else if (AK != AK_Read) {
3077 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003078 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003079 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003080 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003081 // OK, we can read this variable.
3082 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003083 // In OpenCL if a variable is in constant address space it is a const value.
3084 if (!(BaseType.isConstQualified() ||
3085 (Info.getLangOpts().OpenCL &&
3086 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003087 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003088 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003089 Info.Note(VD->getLocation(), diag::note_declared_at);
3090 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003091 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003092 }
3093 return CompleteObject();
3094 }
3095 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3096 // We support folding of const floating-point types, in order to make
3097 // static const data members of such types (supported as an extension)
3098 // more useful.
3099 if (Info.getLangOpts().CPlusPlus11) {
3100 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3101 Info.Note(VD->getLocation(), diag::note_declared_at);
3102 } else {
3103 Info.CCEDiag(E);
3104 }
George Burgess IVb5316982016-12-27 05:33:20 +00003105 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3106 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3107 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003108 } else {
3109 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003110 if (Info.checkingPotentialConstantExpression() &&
3111 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3112 // The definition of this variable could be constexpr. We can't
3113 // access it right now, but may be able to in future.
3114 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003115 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003116 Info.Note(VD->getLocation(), diag::note_declared_at);
3117 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003118 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003119 }
3120 return CompleteObject();
3121 }
3122 }
3123
3124 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3125 return CompleteObject();
3126 } else {
3127 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3128
3129 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003130 if (const MaterializeTemporaryExpr *MTE =
3131 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3132 assert(MTE->getStorageDuration() == SD_Static &&
3133 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003134
Richard Smithe6c01442013-06-05 00:46:14 +00003135 // Per C++1y [expr.const]p2:
3136 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3137 // - a [...] glvalue of integral or enumeration type that refers to
3138 // a non-volatile const object [...]
3139 // [...]
3140 // - a [...] glvalue of literal type that refers to a non-volatile
3141 // object whose lifetime began within the evaluation of e.
3142 //
3143 // C++11 misses the 'began within the evaluation of e' check and
3144 // instead allows all temporaries, including things like:
3145 // int &&r = 1;
3146 // int x = ++r;
3147 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003148 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003149 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3150 const ValueDecl *ED = MTE->getExtendingDecl();
3151 if (!(BaseType.isConstQualified() &&
3152 BaseType->isIntegralOrEnumerationType()) &&
3153 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003154 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003155 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3156 return CompleteObject();
3157 }
3158
3159 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3160 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003161 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003162 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003163 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003164 return CompleteObject();
3165 }
3166 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003167 BaseVal = Frame->getTemporary(Base);
3168 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003169 }
Richard Smith3229b742013-05-05 21:17:10 +00003170
3171 // Volatile temporary objects cannot be accessed in constant expressions.
3172 if (BaseType.isVolatileQualified()) {
3173 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003174 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003175 << AK << 0;
3176 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3177 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003178 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003179 }
3180 return CompleteObject();
3181 }
3182 }
3183
Richard Smith7525ff62013-05-09 07:14:00 +00003184 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003185 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003186 // object under construction.
Erik Pilkington42925492017-10-04 00:18:55 +00003187 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) {
Richard Smith7525ff62013-05-09 07:14:00 +00003188 BaseType = Info.Ctx.getCanonicalType(BaseType);
3189 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003190 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003191 }
3192
Richard Smith9defb7d2018-02-21 03:38:30 +00003193 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003194 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003195 //
3196 // FIXME: Not all local state is mutable. Allow local constant subobjects
3197 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003198 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3199 Info.EvalStatus.HasSideEffects) ||
3200 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003201 return CompleteObject();
3202
Richard Smith9defb7d2018-02-21 03:38:30 +00003203 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003204}
3205
Richard Smith243ef902013-05-05 23:31:59 +00003206/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3207/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3208/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003209///
3210/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003211/// \param Conv - The expression for which we are performing the conversion.
3212/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003213/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3214/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003215/// \param LVal - The glvalue on which we are attempting to perform this action.
3216/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003217static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003218 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003219 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003220 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003221 return false;
3222
Richard Smith3229b742013-05-05 21:17:10 +00003223 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003224 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003225 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003226 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3227 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3228 // initializer until now for such expressions. Such an expression can't be
3229 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003230 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003231 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003232 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003233 }
Richard Smith3229b742013-05-05 21:17:10 +00003234 APValue Lit;
3235 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3236 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003237 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003238 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003239 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003240 // We represent a string literal array as an lvalue pointing at the
3241 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003242 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003243 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smith9defb7d2018-02-21 03:38:30 +00003244 CompleteObject StrObj(&Str, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003245 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003246 }
Richard Smith11562c52011-10-28 17:51:58 +00003247 }
3248
Richard Smith3229b742013-05-05 21:17:10 +00003249 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3250 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003251}
3252
3253/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003254static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003255 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003256 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003257 return false;
3258
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003259 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003260 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003261 return false;
3262 }
3263
Richard Smith3229b742013-05-05 21:17:10 +00003264 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Aaron Ballmana5038552018-01-09 13:07:03 +00003265 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3266}
3267
3268namespace {
3269struct CompoundAssignSubobjectHandler {
3270 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003271 const Expr *E;
3272 QualType PromotedLHSType;
3273 BinaryOperatorKind Opcode;
3274 const APValue &RHS;
3275
3276 static const AccessKinds AccessKind = AK_Assign;
3277
3278 typedef bool result_type;
3279
3280 bool checkConst(QualType QT) {
3281 // Assigning to a const object has undefined behavior.
3282 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003283 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003284 return false;
3285 }
3286 return true;
3287 }
3288
3289 bool failed() { return false; }
3290 bool found(APValue &Subobj, QualType SubobjType) {
3291 switch (Subobj.getKind()) {
3292 case APValue::Int:
3293 return found(Subobj.getInt(), SubobjType);
3294 case APValue::Float:
3295 return found(Subobj.getFloat(), SubobjType);
3296 case APValue::ComplexInt:
3297 case APValue::ComplexFloat:
3298 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003299 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003300 return false;
3301 case APValue::LValue:
3302 return foundPointer(Subobj, SubobjType);
3303 default:
3304 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003305 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003306 return false;
3307 }
3308 }
3309 bool found(APSInt &Value, QualType SubobjType) {
3310 if (!checkConst(SubobjType))
3311 return false;
3312
3313 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3314 // We don't support compound assignment on integer-cast-to-pointer
3315 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003316 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003317 return false;
3318 }
3319
3320 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3321 SubobjType, Value);
3322 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3323 return false;
3324 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3325 return true;
3326 }
3327 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003328 return checkConst(SubobjType) &&
3329 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3330 Value) &&
3331 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3332 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003333 }
3334 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3335 if (!checkConst(SubobjType))
3336 return false;
3337
3338 QualType PointeeType;
3339 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3340 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003341
3342 if (PointeeType.isNull() || !RHS.isInt() ||
3343 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003344 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003345 return false;
3346 }
3347
Richard Smithd6cc1982017-01-31 02:23:02 +00003348 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003349 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003350 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003351
3352 LValue LVal;
3353 LVal.setFrom(Info.Ctx, Subobj);
3354 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3355 return false;
3356 LVal.moveInto(Subobj);
3357 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003358 }
3359 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3360 llvm_unreachable("shouldn't encounter string elements here");
3361 }
3362};
3363} // end anonymous namespace
3364
3365const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3366
3367/// Perform a compound assignment of LVal <op>= RVal.
3368static bool handleCompoundAssignment(
3369 EvalInfo &Info, const Expr *E,
3370 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3371 BinaryOperatorKind Opcode, const APValue &RVal) {
3372 if (LVal.Designator.Invalid)
3373 return false;
3374
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003375 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003376 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003377 return false;
3378 }
3379
3380 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3381 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3382 RVal };
3383 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3384}
3385
Aaron Ballmana5038552018-01-09 13:07:03 +00003386namespace {
3387struct IncDecSubobjectHandler {
3388 EvalInfo &Info;
3389 const UnaryOperator *E;
3390 AccessKinds AccessKind;
3391 APValue *Old;
3392
Richard Smith243ef902013-05-05 23:31:59 +00003393 typedef bool result_type;
3394
3395 bool checkConst(QualType QT) {
3396 // Assigning to a const object has undefined behavior.
3397 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003398 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003399 return false;
3400 }
3401 return true;
3402 }
3403
3404 bool failed() { return false; }
3405 bool found(APValue &Subobj, QualType SubobjType) {
3406 // Stash the old value. Also clear Old, so we don't clobber it later
3407 // if we're post-incrementing a complex.
3408 if (Old) {
3409 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003410 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003411 }
3412
3413 switch (Subobj.getKind()) {
3414 case APValue::Int:
3415 return found(Subobj.getInt(), SubobjType);
3416 case APValue::Float:
3417 return found(Subobj.getFloat(), SubobjType);
3418 case APValue::ComplexInt:
3419 return found(Subobj.getComplexIntReal(),
3420 SubobjType->castAs<ComplexType>()->getElementType()
3421 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3422 case APValue::ComplexFloat:
3423 return found(Subobj.getComplexFloatReal(),
3424 SubobjType->castAs<ComplexType>()->getElementType()
3425 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3426 case APValue::LValue:
3427 return foundPointer(Subobj, SubobjType);
3428 default:
3429 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003430 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003431 return false;
3432 }
3433 }
3434 bool found(APSInt &Value, QualType SubobjType) {
3435 if (!checkConst(SubobjType))
3436 return false;
3437
3438 if (!SubobjType->isIntegerType()) {
3439 // We don't support increment / decrement on integer-cast-to-pointer
3440 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003441 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003442 return false;
3443 }
3444
3445 if (Old) *Old = APValue(Value);
3446
3447 // bool arithmetic promotes to int, and the conversion back to bool
3448 // doesn't reduce mod 2^n, so special-case it.
3449 if (SubobjType->isBooleanType()) {
3450 if (AccessKind == AK_Increment)
3451 Value = 1;
3452 else
3453 Value = !Value;
3454 return true;
3455 }
3456
3457 bool WasNegative = Value.isNegative();
Aaron Ballmana5038552018-01-09 13:07:03 +00003458 if (AccessKind == AK_Increment) {
3459 ++Value;
3460
3461 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3462 APSInt ActualValue(Value, /*IsUnsigned*/true);
3463 return HandleOverflow(Info, E, ActualValue, SubobjType);
3464 }
3465 } else {
3466 --Value;
3467
3468 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3469 unsigned BitWidth = Value.getBitWidth();
3470 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3471 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003472 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003473 }
3474 }
3475 return true;
3476 }
3477 bool found(APFloat &Value, QualType SubobjType) {
3478 if (!checkConst(SubobjType))
3479 return false;
3480
3481 if (Old) *Old = APValue(Value);
3482
3483 APFloat One(Value.getSemantics(), 1);
3484 if (AccessKind == AK_Increment)
3485 Value.add(One, APFloat::rmNearestTiesToEven);
3486 else
3487 Value.subtract(One, APFloat::rmNearestTiesToEven);
3488 return true;
3489 }
3490 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3491 if (!checkConst(SubobjType))
3492 return false;
3493
3494 QualType PointeeType;
3495 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3496 PointeeType = PT->getPointeeType();
3497 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003498 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003499 return false;
3500 }
3501
3502 LValue LVal;
3503 LVal.setFrom(Info.Ctx, Subobj);
3504 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3505 AccessKind == AK_Increment ? 1 : -1))
3506 return false;
3507 LVal.moveInto(Subobj);
3508 return true;
3509 }
3510 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3511 llvm_unreachable("shouldn't encounter string elements here");
3512 }
3513};
3514} // end anonymous namespace
3515
3516/// Perform an increment or decrement on LVal.
3517static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3518 QualType LValType, bool IsIncrement, APValue *Old) {
3519 if (LVal.Designator.Invalid)
3520 return false;
3521
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003522 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003523 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003524 return false;
3525 }
Aaron Ballmana5038552018-01-09 13:07:03 +00003526
3527 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3528 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3529 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3530 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3531}
3532
Richard Smithe97cbd72011-11-11 04:05:33 +00003533/// Build an lvalue for the object argument of a member function call.
3534static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3535 LValue &This) {
3536 if (Object->getType()->isPointerType())
3537 return EvaluatePointer(Object, This, Info);
3538
3539 if (Object->isGLValue())
3540 return EvaluateLValue(Object, This, Info);
3541
Richard Smithd9f663b2013-04-22 15:31:51 +00003542 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003543 return EvaluateTemporary(Object, This, Info);
3544
Faisal Valie690b7a2016-07-02 22:34:24 +00003545 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003546 return false;
3547}
3548
3549/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3550/// lvalue referring to the result.
3551///
3552/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003553/// \param LV - An lvalue referring to the base of the member pointer.
3554/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003555/// \param IncludeMember - Specifies whether the member itself is included in
3556/// the resulting LValue subobject designator. This is not possible when
3557/// creating a bound member function.
3558/// \return The field or method declaration to which the member pointer refers,
3559/// or 0 if evaluation fails.
3560static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003561 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003562 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003563 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003564 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003565 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003566 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003567 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003568
3569 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3570 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003571 if (!MemPtr.getDecl()) {
3572 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003573 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003574 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003575 }
Richard Smith253c2a32012-01-27 01:14:48 +00003576
Richard Smith027bf112011-11-17 22:56:20 +00003577 if (MemPtr.isDerivedMember()) {
3578 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003579 // The end of the derived-to-base path for the base object must match the
3580 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003581 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003582 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003583 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003584 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003585 }
Richard Smith027bf112011-11-17 22:56:20 +00003586 unsigned PathLengthToMember =
3587 LV.Designator.Entries.size() - MemPtr.Path.size();
3588 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3589 const CXXRecordDecl *LVDecl = getAsBaseClass(
3590 LV.Designator.Entries[PathLengthToMember + I]);
3591 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003592 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003593 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003594 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003595 }
Richard Smith027bf112011-11-17 22:56:20 +00003596 }
3597
3598 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003599 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003600 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003601 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003602 } else if (!MemPtr.Path.empty()) {
3603 // Extend the LValue path with the member pointer's path.
3604 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3605 MemPtr.Path.size() + IncludeMember);
3606
3607 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003608 if (const PointerType *PT = LVType->getAs<PointerType>())
3609 LVType = PT->getPointeeType();
3610 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3611 assert(RD && "member pointer access on non-class-type expression");
3612 // The first class in the path is that of the lvalue.
3613 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3614 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003615 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003616 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003617 RD = Base;
3618 }
3619 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003620 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3621 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003622 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003623 }
3624
3625 // Add the member. Note that we cannot build bound member functions here.
3626 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003627 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003628 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003629 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003630 } else if (const IndirectFieldDecl *IFD =
3631 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003632 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003633 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003634 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003635 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003636 }
Richard Smith027bf112011-11-17 22:56:20 +00003637 }
3638
3639 return MemPtr.getDecl();
3640}
3641
Richard Smith84401042013-06-03 05:03:02 +00003642static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3643 const BinaryOperator *BO,
3644 LValue &LV,
3645 bool IncludeMember = true) {
3646 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3647
3648 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003649 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003650 MemberPtr MemPtr;
3651 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3652 }
Craig Topper36250ad2014-05-12 05:36:57 +00003653 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003654 }
3655
3656 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3657 BO->getRHS(), IncludeMember);
3658}
3659
Richard Smith027bf112011-11-17 22:56:20 +00003660/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3661/// the provided lvalue, which currently refers to the base object.
3662static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3663 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003664 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003665 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003666 return false;
3667
Richard Smitha8105bc2012-01-06 16:39:00 +00003668 QualType TargetQT = E->getType();
3669 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3670 TargetQT = PT->getPointeeType();
3671
3672 // Check this cast lands within the final derived-to-base subobject path.
3673 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003674 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003675 << D.MostDerivedType << TargetQT;
3676 return false;
3677 }
3678
Richard Smith027bf112011-11-17 22:56:20 +00003679 // Check the type of the final cast. We don't need to check the path,
3680 // since a cast can only be formed if the path is unique.
3681 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003682 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3683 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003684 if (NewEntriesSize == D.MostDerivedPathLength)
3685 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3686 else
Richard Smith027bf112011-11-17 22:56:20 +00003687 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003688 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003689 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003690 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003691 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003692 }
Richard Smith027bf112011-11-17 22:56:20 +00003693
3694 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003695 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003696}
3697
Mike Stump876387b2009-10-27 22:09:17 +00003698namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003699enum EvalStmtResult {
3700 /// Evaluation failed.
3701 ESR_Failed,
3702 /// Hit a 'return' statement.
3703 ESR_Returned,
3704 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003705 ESR_Succeeded,
3706 /// Hit a 'continue' statement.
3707 ESR_Continue,
3708 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003709 ESR_Break,
3710 /// Still scanning for 'case' or 'default' statement.
3711 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003712};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003713}
Richard Smith254a73d2011-10-28 22:34:42 +00003714
Richard Smith97fcf4b2016-08-14 23:15:52 +00003715static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3716 // We don't need to evaluate the initializer for a static local.
3717 if (!VD->hasLocalStorage())
3718 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003719
Richard Smith97fcf4b2016-08-14 23:15:52 +00003720 LValue Result;
3721 Result.set(VD, Info.CurrentCall->Index);
3722 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003723
Richard Smith97fcf4b2016-08-14 23:15:52 +00003724 const Expr *InitE = VD->getInit();
3725 if (!InitE) {
3726 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3727 << false << VD->getType();
3728 Val = APValue();
3729 return false;
3730 }
Richard Smith51f03172013-06-20 03:00:05 +00003731
Richard Smith97fcf4b2016-08-14 23:15:52 +00003732 if (InitE->isValueDependent())
3733 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003734
Richard Smith97fcf4b2016-08-14 23:15:52 +00003735 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3736 // Wipe out any partially-computed value, to allow tracking that this
3737 // evaluation failed.
3738 Val = APValue();
3739 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003740 }
3741
3742 return true;
3743}
3744
Richard Smith97fcf4b2016-08-14 23:15:52 +00003745static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3746 bool OK = true;
3747
3748 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3749 OK &= EvaluateVarDecl(Info, VD);
3750
3751 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3752 for (auto *BD : DD->bindings())
3753 if (auto *VD = BD->getHoldingVar())
3754 OK &= EvaluateDecl(Info, VD);
3755
3756 return OK;
3757}
3758
3759
Richard Smith4e18ca52013-05-06 05:56:11 +00003760/// Evaluate a condition (either a variable declaration or an expression).
3761static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3762 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003763 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003764 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3765 return false;
3766 return EvaluateAsBooleanCondition(Cond, Result, Info);
3767}
3768
Richard Smith89210072016-04-04 23:29:43 +00003769namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003770/// \brief A location where the result (returned value) of evaluating a
3771/// statement should be stored.
3772struct StmtResult {
3773 /// The APValue that should be filled in with the returned value.
3774 APValue &Value;
3775 /// The location containing the result, if any (used to support RVO).
3776 const LValue *Slot;
3777};
Richard Smith89210072016-04-04 23:29:43 +00003778}
Richard Smith52a980a2015-08-28 02:43:42 +00003779
3780static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003781 const Stmt *S,
3782 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003783
3784/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003785static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003786 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003787 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003788 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003789 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003790 case ESR_Break:
3791 return ESR_Succeeded;
3792 case ESR_Succeeded:
3793 case ESR_Continue:
3794 return ESR_Continue;
3795 case ESR_Failed:
3796 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003797 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003798 return ESR;
3799 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003800 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003801}
3802
Richard Smith496ddcf2013-05-12 17:32:42 +00003803/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003804static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003805 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003806 BlockScopeRAII Scope(Info);
3807
Richard Smith496ddcf2013-05-12 17:32:42 +00003808 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003809 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003810 {
3811 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003812 if (const Stmt *Init = SS->getInit()) {
3813 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3814 if (ESR != ESR_Succeeded)
3815 return ESR;
3816 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003817 if (SS->getConditionVariable() &&
3818 !EvaluateDecl(Info, SS->getConditionVariable()))
3819 return ESR_Failed;
3820 if (!EvaluateInteger(SS->getCond(), Value, Info))
3821 return ESR_Failed;
3822 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003823
3824 // Find the switch case corresponding to the value of the condition.
3825 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003826 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003827 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3828 SC = SC->getNextSwitchCase()) {
3829 if (isa<DefaultStmt>(SC)) {
3830 Found = SC;
3831 continue;
3832 }
3833
3834 const CaseStmt *CS = cast<CaseStmt>(SC);
3835 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3836 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3837 : LHS;
3838 if (LHS <= Value && Value <= RHS) {
3839 Found = SC;
3840 break;
3841 }
3842 }
3843
3844 if (!Found)
3845 return ESR_Succeeded;
3846
3847 // Search the switch body for the switch case and evaluate it from there.
3848 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3849 case ESR_Break:
3850 return ESR_Succeeded;
3851 case ESR_Succeeded:
3852 case ESR_Continue:
3853 case ESR_Failed:
3854 case ESR_Returned:
3855 return ESR;
3856 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003857 // This can only happen if the switch case is nested within a statement
3858 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003859 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003860 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003861 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003862 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003863}
3864
Richard Smith254a73d2011-10-28 22:34:42 +00003865// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003866static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003867 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003868 if (!Info.nextStep(S))
3869 return ESR_Failed;
3870
Richard Smith496ddcf2013-05-12 17:32:42 +00003871 // If we're hunting down a 'case' or 'default' label, recurse through
3872 // substatements until we hit the label.
3873 if (Case) {
3874 // FIXME: We don't start the lifetime of objects whose initialization we
3875 // jump over. However, such objects must be of class type with a trivial
3876 // default constructor that initialize all subobjects, so must be empty,
3877 // so this almost never matters.
3878 switch (S->getStmtClass()) {
3879 case Stmt::CompoundStmtClass:
3880 // FIXME: Precompute which substatement of a compound statement we
3881 // would jump to, and go straight there rather than performing a
3882 // linear scan each time.
3883 case Stmt::LabelStmtClass:
3884 case Stmt::AttributedStmtClass:
3885 case Stmt::DoStmtClass:
3886 break;
3887
3888 case Stmt::CaseStmtClass:
3889 case Stmt::DefaultStmtClass:
3890 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003891 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003892 break;
3893
3894 case Stmt::IfStmtClass: {
3895 // FIXME: Precompute which side of an 'if' we would jump to, and go
3896 // straight there rather than scanning both sides.
3897 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003898
3899 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3900 // preceded by our switch label.
3901 BlockScopeRAII Scope(Info);
3902
Richard Smith496ddcf2013-05-12 17:32:42 +00003903 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3904 if (ESR != ESR_CaseNotFound || !IS->getElse())
3905 return ESR;
3906 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3907 }
3908
3909 case Stmt::WhileStmtClass: {
3910 EvalStmtResult ESR =
3911 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3912 if (ESR != ESR_Continue)
3913 return ESR;
3914 break;
3915 }
3916
3917 case Stmt::ForStmtClass: {
3918 const ForStmt *FS = cast<ForStmt>(S);
3919 EvalStmtResult ESR =
3920 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3921 if (ESR != ESR_Continue)
3922 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003923 if (FS->getInc()) {
3924 FullExpressionRAII IncScope(Info);
3925 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3926 return ESR_Failed;
3927 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003928 break;
3929 }
3930
3931 case Stmt::DeclStmtClass:
3932 // FIXME: If the variable has initialization that can't be jumped over,
3933 // bail out of any immediately-surrounding compound-statement too.
3934 default:
3935 return ESR_CaseNotFound;
3936 }
3937 }
3938
Richard Smith254a73d2011-10-28 22:34:42 +00003939 switch (S->getStmtClass()) {
3940 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003941 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003942 // Don't bother evaluating beyond an expression-statement which couldn't
3943 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003944 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003945 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003946 return ESR_Failed;
3947 return ESR_Succeeded;
3948 }
3949
Faisal Valie690b7a2016-07-02 22:34:24 +00003950 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003951 return ESR_Failed;
3952
3953 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003954 return ESR_Succeeded;
3955
Richard Smithd9f663b2013-04-22 15:31:51 +00003956 case Stmt::DeclStmtClass: {
3957 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003958 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003959 // Each declaration initialization is its own full-expression.
3960 // FIXME: This isn't quite right; if we're performing aggregate
3961 // initialization, each braced subexpression is its own full-expression.
3962 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003963 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003964 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003965 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003966 return ESR_Succeeded;
3967 }
3968
Richard Smith357362d2011-12-13 06:39:58 +00003969 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003970 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003971 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003972 if (RetExpr &&
3973 !(Result.Slot
3974 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3975 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003976 return ESR_Failed;
3977 return ESR_Returned;
3978 }
Richard Smith254a73d2011-10-28 22:34:42 +00003979
3980 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003981 BlockScopeRAII Scope(Info);
3982
Richard Smith254a73d2011-10-28 22:34:42 +00003983 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003984 for (const auto *BI : CS->body()) {
3985 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003986 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003987 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003988 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003989 return ESR;
3990 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003991 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003992 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003993
3994 case Stmt::IfStmtClass: {
3995 const IfStmt *IS = cast<IfStmt>(S);
3996
3997 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003998 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003999 if (const Stmt *Init = IS->getInit()) {
4000 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4001 if (ESR != ESR_Succeeded)
4002 return ESR;
4003 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004004 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004005 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004006 return ESR_Failed;
4007
4008 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4009 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4010 if (ESR != ESR_Succeeded)
4011 return ESR;
4012 }
4013 return ESR_Succeeded;
4014 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004015
4016 case Stmt::WhileStmtClass: {
4017 const WhileStmt *WS = cast<WhileStmt>(S);
4018 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004019 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004020 bool Continue;
4021 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4022 Continue))
4023 return ESR_Failed;
4024 if (!Continue)
4025 break;
4026
4027 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4028 if (ESR != ESR_Continue)
4029 return ESR;
4030 }
4031 return ESR_Succeeded;
4032 }
4033
4034 case Stmt::DoStmtClass: {
4035 const DoStmt *DS = cast<DoStmt>(S);
4036 bool Continue;
4037 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004038 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004039 if (ESR != ESR_Continue)
4040 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004041 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004042
Richard Smith08d6a2c2013-07-24 07:11:57 +00004043 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004044 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4045 return ESR_Failed;
4046 } while (Continue);
4047 return ESR_Succeeded;
4048 }
4049
4050 case Stmt::ForStmtClass: {
4051 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004052 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004053 if (FS->getInit()) {
4054 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4055 if (ESR != ESR_Succeeded)
4056 return ESR;
4057 }
4058 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004059 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004060 bool Continue = true;
4061 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4062 FS->getCond(), Continue))
4063 return ESR_Failed;
4064 if (!Continue)
4065 break;
4066
4067 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4068 if (ESR != ESR_Continue)
4069 return ESR;
4070
Richard Smith08d6a2c2013-07-24 07:11:57 +00004071 if (FS->getInc()) {
4072 FullExpressionRAII IncScope(Info);
4073 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4074 return ESR_Failed;
4075 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004076 }
4077 return ESR_Succeeded;
4078 }
4079
Richard Smith896e0d72013-05-06 06:51:17 +00004080 case Stmt::CXXForRangeStmtClass: {
4081 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004082 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004083
4084 // Initialize the __range variable.
4085 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4086 if (ESR != ESR_Succeeded)
4087 return ESR;
4088
4089 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004090 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4091 if (ESR != ESR_Succeeded)
4092 return ESR;
4093 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004094 if (ESR != ESR_Succeeded)
4095 return ESR;
4096
4097 while (true) {
4098 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004099 {
4100 bool Continue = true;
4101 FullExpressionRAII CondExpr(Info);
4102 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4103 return ESR_Failed;
4104 if (!Continue)
4105 break;
4106 }
Richard Smith896e0d72013-05-06 06:51:17 +00004107
4108 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004109 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004110 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4111 if (ESR != ESR_Succeeded)
4112 return ESR;
4113
4114 // Loop body.
4115 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4116 if (ESR != ESR_Continue)
4117 return ESR;
4118
4119 // Increment: ++__begin
4120 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4121 return ESR_Failed;
4122 }
4123
4124 return ESR_Succeeded;
4125 }
4126
Richard Smith496ddcf2013-05-12 17:32:42 +00004127 case Stmt::SwitchStmtClass:
4128 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4129
Richard Smith4e18ca52013-05-06 05:56:11 +00004130 case Stmt::ContinueStmtClass:
4131 return ESR_Continue;
4132
4133 case Stmt::BreakStmtClass:
4134 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004135
4136 case Stmt::LabelStmtClass:
4137 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4138
4139 case Stmt::AttributedStmtClass:
4140 // As a general principle, C++11 attributes can be ignored without
4141 // any semantic impact.
4142 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4143 Case);
4144
4145 case Stmt::CaseStmtClass:
4146 case Stmt::DefaultStmtClass:
4147 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004148 }
4149}
4150
Richard Smithcc36f692011-12-22 02:22:31 +00004151/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4152/// default constructor. If so, we'll fold it whether or not it's marked as
4153/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4154/// so we need special handling.
4155static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004156 const CXXConstructorDecl *CD,
4157 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004158 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4159 return false;
4160
Richard Smith66e05fe2012-01-18 05:21:49 +00004161 // Value-initialization does not call a trivial default constructor, so such a
4162 // call is a core constant expression whether or not the constructor is
4163 // constexpr.
4164 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004165 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004166 // FIXME: If DiagDecl is an implicitly-declared special member function,
4167 // we should be much more explicit about why it's not constexpr.
4168 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4169 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4170 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004171 } else {
4172 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4173 }
4174 }
4175 return true;
4176}
4177
Richard Smith357362d2011-12-13 06:39:58 +00004178/// CheckConstexprFunction - Check that a function can be called in a constant
4179/// expression.
4180static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4181 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004182 const FunctionDecl *Definition,
4183 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004184 // Potential constant expressions can contain calls to declared, but not yet
4185 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004186 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004187 Declaration->isConstexpr())
4188 return false;
4189
Richard Smith0838f3a2013-05-14 05:18:44 +00004190 // Bail out with no diagnostic if the function declaration itself is invalid.
4191 // We will have produced a relevant diagnostic while parsing it.
4192 if (Declaration->isInvalidDecl())
4193 return false;
4194
Richard Smith357362d2011-12-13 06:39:58 +00004195 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004196 if (Definition && Definition->isConstexpr() &&
4197 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004198 return true;
4199
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004200 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004201 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004202
Richard Smith5179eb72016-06-28 19:03:57 +00004203 // If this function is not constexpr because it is an inherited
4204 // non-constexpr constructor, diagnose that directly.
4205 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4206 if (CD && CD->isInheritingConstructor()) {
4207 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004208 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004209 DiagDecl = CD = Inherited;
4210 }
4211
4212 // FIXME: If DiagDecl is an implicitly-declared special member function
4213 // or an inheriting constructor, we should be much more explicit about why
4214 // it's not constexpr.
4215 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004216 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004217 << CD->getInheritedConstructor().getConstructor()->getParent();
4218 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004219 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004220 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004221 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4222 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004223 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004224 }
4225 return false;
4226}
4227
Richard Smithbe6dd812014-11-19 21:27:17 +00004228/// Determine if a class has any fields that might need to be copied by a
4229/// trivial copy or move operation.
4230static bool hasFields(const CXXRecordDecl *RD) {
4231 if (!RD || RD->isEmpty())
4232 return false;
4233 for (auto *FD : RD->fields()) {
4234 if (FD->isUnnamedBitfield())
4235 continue;
4236 return true;
4237 }
4238 for (auto &Base : RD->bases())
4239 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4240 return true;
4241 return false;
4242}
4243
Richard Smithd62306a2011-11-10 06:34:14 +00004244namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004245typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004246}
4247
4248/// EvaluateArgs - Evaluate the arguments to a function call.
4249static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4250 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004251 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004252 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004253 I != E; ++I) {
4254 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4255 // If we're checking for a potential constant expression, evaluate all
4256 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004257 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004258 return false;
4259 Success = false;
4260 }
4261 }
4262 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004263}
4264
Richard Smith254a73d2011-10-28 22:34:42 +00004265/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004266static bool HandleFunctionCall(SourceLocation CallLoc,
4267 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004268 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004269 EvalInfo &Info, APValue &Result,
4270 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004271 ArgVector ArgValues(Args.size());
4272 if (!EvaluateArgs(Args, ArgValues, Info))
4273 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004274
Richard Smith253c2a32012-01-27 01:14:48 +00004275 if (!Info.CheckCallLimit(CallLoc))
4276 return false;
4277
4278 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004279
4280 // For a trivial copy or move assignment, perform an APValue copy. This is
4281 // essential for unions, where the operations performed by the assignment
4282 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004283 //
4284 // Skip this for non-union classes with no fields; in that case, the defaulted
4285 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004286 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004287 if (MD && MD->isDefaulted() &&
4288 (MD->getParent()->isUnion() ||
4289 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004290 assert(This &&
4291 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4292 LValue RHS;
4293 RHS.setFrom(Info.Ctx, ArgValues[0]);
4294 APValue RHSValue;
4295 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4296 RHS, RHSValue))
4297 return false;
4298 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4299 RHSValue))
4300 return false;
4301 This->moveInto(Result);
4302 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004303 } else if (MD && isLambdaCallOperator(MD)) {
4304 // We're in a lambda; determine the lambda capture field maps.
4305 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4306 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004307 }
4308
Richard Smith52a980a2015-08-28 02:43:42 +00004309 StmtResult Ret = {Result, ResultSlot};
4310 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004311 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004312 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004313 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004314 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004315 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004316 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004317}
4318
Richard Smithd62306a2011-11-10 06:34:14 +00004319/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004320static bool HandleConstructorCall(const Expr *E, const LValue &This,
4321 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004322 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004323 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004324 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004325 if (!Info.CheckCallLimit(CallLoc))
4326 return false;
4327
Richard Smith3607ffe2012-02-13 03:54:03 +00004328 const CXXRecordDecl *RD = Definition->getParent();
4329 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004330 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004331 return false;
4332 }
4333
Erik Pilkington42925492017-10-04 00:18:55 +00004334 EvalInfo::EvaluatingConstructorRAII EvalObj(
4335 Info, {This.getLValueBase(), This.CallIndex});
Richard Smith5179eb72016-06-28 19:03:57 +00004336 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004337
Richard Smith52a980a2015-08-28 02:43:42 +00004338 // FIXME: Creating an APValue just to hold a nonexistent return value is
4339 // wasteful.
4340 APValue RetVal;
4341 StmtResult Ret = {RetVal, nullptr};
4342
Richard Smith5179eb72016-06-28 19:03:57 +00004343 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004344 if (Definition->isDelegatingConstructor()) {
4345 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004346 {
4347 FullExpressionRAII InitScope(Info);
4348 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4349 return false;
4350 }
Richard Smith52a980a2015-08-28 02:43:42 +00004351 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004352 }
4353
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004354 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004355 // essential for unions (or classes with anonymous union members), where the
4356 // operations performed by the constructor cannot be represented by
4357 // ctor-initializers.
4358 //
4359 // Skip this for empty non-union classes; we should not perform an
4360 // lvalue-to-rvalue conversion on them because their copy constructor does not
4361 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004362 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004363 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004364 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004365 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004366 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004367 return handleLValueToRValueConversion(
4368 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4369 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004370 }
4371
4372 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004373 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004374 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004375 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004376
John McCalld7bca762012-05-01 00:38:49 +00004377 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004378 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4379
Richard Smith08d6a2c2013-07-24 07:11:57 +00004380 // A scope for temporaries lifetime-extended by reference members.
4381 BlockScopeRAII LifetimeExtendedScope(Info);
4382
Richard Smith253c2a32012-01-27 01:14:48 +00004383 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004384 unsigned BasesSeen = 0;
4385#ifndef NDEBUG
4386 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4387#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004388 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004389 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004390 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004391 APValue *Value = &Result;
4392
4393 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004394 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004395 if (I->isBaseInitializer()) {
4396 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004397#ifndef NDEBUG
4398 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004399 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004400 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4401 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4402 "base class initializers not in expected order");
4403 ++BaseIt;
4404#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004405 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004406 BaseType->getAsCXXRecordDecl(), &Layout))
4407 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004408 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004409 } else if ((FD = I->getMember())) {
4410 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004411 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004412 if (RD->isUnion()) {
4413 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004414 Value = &Result.getUnionValue();
4415 } else {
4416 Value = &Result.getStructField(FD->getFieldIndex());
4417 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004418 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004419 // Walk the indirect field decl's chain to find the object to initialize,
4420 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004421 auto IndirectFieldChain = IFD->chain();
4422 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004423 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004424 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4425 // Switch the union field if it differs. This happens if we had
4426 // preceding zero-initialization, and we're now initializing a union
4427 // subobject other than the first.
4428 // FIXME: In this case, the values of the other subobjects are
4429 // specified, since zero-initialization sets all padding bits to zero.
4430 if (Value->isUninit() ||
4431 (Value->isUnion() && Value->getUnionField() != FD)) {
4432 if (CD->isUnion())
4433 *Value = APValue(FD);
4434 else
4435 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004436 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004437 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004438 // Store Subobject as its parent before updating it for the last element
4439 // in the chain.
4440 if (C == IndirectFieldChain.back())
4441 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004442 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004443 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004444 if (CD->isUnion())
4445 Value = &Value->getUnionValue();
4446 else
4447 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004448 }
Richard Smithd62306a2011-11-10 06:34:14 +00004449 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004450 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004451 }
Richard Smith253c2a32012-01-27 01:14:48 +00004452
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004453 // Need to override This for implicit field initializers as in this case
4454 // This refers to innermost anonymous struct/union containing initializer,
4455 // not to currently constructed class.
4456 const Expr *Init = I->getInit();
4457 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4458 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004459 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004460 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4461 (FD && FD->isBitField() &&
4462 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004463 // If we're checking for a potential constant expression, evaluate all
4464 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004465 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004466 return false;
4467 Success = false;
4468 }
Richard Smithd62306a2011-11-10 06:34:14 +00004469 }
4470
Richard Smithd9f663b2013-04-22 15:31:51 +00004471 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004472 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004473}
4474
Richard Smith5179eb72016-06-28 19:03:57 +00004475static bool HandleConstructorCall(const Expr *E, const LValue &This,
4476 ArrayRef<const Expr*> Args,
4477 const CXXConstructorDecl *Definition,
4478 EvalInfo &Info, APValue &Result) {
4479 ArgVector ArgValues(Args.size());
4480 if (!EvaluateArgs(Args, ArgValues, Info))
4481 return false;
4482
4483 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4484 Info, Result);
4485}
4486
Eli Friedman9a156e52008-11-12 09:44:48 +00004487//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004488// Generic Evaluation
4489//===----------------------------------------------------------------------===//
4490namespace {
4491
Aaron Ballman68af21c2014-01-03 19:26:43 +00004492template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004493class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004494 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004495private:
Richard Smith52a980a2015-08-28 02:43:42 +00004496 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004497 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004498 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004499 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004500 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004501 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004502 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004503
Richard Smith17100ba2012-02-16 02:46:34 +00004504 // Check whether a conditional operator with a non-constant condition is a
4505 // potential constant expression. If neither arm is a potential constant
4506 // expression, then the conditional operator is not either.
4507 template<typename ConditionalOperator>
4508 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004509 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004510
4511 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004512 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004513 {
Richard Smith17100ba2012-02-16 02:46:34 +00004514 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004515 StmtVisitorTy::Visit(E->getFalseExpr());
4516 if (Diag.empty())
4517 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004518 }
Richard Smith17100ba2012-02-16 02:46:34 +00004519
George Burgess IV8c892b52016-05-25 22:31:54 +00004520 {
4521 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004522 Diag.clear();
4523 StmtVisitorTy::Visit(E->getTrueExpr());
4524 if (Diag.empty())
4525 return;
4526 }
4527
4528 Error(E, diag::note_constexpr_conditional_never_const);
4529 }
4530
4531
4532 template<typename ConditionalOperator>
4533 bool HandleConditionalOperator(const ConditionalOperator *E) {
4534 bool BoolResult;
4535 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004536 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004537 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004538 return false;
4539 }
4540 if (Info.noteFailure()) {
4541 StmtVisitorTy::Visit(E->getTrueExpr());
4542 StmtVisitorTy::Visit(E->getFalseExpr());
4543 }
Richard Smith17100ba2012-02-16 02:46:34 +00004544 return false;
4545 }
4546
4547 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4548 return StmtVisitorTy::Visit(EvalExpr);
4549 }
4550
Peter Collingbournee9200682011-05-13 03:29:01 +00004551protected:
4552 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004553 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004554 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4555
Richard Smith92b1ce02011-12-12 09:28:41 +00004556 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004557 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004558 }
4559
Aaron Ballman68af21c2014-01-03 19:26:43 +00004560 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004561
4562public:
4563 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4564
4565 EvalInfo &getEvalInfo() { return Info; }
4566
Richard Smithf57d8cb2011-12-09 22:58:01 +00004567 /// Report an evaluation error. This should only be called when an error is
4568 /// first discovered. When propagating an error, just return false.
4569 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004570 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004571 return false;
4572 }
4573 bool Error(const Expr *E) {
4574 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4575 }
4576
Aaron Ballman68af21c2014-01-03 19:26:43 +00004577 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004578 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004579 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004580 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004581 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004582 }
4583
Aaron Ballman68af21c2014-01-03 19:26:43 +00004584 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004585 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004586 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004587 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004588 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004589 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004590 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004591 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004592 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004593 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004594 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004595 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004596 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004597 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004598 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004599 // The initializer may not have been parsed yet, or might be erroneous.
4600 if (!E->getExpr())
4601 return Error(E);
4602 return StmtVisitorTy::Visit(E->getExpr());
4603 }
Richard Smith5894a912011-12-19 22:12:41 +00004604 // We cannot create any objects for which cleanups are required, so there is
4605 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004606 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004607 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004608
Aaron Ballman68af21c2014-01-03 19:26:43 +00004609 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004610 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4611 return static_cast<Derived*>(this)->VisitCastExpr(E);
4612 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004613 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004614 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4615 return static_cast<Derived*>(this)->VisitCastExpr(E);
4616 }
4617
Aaron Ballman68af21c2014-01-03 19:26:43 +00004618 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004619 switch (E->getOpcode()) {
4620 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004621 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004622
4623 case BO_Comma:
4624 VisitIgnoredValue(E->getLHS());
4625 return StmtVisitorTy::Visit(E->getRHS());
4626
4627 case BO_PtrMemD:
4628 case BO_PtrMemI: {
4629 LValue Obj;
4630 if (!HandleMemberPointerAccess(Info, E, Obj))
4631 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004632 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004633 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004634 return false;
4635 return DerivedSuccess(Result, E);
4636 }
4637 }
4638 }
4639
Aaron Ballman68af21c2014-01-03 19:26:43 +00004640 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004641 // Evaluate and cache the common expression. We treat it as a temporary,
4642 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004643 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004644 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004645 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004646
Richard Smith17100ba2012-02-16 02:46:34 +00004647 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004648 }
4649
Aaron Ballman68af21c2014-01-03 19:26:43 +00004650 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004651 bool IsBcpCall = false;
4652 // If the condition (ignoring parens) is a __builtin_constant_p call,
4653 // the result is a constant expression if it can be folded without
4654 // side-effects. This is an important GNU extension. See GCC PR38377
4655 // for discussion.
4656 if (const CallExpr *CallCE =
4657 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004658 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004659 IsBcpCall = true;
4660
4661 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4662 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004663 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004664 return false;
4665
Richard Smith6d4c6582013-11-05 22:18:15 +00004666 FoldConstant Fold(Info, IsBcpCall);
4667 if (!HandleConditionalOperator(E)) {
4668 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004669 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004670 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004671
4672 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004673 }
4674
Aaron Ballman68af21c2014-01-03 19:26:43 +00004675 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004676 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4677 return DerivedSuccess(*Value, E);
4678
4679 const Expr *Source = E->getSourceExpr();
4680 if (!Source)
4681 return Error(E);
4682 if (Source == E) { // sanity checking.
4683 assert(0 && "OpaqueValueExpr recursively refers to itself");
4684 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004685 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004686 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004687 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004688
Aaron Ballman68af21c2014-01-03 19:26:43 +00004689 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004690 APValue Result;
4691 if (!handleCallExpr(E, Result, nullptr))
4692 return false;
4693 return DerivedSuccess(Result, E);
4694 }
4695
4696 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004697 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004698 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004699 QualType CalleeType = Callee->getType();
4700
Craig Topper36250ad2014-05-12 05:36:57 +00004701 const FunctionDecl *FD = nullptr;
4702 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004703 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004704 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004705
Richard Smithe97cbd72011-11-11 04:05:33 +00004706 // Extract function decl and 'this' pointer from the callee.
4707 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004708 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004709 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4710 // Explicit bound member calls, such as x.f() or p->g();
4711 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004712 return false;
4713 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004714 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004715 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004716 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4717 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004718 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4719 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004720 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004721 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004722 return Error(Callee);
4723
4724 FD = dyn_cast<FunctionDecl>(Member);
4725 if (!FD)
4726 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004727 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004728 LValue Call;
4729 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004730 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004731
Richard Smitha8105bc2012-01-06 16:39:00 +00004732 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004733 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004734 FD = dyn_cast_or_null<FunctionDecl>(
4735 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004736 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004737 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004738 // Don't call function pointers which have been cast to some other type.
4739 // Per DR (no number yet), the caller and callee can differ in noexcept.
4740 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4741 CalleeType->getPointeeType(), FD->getType())) {
4742 return Error(E);
4743 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004744
4745 // Overloaded operator calls to member functions are represented as normal
4746 // calls with '*this' as the first argument.
4747 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4748 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004749 // FIXME: When selecting an implicit conversion for an overloaded
4750 // operator delete, we sometimes try to evaluate calls to conversion
4751 // operators without a 'this' parameter!
4752 if (Args.empty())
4753 return Error(E);
4754
Nick Lewycky13073a62017-06-12 21:15:44 +00004755 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004756 return false;
4757 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004758 Args = Args.slice(1);
Daniel Jasperffdee092017-05-02 19:21:42 +00004759 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004760 // Map the static invoker for the lambda back to the call operator.
4761 // Conveniently, we don't have to slice out the 'this' argument (as is
4762 // being done for the non-static case), since a static member function
4763 // doesn't have an implicit argument passed in.
4764 const CXXRecordDecl *ClosureClass = MD->getParent();
4765 assert(
4766 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4767 "Number of captures must be zero for conversion to function-ptr");
4768
4769 const CXXMethodDecl *LambdaCallOp =
4770 ClosureClass->getLambdaCallOperator();
4771
4772 // Set 'FD', the function that will be called below, to the call
4773 // operator. If the closure object represents a generic lambda, find
4774 // the corresponding specialization of the call operator.
4775
4776 if (ClosureClass->isGenericLambda()) {
4777 assert(MD->isFunctionTemplateSpecialization() &&
4778 "A generic lambda's static-invoker function must be a "
4779 "template specialization");
4780 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4781 FunctionTemplateDecl *CallOpTemplate =
4782 LambdaCallOp->getDescribedFunctionTemplate();
4783 void *InsertPos = nullptr;
4784 FunctionDecl *CorrespondingCallOpSpecialization =
4785 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4786 assert(CorrespondingCallOpSpecialization &&
4787 "We must always have a function call operator specialization "
4788 "that corresponds to our static invoker specialization");
4789 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4790 } else
4791 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004792 }
4793
Daniel Jasperffdee092017-05-02 19:21:42 +00004794
Richard Smithe97cbd72011-11-11 04:05:33 +00004795 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004796 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004797
Richard Smith47b34932012-02-01 02:39:43 +00004798 if (This && !This->checkSubobject(Info, E, CSK_This))
4799 return false;
4800
Richard Smith3607ffe2012-02-13 03:54:03 +00004801 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4802 // calls to such functions in constant expressions.
4803 if (This && !HasQualifier &&
4804 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4805 return Error(E, diag::note_constexpr_virtual_call);
4806
Craig Topper36250ad2014-05-12 05:36:57 +00004807 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004808 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004809
Nick Lewycky13073a62017-06-12 21:15:44 +00004810 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4811 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004812 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004813 return false;
4814
Richard Smith52a980a2015-08-28 02:43:42 +00004815 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004816 }
4817
Aaron Ballman68af21c2014-01-03 19:26:43 +00004818 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004819 return StmtVisitorTy::Visit(E->getInitializer());
4820 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004821 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004822 if (E->getNumInits() == 0)
4823 return DerivedZeroInitialization(E);
4824 if (E->getNumInits() == 1)
4825 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004826 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004827 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004828 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004829 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004830 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004831 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004832 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004833 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004834 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004835 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004836 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004837
Richard Smithd62306a2011-11-10 06:34:14 +00004838 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004839 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004840 assert(!E->isArrow() && "missing call to bound member function?");
4841
Richard Smith2e312c82012-03-03 22:46:17 +00004842 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004843 if (!Evaluate(Val, Info, E->getBase()))
4844 return false;
4845
4846 QualType BaseTy = E->getBase()->getType();
4847
4848 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004849 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004850 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004851 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004852 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4853
Richard Smith9defb7d2018-02-21 03:38:30 +00004854 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00004855 SubobjectDesignator Designator(BaseTy);
4856 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004857
Richard Smith3229b742013-05-05 21:17:10 +00004858 APValue Result;
4859 return extractSubobject(Info, E, Obj, Designator, Result) &&
4860 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004861 }
4862
Aaron Ballman68af21c2014-01-03 19:26:43 +00004863 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004864 switch (E->getCastKind()) {
4865 default:
4866 break;
4867
Richard Smitha23ab512013-05-23 00:30:41 +00004868 case CK_AtomicToNonAtomic: {
4869 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004870 // This does not need to be done in place even for class/array types:
4871 // atomic-to-non-atomic conversion implies copying the object
4872 // representation.
4873 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004874 return false;
4875 return DerivedSuccess(AtomicVal, E);
4876 }
4877
Richard Smith11562c52011-10-28 17:51:58 +00004878 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004879 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004880 return StmtVisitorTy::Visit(E->getSubExpr());
4881
4882 case CK_LValueToRValue: {
4883 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004884 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4885 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004886 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004887 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004888 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004889 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004890 return false;
4891 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004892 }
4893 }
4894
Richard Smithf57d8cb2011-12-09 22:58:01 +00004895 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004896 }
4897
Aaron Ballman68af21c2014-01-03 19:26:43 +00004898 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004899 return VisitUnaryPostIncDec(UO);
4900 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004901 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004902 return VisitUnaryPostIncDec(UO);
4903 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004904 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004905 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004906 return Error(UO);
4907
4908 LValue LVal;
4909 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4910 return false;
4911 APValue RVal;
4912 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4913 UO->isIncrementOp(), &RVal))
4914 return false;
4915 return DerivedSuccess(RVal, UO);
4916 }
4917
Aaron Ballman68af21c2014-01-03 19:26:43 +00004918 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004919 // We will have checked the full-expressions inside the statement expression
4920 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004921 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004922 return Error(E);
4923
Richard Smith08d6a2c2013-07-24 07:11:57 +00004924 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004925 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004926 if (CS->body_empty())
4927 return true;
4928
Richard Smith51f03172013-06-20 03:00:05 +00004929 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4930 BE = CS->body_end();
4931 /**/; ++BI) {
4932 if (BI + 1 == BE) {
4933 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4934 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004935 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004936 diag::note_constexpr_stmt_expr_unsupported);
4937 return false;
4938 }
4939 return this->Visit(FinalExpr);
4940 }
4941
4942 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004943 StmtResult Result = { ReturnValue, nullptr };
4944 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004945 if (ESR != ESR_Succeeded) {
4946 // FIXME: If the statement-expression terminated due to 'return',
4947 // 'break', or 'continue', it would be nice to propagate that to
4948 // the outer statement evaluation rather than bailing out.
4949 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004950 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004951 diag::note_constexpr_stmt_expr_unsupported);
4952 return false;
4953 }
4954 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004955
4956 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004957 }
4958
Richard Smith4a678122011-10-24 18:44:57 +00004959 /// Visit a value which is evaluated, but whose value is ignored.
4960 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004961 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004962 }
David Majnemere9807b22016-02-26 04:23:19 +00004963
4964 /// Potentially visit a MemberExpr's base expression.
4965 void VisitIgnoredBaseExpression(const Expr *E) {
4966 // While MSVC doesn't evaluate the base expression, it does diagnose the
4967 // presence of side-effecting behavior.
4968 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4969 return;
4970 VisitIgnoredValue(E);
4971 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004972};
4973
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004974}
Peter Collingbournee9200682011-05-13 03:29:01 +00004975
4976//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004977// Common base class for lvalue and temporary evaluation.
4978//===----------------------------------------------------------------------===//
4979namespace {
4980template<class Derived>
4981class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004982 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004983protected:
4984 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004985 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004986 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004987 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004988
4989 bool Success(APValue::LValueBase B) {
4990 Result.set(B);
4991 return true;
4992 }
4993
George Burgess IVf9013bf2017-02-10 22:52:29 +00004994 bool evaluatePointer(const Expr *E, LValue &Result) {
4995 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4996 }
4997
Richard Smith027bf112011-11-17 22:56:20 +00004998public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004999 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5000 : ExprEvaluatorBaseTy(Info), Result(Result),
5001 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005002
Richard Smith2e312c82012-03-03 22:46:17 +00005003 bool Success(const APValue &V, const Expr *E) {
5004 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005005 return true;
5006 }
Richard Smith027bf112011-11-17 22:56:20 +00005007
Richard Smith027bf112011-11-17 22:56:20 +00005008 bool VisitMemberExpr(const MemberExpr *E) {
5009 // Handle non-static data members.
5010 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005011 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005012 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005013 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005014 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005015 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005016 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005017 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005018 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005019 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005020 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005021 BaseTy = E->getBase()->getType();
5022 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005023 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005024 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005025 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005026 Result.setInvalid(E);
5027 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005028 }
Richard Smith027bf112011-11-17 22:56:20 +00005029
Richard Smith1b78b3d2012-01-25 22:15:11 +00005030 const ValueDecl *MD = E->getMemberDecl();
5031 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5032 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5033 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5034 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005035 if (!HandleLValueMember(this->Info, E, Result, FD))
5036 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005037 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005038 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5039 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005040 } else
5041 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005042
Richard Smith1b78b3d2012-01-25 22:15:11 +00005043 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005044 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005045 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005046 RefValue))
5047 return false;
5048 return Success(RefValue, E);
5049 }
5050 return true;
5051 }
5052
5053 bool VisitBinaryOperator(const BinaryOperator *E) {
5054 switch (E->getOpcode()) {
5055 default:
5056 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5057
5058 case BO_PtrMemD:
5059 case BO_PtrMemI:
5060 return HandleMemberPointerAccess(this->Info, E, Result);
5061 }
5062 }
5063
5064 bool VisitCastExpr(const CastExpr *E) {
5065 switch (E->getCastKind()) {
5066 default:
5067 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5068
5069 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005070 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005071 if (!this->Visit(E->getSubExpr()))
5072 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005073
5074 // Now figure out the necessary offset to add to the base LV to get from
5075 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005076 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5077 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005078 }
5079 }
5080};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005081}
Richard Smith027bf112011-11-17 22:56:20 +00005082
5083//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005084// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005085//
5086// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5087// function designators (in C), decl references to void objects (in C), and
5088// temporaries (if building with -Wno-address-of-temporary).
5089//
5090// LValue evaluation produces values comprising a base expression of one of the
5091// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005092// - Declarations
5093// * VarDecl
5094// * FunctionDecl
5095// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005096// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005097// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005098// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005099// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005100// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005101// * ObjCEncodeExpr
5102// * AddrLabelExpr
5103// * BlockExpr
5104// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005105// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005106// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005107// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005108// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5109// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005110// * A MaterializeTemporaryExpr that has static storage duration, with no
5111// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005112// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005113//===----------------------------------------------------------------------===//
5114namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005115class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005116 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005117public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005118 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5119 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005120
Richard Smith11562c52011-10-28 17:51:58 +00005121 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005122 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005123
Peter Collingbournee9200682011-05-13 03:29:01 +00005124 bool VisitDeclRefExpr(const DeclRefExpr *E);
5125 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005126 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005127 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5128 bool VisitMemberExpr(const MemberExpr *E);
5129 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5130 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005131 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005132 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005133 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5134 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005135 bool VisitUnaryReal(const UnaryOperator *E);
5136 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005137 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5138 return VisitUnaryPreIncDec(UO);
5139 }
5140 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5141 return VisitUnaryPreIncDec(UO);
5142 }
Richard Smith3229b742013-05-05 21:17:10 +00005143 bool VisitBinAssign(const BinaryOperator *BO);
5144 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005145
Peter Collingbournee9200682011-05-13 03:29:01 +00005146 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005147 switch (E->getCastKind()) {
5148 default:
Richard Smith027bf112011-11-17 22:56:20 +00005149 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005150
Eli Friedmance3e02a2011-10-11 00:13:24 +00005151 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005152 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005153 if (!Visit(E->getSubExpr()))
5154 return false;
5155 Result.Designator.setInvalid();
5156 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005157
Richard Smith027bf112011-11-17 22:56:20 +00005158 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005159 if (!Visit(E->getSubExpr()))
5160 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005161 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005162 }
5163 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005164};
5165} // end anonymous namespace
5166
Richard Smith11562c52011-10-28 17:51:58 +00005167/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005168/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005169/// * function designators in C, and
5170/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005171/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005172static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5173 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005174 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005175 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005176 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005177}
5178
Peter Collingbournee9200682011-05-13 03:29:01 +00005179bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005180 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005181 return Success(FD);
5182 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005183 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005184 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005185 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005186 return Error(E);
5187}
Richard Smith733237d2011-10-24 23:14:33 +00005188
Faisal Vali0528a312016-11-13 06:09:16 +00005189
Richard Smith11562c52011-10-28 17:51:58 +00005190bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005191
5192 // If we are within a lambda's call operator, check whether the 'VD' referred
5193 // to within 'E' actually represents a lambda-capture that maps to a
5194 // data-member/field within the closure object, and if so, evaluate to the
5195 // field or what the field refers to.
5196 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5197 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5198 if (Info.checkingPotentialConstantExpression())
5199 return false;
5200 // Start with 'Result' referring to the complete closure object...
5201 Result = *Info.CurrentCall->This;
5202 // ... then update it to refer to the field of the closure object
5203 // that represents the capture.
5204 if (!HandleLValueMember(Info, E, Result, FD))
5205 return false;
5206 // And if the field is of reference type, update 'Result' to refer to what
5207 // the field refers to.
5208 if (FD->getType()->isReferenceType()) {
5209 APValue RVal;
5210 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5211 RVal))
5212 return false;
5213 Result.setFrom(Info.Ctx, RVal);
5214 }
5215 return true;
5216 }
5217 }
Craig Topper36250ad2014-05-12 05:36:57 +00005218 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005219 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5220 // Only if a local variable was declared in the function currently being
5221 // evaluated, do we expect to be able to find its value in the current
5222 // frame. (Otherwise it was likely declared in an enclosing context and
5223 // could either have a valid evaluatable value (for e.g. a constexpr
5224 // variable) or be ill-formed (and trigger an appropriate evaluation
5225 // diagnostic)).
5226 if (Info.CurrentCall->Callee &&
5227 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5228 Frame = Info.CurrentCall;
5229 }
5230 }
Richard Smith3229b742013-05-05 21:17:10 +00005231
Richard Smithfec09922011-11-01 16:57:24 +00005232 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005233 if (Frame) {
5234 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005235 return true;
5236 }
Richard Smithce40ad62011-11-12 22:28:03 +00005237 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005238 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005239
Richard Smith3229b742013-05-05 21:17:10 +00005240 APValue *V;
5241 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005242 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005243 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005244 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005245 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005246 return false;
5247 }
Richard Smith3229b742013-05-05 21:17:10 +00005248 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005249}
5250
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005251bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5252 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005253 // Walk through the expression to find the materialized temporary itself.
5254 SmallVector<const Expr *, 2> CommaLHSs;
5255 SmallVector<SubobjectAdjustment, 2> Adjustments;
5256 const Expr *Inner = E->GetTemporaryExpr()->
5257 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005258
Richard Smith84401042013-06-03 05:03:02 +00005259 // If we passed any comma operators, evaluate their LHSs.
5260 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5261 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5262 return false;
5263
Richard Smithe6c01442013-06-05 00:46:14 +00005264 // A materialized temporary with static storage duration can appear within the
5265 // result of a constant expression evaluation, so we need to preserve its
5266 // value for use outside this evaluation.
5267 APValue *Value;
5268 if (E->getStorageDuration() == SD_Static) {
5269 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005270 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005271 Result.set(E);
5272 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005273 Value = &Info.CurrentCall->
5274 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005275 Result.set(E, Info.CurrentCall->Index);
5276 }
5277
Richard Smithea4ad5d2013-06-06 08:19:16 +00005278 QualType Type = Inner->getType();
5279
Richard Smith84401042013-06-03 05:03:02 +00005280 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005281 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5282 (E->getStorageDuration() == SD_Static &&
5283 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5284 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005285 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005286 }
Richard Smith84401042013-06-03 05:03:02 +00005287
5288 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005289 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5290 --I;
5291 switch (Adjustments[I].Kind) {
5292 case SubobjectAdjustment::DerivedToBaseAdjustment:
5293 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5294 Type, Result))
5295 return false;
5296 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5297 break;
5298
5299 case SubobjectAdjustment::FieldAdjustment:
5300 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5301 return false;
5302 Type = Adjustments[I].Field->getType();
5303 break;
5304
5305 case SubobjectAdjustment::MemberPointerAdjustment:
5306 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5307 Adjustments[I].Ptr.RHS))
5308 return false;
5309 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5310 break;
5311 }
5312 }
5313
5314 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005315}
5316
Peter Collingbournee9200682011-05-13 03:29:01 +00005317bool
5318LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005319 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5320 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005321 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5322 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005323 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005324}
5325
Richard Smith6e525142011-12-27 12:18:28 +00005326bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005327 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005328 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005329
Faisal Valie690b7a2016-07-02 22:34:24 +00005330 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005331 << E->getExprOperand()->getType()
5332 << E->getExprOperand()->getSourceRange();
5333 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005334}
5335
Francois Pichet0066db92012-04-16 04:08:35 +00005336bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5337 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005338}
Francois Pichet0066db92012-04-16 04:08:35 +00005339
Peter Collingbournee9200682011-05-13 03:29:01 +00005340bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005341 // Handle static data members.
5342 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005343 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005344 return VisitVarDecl(E, VD);
5345 }
5346
Richard Smith254a73d2011-10-28 22:34:42 +00005347 // Handle static member functions.
5348 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5349 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005350 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005351 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005352 }
5353 }
5354
Richard Smithd62306a2011-11-10 06:34:14 +00005355 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005356 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005357}
5358
Peter Collingbournee9200682011-05-13 03:29:01 +00005359bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005360 // FIXME: Deal with vectors as array subscript bases.
5361 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005362 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005363
Nick Lewyckyad888682017-04-27 07:27:36 +00005364 bool Success = true;
5365 if (!evaluatePointer(E->getBase(), Result)) {
5366 if (!Info.noteFailure())
5367 return false;
5368 Success = false;
5369 }
Mike Stump11289f42009-09-09 15:08:12 +00005370
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005371 APSInt Index;
5372 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005373 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005374
Nick Lewyckyad888682017-04-27 07:27:36 +00005375 return Success &&
5376 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005377}
Eli Friedman9a156e52008-11-12 09:44:48 +00005378
Peter Collingbournee9200682011-05-13 03:29:01 +00005379bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005380 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005381}
5382
Richard Smith66c96992012-02-18 22:04:06 +00005383bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5384 if (!Visit(E->getSubExpr()))
5385 return false;
5386 // __real is a no-op on scalar lvalues.
5387 if (E->getSubExpr()->getType()->isAnyComplexType())
5388 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5389 return true;
5390}
5391
5392bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5393 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5394 "lvalue __imag__ on scalar?");
5395 if (!Visit(E->getSubExpr()))
5396 return false;
5397 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5398 return true;
5399}
5400
Richard Smith243ef902013-05-05 23:31:59 +00005401bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005402 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005403 return Error(UO);
5404
5405 if (!this->Visit(UO->getSubExpr()))
5406 return false;
5407
Richard Smith243ef902013-05-05 23:31:59 +00005408 return handleIncDec(
5409 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005410 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005411}
5412
5413bool LValueExprEvaluator::VisitCompoundAssignOperator(
5414 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005415 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005416 return Error(CAO);
5417
Richard Smith3229b742013-05-05 21:17:10 +00005418 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005419
5420 // The overall lvalue result is the result of evaluating the LHS.
5421 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005422 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005423 Evaluate(RHS, this->Info, CAO->getRHS());
5424 return false;
5425 }
5426
Richard Smith3229b742013-05-05 21:17:10 +00005427 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5428 return false;
5429
Richard Smith43e77732013-05-07 04:50:00 +00005430 return handleCompoundAssignment(
5431 this->Info, CAO,
5432 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5433 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005434}
5435
5436bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005437 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005438 return Error(E);
5439
Richard Smith3229b742013-05-05 21:17:10 +00005440 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005441
5442 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005443 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005444 Evaluate(NewVal, this->Info, E->getRHS());
5445 return false;
5446 }
5447
Richard Smith3229b742013-05-05 21:17:10 +00005448 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5449 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005450
5451 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005452 NewVal);
5453}
5454
Eli Friedman9a156e52008-11-12 09:44:48 +00005455//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005456// Pointer Evaluation
5457//===----------------------------------------------------------------------===//
5458
George Burgess IVe3763372016-12-22 02:50:20 +00005459/// \brief Attempts to compute the number of bytes available at the pointer
5460/// returned by a function with the alloc_size attribute. Returns true if we
5461/// were successful. Places an unsigned number into `Result`.
5462///
5463/// This expects the given CallExpr to be a call to a function with an
5464/// alloc_size attribute.
5465static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5466 const CallExpr *Call,
5467 llvm::APInt &Result) {
5468 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5469
Nico Weberbbf64822018-03-07 02:22:41 +00005470 // alloc_size args are 1-indexed, 0 means not present.
5471 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5472 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
George Burgess IVe3763372016-12-22 02:50:20 +00005473 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5474 if (Call->getNumArgs() <= SizeArgNo)
5475 return false;
5476
5477 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5478 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5479 return false;
5480 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5481 return false;
5482 Into = Into.zextOrSelf(BitsInSizeT);
5483 return true;
5484 };
5485
5486 APSInt SizeOfElem;
5487 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5488 return false;
5489
Nico Weberbbf64822018-03-07 02:22:41 +00005490 if (!AllocSize->getNumElemsParam()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005491 Result = std::move(SizeOfElem);
5492 return true;
5493 }
5494
5495 APSInt NumberOfElems;
Nico Weberbbf64822018-03-07 02:22:41 +00005496 // Argument numbers start at 1
5497 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
George Burgess IVe3763372016-12-22 02:50:20 +00005498 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5499 return false;
5500
5501 bool Overflow;
5502 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5503 if (Overflow)
5504 return false;
5505
5506 Result = std::move(BytesAvailable);
5507 return true;
5508}
5509
5510/// \brief Convenience function. LVal's base must be a call to an alloc_size
5511/// function.
5512static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5513 const LValue &LVal,
5514 llvm::APInt &Result) {
5515 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5516 "Can't get the size of a non alloc_size function");
5517 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5518 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5519 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5520}
5521
5522/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5523/// a function with the alloc_size attribute. If it was possible to do so, this
5524/// function will return true, make Result's Base point to said function call,
5525/// and mark Result's Base as invalid.
5526static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5527 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005528 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005529 return false;
5530
5531 // Because we do no form of static analysis, we only support const variables.
5532 //
5533 // Additionally, we can't support parameters, nor can we support static
5534 // variables (in the latter case, use-before-assign isn't UB; in the former,
5535 // we have no clue what they'll be assigned to).
5536 const auto *VD =
5537 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5538 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5539 return false;
5540
5541 const Expr *Init = VD->getAnyInitializer();
5542 if (!Init)
5543 return false;
5544
5545 const Expr *E = Init->IgnoreParens();
5546 if (!tryUnwrapAllocSizeCall(E))
5547 return false;
5548
5549 // Store E instead of E unwrapped so that the type of the LValue's base is
5550 // what the user wanted.
5551 Result.setInvalid(E);
5552
5553 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005554 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005555 return true;
5556}
5557
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005558namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005559class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005560 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005561 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005562 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005563
Peter Collingbournee9200682011-05-13 03:29:01 +00005564 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005565 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005566 return true;
5567 }
George Burgess IVe3763372016-12-22 02:50:20 +00005568
George Burgess IVf9013bf2017-02-10 22:52:29 +00005569 bool evaluateLValue(const Expr *E, LValue &Result) {
5570 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5571 }
5572
5573 bool evaluatePointer(const Expr *E, LValue &Result) {
5574 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5575 }
5576
George Burgess IVe3763372016-12-22 02:50:20 +00005577 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005578public:
Mike Stump11289f42009-09-09 15:08:12 +00005579
George Burgess IVf9013bf2017-02-10 22:52:29 +00005580 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5581 : ExprEvaluatorBaseTy(info), Result(Result),
5582 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005583
Richard Smith2e312c82012-03-03 22:46:17 +00005584 bool Success(const APValue &V, const Expr *E) {
5585 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005586 return true;
5587 }
Richard Smithfddd3842011-12-30 21:15:51 +00005588 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005589 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5590 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005591 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005592 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005593
John McCall45d55e42010-05-07 21:00:08 +00005594 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005595 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005596 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005597 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005598 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005599 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5600 if (Info.noteFailure())
5601 EvaluateIgnoredValue(Info, E->getSubExpr());
5602 return Error(E);
5603 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005604 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005605 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005606 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005607 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005608 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005609 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005610 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005611 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005612 }
Richard Smithd62306a2011-11-10 06:34:14 +00005613 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005614 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005615 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005616 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005617 if (!Info.CurrentCall->This) {
5618 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005619 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005620 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005621 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005622 return false;
5623 }
Richard Smithd62306a2011-11-10 06:34:14 +00005624 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005625 // If we are inside a lambda's call operator, the 'this' expression refers
5626 // to the enclosing '*this' object (either by value or reference) which is
5627 // either copied into the closure object's field that represents the '*this'
5628 // or refers to '*this'.
5629 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5630 // Update 'Result' to refer to the data member/field of the closure object
5631 // that represents the '*this' capture.
5632 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005633 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005634 return false;
5635 // If we captured '*this' by reference, replace the field with its referent.
5636 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5637 ->isPointerType()) {
5638 APValue RVal;
5639 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5640 RVal))
5641 return false;
5642
5643 Result.setFrom(Info.Ctx, RVal);
5644 }
5645 }
Richard Smithd62306a2011-11-10 06:34:14 +00005646 return true;
5647 }
John McCallc07a0c72011-02-17 10:25:35 +00005648
Eli Friedman449fe542009-03-23 04:56:01 +00005649 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005650};
Chris Lattner05706e882008-07-11 18:11:29 +00005651} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005652
George Burgess IVf9013bf2017-02-10 22:52:29 +00005653static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5654 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005655 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005656 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005657}
5658
John McCall45d55e42010-05-07 21:00:08 +00005659bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005660 if (E->getOpcode() != BO_Add &&
5661 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005662 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005663
Chris Lattner05706e882008-07-11 18:11:29 +00005664 const Expr *PExp = E->getLHS();
5665 const Expr *IExp = E->getRHS();
5666 if (IExp->getType()->isPointerType())
5667 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005668
George Burgess IVf9013bf2017-02-10 22:52:29 +00005669 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005670 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005671 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005672
John McCall45d55e42010-05-07 21:00:08 +00005673 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005674 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005675 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005676
Richard Smith96e0c102011-11-04 02:25:55 +00005677 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005678 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005679
Ted Kremenek28831752012-08-23 20:46:57 +00005680 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005681 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005682}
Eli Friedman9a156e52008-11-12 09:44:48 +00005683
John McCall45d55e42010-05-07 21:00:08 +00005684bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005685 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005686}
Mike Stump11289f42009-09-09 15:08:12 +00005687
Peter Collingbournee9200682011-05-13 03:29:01 +00005688bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5689 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005690
Eli Friedman847a2bc2009-12-27 05:43:15 +00005691 switch (E->getCastKind()) {
5692 default:
5693 break;
5694
John McCalle3027922010-08-25 11:45:40 +00005695 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005696 case CK_CPointerToObjCPointerCast:
5697 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005698 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005699 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005700 if (!Visit(SubExpr))
5701 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005702 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5703 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5704 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005705 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005706 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005707 if (SubExpr->getType()->isVoidPointerType())
5708 CCEDiag(E, diag::note_constexpr_invalid_cast)
5709 << 3 << SubExpr->getType();
5710 else
5711 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5712 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005713 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5714 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005715 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005716
Anders Carlsson18275092010-10-31 20:41:46 +00005717 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005718 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005719 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005720 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005721 if (!Result.Base && Result.Offset.isZero())
5722 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005723
Richard Smithd62306a2011-11-10 06:34:14 +00005724 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005725 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005726 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5727 castAs<PointerType>()->getPointeeType(),
5728 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005729
Richard Smith027bf112011-11-17 22:56:20 +00005730 case CK_BaseToDerived:
5731 if (!Visit(E->getSubExpr()))
5732 return false;
5733 if (!Result.Base && Result.Offset.isZero())
5734 return true;
5735 return HandleBaseToDerivedCast(Info, E, Result);
5736
Richard Smith0b0a0b62011-10-29 20:57:55 +00005737 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005738 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005739 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005740
John McCalle3027922010-08-25 11:45:40 +00005741 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005742 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5743
Richard Smith2e312c82012-03-03 22:46:17 +00005744 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005745 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005746 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005747
John McCall45d55e42010-05-07 21:00:08 +00005748 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005749 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5750 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005751 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005752 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005753 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005754 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005755 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005756 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005757 return true;
5758 } else {
5759 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005760 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005761 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005762 }
5763 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005764
5765 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005766 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005767 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005768 return false;
5769 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005770 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005771 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005772 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005773 return false;
5774 }
Richard Smith96e0c102011-11-04 02:25:55 +00005775 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005776 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5777 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005778 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005779 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005780 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005781 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005782 }
Richard Smithdd785442011-10-31 20:57:44 +00005783
John McCalle3027922010-08-25 11:45:40 +00005784 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005785 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005786
5787 case CK_LValueToRValue: {
5788 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005789 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005790 return false;
5791
5792 APValue RVal;
5793 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5794 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5795 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005796 return InvalidBaseOK &&
5797 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005798 return Success(RVal, E);
5799 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005800 }
5801
Richard Smith11562c52011-10-28 17:51:58 +00005802 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005803}
Chris Lattner05706e882008-07-11 18:11:29 +00005804
Hal Finkel0dd05d42014-10-03 17:18:37 +00005805static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5806 // C++ [expr.alignof]p3:
5807 // When alignof is applied to a reference type, the result is the
5808 // alignment of the referenced type.
5809 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5810 T = Ref->getPointeeType();
5811
5812 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005813 if (T.getQualifiers().hasUnaligned())
5814 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005815 return Info.Ctx.toCharUnitsFromBits(
5816 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5817}
5818
5819static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5820 E = E->IgnoreParens();
5821
5822 // The kinds of expressions that we have special-case logic here for
5823 // should be kept up to date with the special checks for those
5824 // expressions in Sema.
5825
5826 // alignof decl is always accepted, even if it doesn't make sense: we default
5827 // to 1 in those cases.
5828 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5829 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5830 /*RefAsPointee*/true);
5831
5832 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5833 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5834 /*RefAsPointee*/true);
5835
5836 return GetAlignOfType(Info, E->getType());
5837}
5838
George Burgess IVe3763372016-12-22 02:50:20 +00005839// To be clear: this happily visits unsupported builtins. Better name welcomed.
5840bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5841 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5842 return true;
5843
George Burgess IVf9013bf2017-02-10 22:52:29 +00005844 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005845 return false;
5846
5847 Result.setInvalid(E);
5848 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005849 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005850 return true;
5851}
5852
Peter Collingbournee9200682011-05-13 03:29:01 +00005853bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005854 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005855 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005856
Richard Smith6328cbd2016-11-16 00:57:23 +00005857 if (unsigned BuiltinOp = E->getBuiltinCallee())
5858 return VisitBuiltinCallExpr(E, BuiltinOp);
5859
George Burgess IVe3763372016-12-22 02:50:20 +00005860 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005861}
5862
5863bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5864 unsigned BuiltinOp) {
5865 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005866 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005867 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005868 case Builtin::BI__builtin_assume_aligned: {
5869 // We need to be very careful here because: if the pointer does not have the
5870 // asserted alignment, then the behavior is undefined, and undefined
5871 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005872 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005873 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005874
Hal Finkel0dd05d42014-10-03 17:18:37 +00005875 LValue OffsetResult(Result);
5876 APSInt Alignment;
5877 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5878 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005879 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005880
5881 if (E->getNumArgs() > 2) {
5882 APSInt Offset;
5883 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5884 return false;
5885
Richard Smith642a2362017-01-30 23:30:26 +00005886 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005887 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5888 }
5889
5890 // If there is a base object, then it must have the correct alignment.
5891 if (OffsetResult.Base) {
5892 CharUnits BaseAlignment;
5893 if (const ValueDecl *VD =
5894 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5895 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5896 } else {
5897 BaseAlignment =
5898 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5899 }
5900
5901 if (BaseAlignment < Align) {
5902 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005903 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005904 CCEDiag(E->getArg(0),
5905 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005906 << (unsigned)BaseAlignment.getQuantity()
5907 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005908 return false;
5909 }
5910 }
5911
5912 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005913 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005914 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005915
Richard Smith642a2362017-01-30 23:30:26 +00005916 (OffsetResult.Base
5917 ? CCEDiag(E->getArg(0),
5918 diag::note_constexpr_baa_insufficient_alignment) << 1
5919 : CCEDiag(E->getArg(0),
5920 diag::note_constexpr_baa_value_insufficient_alignment))
5921 << (int)OffsetResult.Offset.getQuantity()
5922 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005923 return false;
5924 }
5925
5926 return true;
5927 }
Richard Smithe9507952016-11-12 01:39:56 +00005928
5929 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005930 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005931 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005932 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005933 if (Info.getLangOpts().CPlusPlus11)
5934 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5935 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005936 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005937 else
5938 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005939 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00005940 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005941 case Builtin::BI__builtin_wcschr:
5942 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005943 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005944 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005945 if (!Visit(E->getArg(0)))
5946 return false;
5947 APSInt Desired;
5948 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5949 return false;
5950 uint64_t MaxLength = uint64_t(-1);
5951 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005952 BuiltinOp != Builtin::BIwcschr &&
5953 BuiltinOp != Builtin::BI__builtin_strchr &&
5954 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005955 APSInt N;
5956 if (!EvaluateInteger(E->getArg(2), N, Info))
5957 return false;
5958 MaxLength = N.getExtValue();
5959 }
5960
Richard Smith8110c9d2016-11-29 19:45:17 +00005961 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005962
Richard Smith8110c9d2016-11-29 19:45:17 +00005963 // Figure out what value we're actually looking for (after converting to
5964 // the corresponding unsigned type if necessary).
5965 uint64_t DesiredVal;
5966 bool StopAtNull = false;
5967 switch (BuiltinOp) {
5968 case Builtin::BIstrchr:
5969 case Builtin::BI__builtin_strchr:
5970 // strchr compares directly to the passed integer, and therefore
5971 // always fails if given an int that is not a char.
5972 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5973 E->getArg(1)->getType(),
5974 Desired),
5975 Desired))
5976 return ZeroInitialization(E);
5977 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005978 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00005979 case Builtin::BImemchr:
5980 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005981 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005982 // memchr compares by converting both sides to unsigned char. That's also
5983 // correct for strchr if we get this far (to cope with plain char being
5984 // unsigned in the strchr case).
5985 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5986 break;
Richard Smithe9507952016-11-12 01:39:56 +00005987
Richard Smith8110c9d2016-11-29 19:45:17 +00005988 case Builtin::BIwcschr:
5989 case Builtin::BI__builtin_wcschr:
5990 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005991 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00005992 case Builtin::BIwmemchr:
5993 case Builtin::BI__builtin_wmemchr:
5994 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5995 DesiredVal = Desired.getZExtValue();
5996 break;
5997 }
Richard Smithe9507952016-11-12 01:39:56 +00005998
5999 for (; MaxLength; --MaxLength) {
6000 APValue Char;
6001 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6002 !Char.isInt())
6003 return false;
6004 if (Char.getInt().getZExtValue() == DesiredVal)
6005 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006006 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006007 break;
6008 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6009 return false;
6010 }
6011 // Not found: return nullptr.
6012 return ZeroInitialization(E);
6013 }
6014
Richard Smith6cbd65d2013-07-11 02:27:57 +00006015 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006016 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006017 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006018}
Chris Lattner05706e882008-07-11 18:11:29 +00006019
6020//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006021// Member Pointer Evaluation
6022//===----------------------------------------------------------------------===//
6023
6024namespace {
6025class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006026 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006027 MemberPtr &Result;
6028
6029 bool Success(const ValueDecl *D) {
6030 Result = MemberPtr(D);
6031 return true;
6032 }
6033public:
6034
6035 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6036 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6037
Richard Smith2e312c82012-03-03 22:46:17 +00006038 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006039 Result.setFrom(V);
6040 return true;
6041 }
Richard Smithfddd3842011-12-30 21:15:51 +00006042 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006043 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006044 }
6045
6046 bool VisitCastExpr(const CastExpr *E);
6047 bool VisitUnaryAddrOf(const UnaryOperator *E);
6048};
6049} // end anonymous namespace
6050
6051static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6052 EvalInfo &Info) {
6053 assert(E->isRValue() && E->getType()->isMemberPointerType());
6054 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6055}
6056
6057bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6058 switch (E->getCastKind()) {
6059 default:
6060 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6061
6062 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006063 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006064 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006065
6066 case CK_BaseToDerivedMemberPointer: {
6067 if (!Visit(E->getSubExpr()))
6068 return false;
6069 if (E->path_empty())
6070 return true;
6071 // Base-to-derived member pointer casts store the path in derived-to-base
6072 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6073 // the wrong end of the derived->base arc, so stagger the path by one class.
6074 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6075 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6076 PathI != PathE; ++PathI) {
6077 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6078 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6079 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006080 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006081 }
6082 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6083 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006084 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006085 return true;
6086 }
6087
6088 case CK_DerivedToBaseMemberPointer:
6089 if (!Visit(E->getSubExpr()))
6090 return false;
6091 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6092 PathE = E->path_end(); PathI != PathE; ++PathI) {
6093 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6094 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6095 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006096 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006097 }
6098 return true;
6099 }
6100}
6101
6102bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6103 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6104 // member can be formed.
6105 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6106}
6107
6108//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006109// Record Evaluation
6110//===----------------------------------------------------------------------===//
6111
6112namespace {
6113 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006114 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006115 const LValue &This;
6116 APValue &Result;
6117 public:
6118
6119 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6120 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6121
Richard Smith2e312c82012-03-03 22:46:17 +00006122 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006123 Result = V;
6124 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006125 }
Richard Smithb8348f52016-05-12 22:16:28 +00006126 bool ZeroInitialization(const Expr *E) {
6127 return ZeroInitialization(E, E->getType());
6128 }
6129 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006130
Richard Smith52a980a2015-08-28 02:43:42 +00006131 bool VisitCallExpr(const CallExpr *E) {
6132 return handleCallExpr(E, Result, &This);
6133 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006134 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006135 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006136 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6137 return VisitCXXConstructExpr(E, E->getType());
6138 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006139 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006140 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006141 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006142 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006143 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006144}
Richard Smithd62306a2011-11-10 06:34:14 +00006145
Richard Smithfddd3842011-12-30 21:15:51 +00006146/// Perform zero-initialization on an object of non-union class type.
6147/// C++11 [dcl.init]p5:
6148/// To zero-initialize an object or reference of type T means:
6149/// [...]
6150/// -- if T is a (possibly cv-qualified) non-union class type,
6151/// each non-static data member and each base-class subobject is
6152/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006153static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6154 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006155 const LValue &This, APValue &Result) {
6156 assert(!RD->isUnion() && "Expected non-union class type");
6157 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6158 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006159 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006160
John McCalld7bca762012-05-01 00:38:49 +00006161 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006162 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6163
6164 if (CD) {
6165 unsigned Index = 0;
6166 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006167 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006168 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6169 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006170 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6171 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006172 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006173 Result.getStructBase(Index)))
6174 return false;
6175 }
6176 }
6177
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006178 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006179 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006180 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006181 continue;
6182
6183 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006184 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006185 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006186
David Blaikie2d7c57e2012-04-30 02:36:29 +00006187 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006188 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006189 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006190 return false;
6191 }
6192
6193 return true;
6194}
6195
Richard Smithb8348f52016-05-12 22:16:28 +00006196bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6197 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006198 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006199 if (RD->isUnion()) {
6200 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6201 // object's first non-static named data member is zero-initialized
6202 RecordDecl::field_iterator I = RD->field_begin();
6203 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006204 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006205 return true;
6206 }
6207
6208 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006209 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006210 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006211 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006212 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006213 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006214 }
6215
Richard Smith5d108602012-02-17 00:44:16 +00006216 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006217 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006218 return false;
6219 }
6220
Richard Smitha8105bc2012-01-06 16:39:00 +00006221 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006222}
6223
Richard Smithe97cbd72011-11-11 04:05:33 +00006224bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6225 switch (E->getCastKind()) {
6226 default:
6227 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6228
6229 case CK_ConstructorConversion:
6230 return Visit(E->getSubExpr());
6231
6232 case CK_DerivedToBase:
6233 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006234 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006235 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006236 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006237 if (!DerivedObject.isStruct())
6238 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006239
6240 // Derived-to-base rvalue conversion: just slice off the derived part.
6241 APValue *Value = &DerivedObject;
6242 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6243 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6244 PathE = E->path_end(); PathI != PathE; ++PathI) {
6245 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6246 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6247 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6248 RD = Base;
6249 }
6250 Result = *Value;
6251 return true;
6252 }
6253 }
6254}
6255
Richard Smithd62306a2011-11-10 06:34:14 +00006256bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006257 if (E->isTransparent())
6258 return Visit(E->getInit(0));
6259
Richard Smithd62306a2011-11-10 06:34:14 +00006260 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006261 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006262 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6263
6264 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006265 const FieldDecl *Field = E->getInitializedFieldInUnion();
6266 Result = APValue(Field);
6267 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006268 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006269
6270 // If the initializer list for a union does not contain any elements, the
6271 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006272 // FIXME: The element should be initialized from an initializer list.
6273 // Is this difference ever observable for initializer lists which
6274 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006275 ImplicitValueInitExpr VIE(Field->getType());
6276 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6277
Richard Smithd62306a2011-11-10 06:34:14 +00006278 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006279 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6280 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006281
6282 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6283 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6284 isa<CXXDefaultInitExpr>(InitExpr));
6285
Richard Smithb228a862012-02-15 02:18:13 +00006286 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006287 }
6288
Richard Smith872307e2016-03-08 22:17:41 +00006289 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006290 if (Result.isUninit())
6291 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6292 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006293 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006294 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006295
6296 // Initialize base classes.
6297 if (CXXRD) {
6298 for (const auto &Base : CXXRD->bases()) {
6299 assert(ElementNo < E->getNumInits() && "missing init for base class");
6300 const Expr *Init = E->getInit(ElementNo);
6301
6302 LValue Subobject = This;
6303 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6304 return false;
6305
6306 APValue &FieldVal = Result.getStructBase(ElementNo);
6307 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006308 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006309 return false;
6310 Success = false;
6311 }
6312 ++ElementNo;
6313 }
6314 }
6315
6316 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006317 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006318 // Anonymous bit-fields are not considered members of the class for
6319 // purposes of aggregate initialization.
6320 if (Field->isUnnamedBitfield())
6321 continue;
6322
6323 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006324
Richard Smith253c2a32012-01-27 01:14:48 +00006325 bool HaveInit = ElementNo < E->getNumInits();
6326
6327 // FIXME: Diagnostics here should point to the end of the initializer
6328 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006329 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006330 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006331 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006332
6333 // Perform an implicit value-initialization for members beyond the end of
6334 // the initializer list.
6335 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006336 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006337
Richard Smith852c9db2013-04-20 22:23:05 +00006338 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6339 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6340 isa<CXXDefaultInitExpr>(Init));
6341
Richard Smith49ca8aa2013-08-06 07:09:20 +00006342 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6343 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6344 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006345 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006346 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006347 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006348 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006349 }
6350 }
6351
Richard Smith253c2a32012-01-27 01:14:48 +00006352 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006353}
6354
Richard Smithb8348f52016-05-12 22:16:28 +00006355bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6356 QualType T) {
6357 // Note that E's type is not necessarily the type of our class here; we might
6358 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006359 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006360 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6361
Richard Smithfddd3842011-12-30 21:15:51 +00006362 bool ZeroInit = E->requiresZeroInitialization();
6363 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006364 // If we've already performed zero-initialization, we're already done.
6365 if (!Result.isUninit())
6366 return true;
6367
Richard Smithda3f4fd2014-03-05 23:32:50 +00006368 // We can get here in two different ways:
6369 // 1) We're performing value-initialization, and should zero-initialize
6370 // the object, or
6371 // 2) We're performing default-initialization of an object with a trivial
6372 // constexpr default constructor, in which case we should start the
6373 // lifetimes of all the base subobjects (there can be no data member
6374 // subobjects in this case) per [basic.life]p1.
6375 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006376 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006377 }
6378
Craig Topper36250ad2014-05-12 05:36:57 +00006379 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006380 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006381
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006382 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006383 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006384
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006385 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006386 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006387 if (const MaterializeTemporaryExpr *ME
6388 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6389 return Visit(ME->GetTemporaryExpr());
6390
Richard Smithb8348f52016-05-12 22:16:28 +00006391 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006392 return false;
6393
Craig Topper5fc8fc22014-08-27 06:28:36 +00006394 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006395 return HandleConstructorCall(E, This, Args,
6396 cast<CXXConstructorDecl>(Definition), Info,
6397 Result);
6398}
6399
6400bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6401 const CXXInheritedCtorInitExpr *E) {
6402 if (!Info.CurrentCall) {
6403 assert(Info.checkingPotentialConstantExpression());
6404 return false;
6405 }
6406
6407 const CXXConstructorDecl *FD = E->getConstructor();
6408 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6409 return false;
6410
6411 const FunctionDecl *Definition = nullptr;
6412 auto Body = FD->getBody(Definition);
6413
6414 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6415 return false;
6416
6417 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006418 cast<CXXConstructorDecl>(Definition), Info,
6419 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006420}
6421
Richard Smithcc1b96d2013-06-12 22:31:48 +00006422bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6423 const CXXStdInitializerListExpr *E) {
6424 const ConstantArrayType *ArrayType =
6425 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6426
6427 LValue Array;
6428 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6429 return false;
6430
6431 // Get a pointer to the first element of the array.
6432 Array.addArray(Info, E, ArrayType);
6433
6434 // FIXME: Perform the checks on the field types in SemaInit.
6435 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6436 RecordDecl::field_iterator Field = Record->field_begin();
6437 if (Field == Record->field_end())
6438 return Error(E);
6439
6440 // Start pointer.
6441 if (!Field->getType()->isPointerType() ||
6442 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6443 ArrayType->getElementType()))
6444 return Error(E);
6445
6446 // FIXME: What if the initializer_list type has base classes, etc?
6447 Result = APValue(APValue::UninitStruct(), 0, 2);
6448 Array.moveInto(Result.getStructField(0));
6449
6450 if (++Field == Record->field_end())
6451 return Error(E);
6452
6453 if (Field->getType()->isPointerType() &&
6454 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6455 ArrayType->getElementType())) {
6456 // End pointer.
6457 if (!HandleLValueArrayAdjustment(Info, E, Array,
6458 ArrayType->getElementType(),
6459 ArrayType->getSize().getZExtValue()))
6460 return false;
6461 Array.moveInto(Result.getStructField(1));
6462 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6463 // Length.
6464 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6465 else
6466 return Error(E);
6467
6468 if (++Field != Record->field_end())
6469 return Error(E);
6470
6471 return true;
6472}
6473
Faisal Valic72a08c2017-01-09 03:02:53 +00006474bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6475 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6476 if (ClosureClass->isInvalidDecl()) return false;
6477
6478 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006479
Faisal Vali051e3a22017-02-16 04:12:21 +00006480 const size_t NumFields =
6481 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006482
6483 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6484 E->capture_init_end()) &&
6485 "The number of lambda capture initializers should equal the number of "
6486 "fields within the closure type");
6487
Faisal Vali051e3a22017-02-16 04:12:21 +00006488 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6489 // Iterate through all the lambda's closure object's fields and initialize
6490 // them.
6491 auto *CaptureInitIt = E->capture_init_begin();
6492 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6493 bool Success = true;
6494 for (const auto *Field : ClosureClass->fields()) {
6495 assert(CaptureInitIt != E->capture_init_end());
6496 // Get the initializer for this field
6497 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006498
Faisal Vali051e3a22017-02-16 04:12:21 +00006499 // If there is no initializer, either this is a VLA or an error has
6500 // occurred.
6501 if (!CurFieldInit)
6502 return Error(E);
6503
6504 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6505 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6506 if (!Info.keepEvaluatingAfterFailure())
6507 return false;
6508 Success = false;
6509 }
6510 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006511 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006512 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006513}
6514
Richard Smithd62306a2011-11-10 06:34:14 +00006515static bool EvaluateRecord(const Expr *E, const LValue &This,
6516 APValue &Result, EvalInfo &Info) {
6517 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006518 "can't evaluate expression as a record rvalue");
6519 return RecordExprEvaluator(Info, This, Result).Visit(E);
6520}
6521
6522//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006523// Temporary Evaluation
6524//
6525// Temporaries are represented in the AST as rvalues, but generally behave like
6526// lvalues. The full-object of which the temporary is a subobject is implicitly
6527// materialized so that a reference can bind to it.
6528//===----------------------------------------------------------------------===//
6529namespace {
6530class TemporaryExprEvaluator
6531 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6532public:
6533 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006534 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006535
6536 /// Visit an expression which constructs the value of this temporary.
6537 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006538 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006539 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6540 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006541 }
6542
6543 bool VisitCastExpr(const CastExpr *E) {
6544 switch (E->getCastKind()) {
6545 default:
6546 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6547
6548 case CK_ConstructorConversion:
6549 return VisitConstructExpr(E->getSubExpr());
6550 }
6551 }
6552 bool VisitInitListExpr(const InitListExpr *E) {
6553 return VisitConstructExpr(E);
6554 }
6555 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6556 return VisitConstructExpr(E);
6557 }
6558 bool VisitCallExpr(const CallExpr *E) {
6559 return VisitConstructExpr(E);
6560 }
Richard Smith513955c2014-12-17 19:24:30 +00006561 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6562 return VisitConstructExpr(E);
6563 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006564 bool VisitLambdaExpr(const LambdaExpr *E) {
6565 return VisitConstructExpr(E);
6566 }
Richard Smith027bf112011-11-17 22:56:20 +00006567};
6568} // end anonymous namespace
6569
6570/// Evaluate an expression of record type as a temporary.
6571static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006572 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006573 return TemporaryExprEvaluator(Info, Result).Visit(E);
6574}
6575
6576//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006577// Vector Evaluation
6578//===----------------------------------------------------------------------===//
6579
6580namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006581 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006582 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006583 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006584 public:
Mike Stump11289f42009-09-09 15:08:12 +00006585
Richard Smith2d406342011-10-22 21:10:00 +00006586 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6587 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006588
Craig Topper9798b932015-09-29 04:30:05 +00006589 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006590 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6591 // FIXME: remove this APValue copy.
6592 Result = APValue(V.data(), V.size());
6593 return true;
6594 }
Richard Smith2e312c82012-03-03 22:46:17 +00006595 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006596 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006597 Result = V;
6598 return true;
6599 }
Richard Smithfddd3842011-12-30 21:15:51 +00006600 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006601
Richard Smith2d406342011-10-22 21:10:00 +00006602 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006603 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006604 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006605 bool VisitInitListExpr(const InitListExpr *E);
6606 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006607 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006608 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006609 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006610 };
6611} // end anonymous namespace
6612
6613static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006614 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006615 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006616}
6617
George Burgess IV533ff002015-12-11 00:23:35 +00006618bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006619 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006620 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006621
Richard Smith161f09a2011-12-06 22:44:34 +00006622 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006623 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006624
Eli Friedmanc757de22011-03-25 00:43:55 +00006625 switch (E->getCastKind()) {
6626 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006627 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006628 if (SETy->isIntegerType()) {
6629 APSInt IntResult;
6630 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006631 return false;
6632 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006633 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006634 APFloat FloatResult(0.0);
6635 if (!EvaluateFloat(SE, FloatResult, Info))
6636 return false;
6637 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006638 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006639 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006640 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006641
6642 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006643 SmallVector<APValue, 4> Elts(NElts, Val);
6644 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006645 }
Eli Friedman803acb32011-12-22 03:51:45 +00006646 case CK_BitCast: {
6647 // Evaluate the operand into an APInt we can extract from.
6648 llvm::APInt SValInt;
6649 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6650 return false;
6651 // Extract the elements
6652 QualType EltTy = VTy->getElementType();
6653 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6654 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6655 SmallVector<APValue, 4> Elts;
6656 if (EltTy->isRealFloatingType()) {
6657 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006658 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006659 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006660 FloatEltSize = 80;
6661 for (unsigned i = 0; i < NElts; i++) {
6662 llvm::APInt Elt;
6663 if (BigEndian)
6664 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6665 else
6666 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006667 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006668 }
6669 } else if (EltTy->isIntegerType()) {
6670 for (unsigned i = 0; i < NElts; i++) {
6671 llvm::APInt Elt;
6672 if (BigEndian)
6673 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6674 else
6675 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6676 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6677 }
6678 } else {
6679 return Error(E);
6680 }
6681 return Success(Elts, E);
6682 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006683 default:
Richard Smith11562c52011-10-28 17:51:58 +00006684 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006685 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006686}
6687
Richard Smith2d406342011-10-22 21:10:00 +00006688bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006689VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006690 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006691 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006692 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006693
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006694 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006695 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006696
Eli Friedmanb9c71292012-01-03 23:24:20 +00006697 // The number of initializers can be less than the number of
6698 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006699 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006700 // should be initialized with zeroes.
6701 unsigned CountInits = 0, CountElts = 0;
6702 while (CountElts < NumElements) {
6703 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006704 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006705 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006706 APValue v;
6707 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6708 return Error(E);
6709 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006710 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006711 Elements.push_back(v.getVectorElt(j));
6712 CountElts += vlen;
6713 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006714 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006715 if (CountInits < NumInits) {
6716 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006717 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006718 } else // trailing integer zero.
6719 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6720 Elements.push_back(APValue(sInt));
6721 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006722 } else {
6723 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006724 if (CountInits < NumInits) {
6725 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006726 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006727 } else // trailing float zero.
6728 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6729 Elements.push_back(APValue(f));
6730 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006731 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006732 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006733 }
Richard Smith2d406342011-10-22 21:10:00 +00006734 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006735}
6736
Richard Smith2d406342011-10-22 21:10:00 +00006737bool
Richard Smithfddd3842011-12-30 21:15:51 +00006738VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006739 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006740 QualType EltTy = VT->getElementType();
6741 APValue ZeroElement;
6742 if (EltTy->isIntegerType())
6743 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6744 else
6745 ZeroElement =
6746 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6747
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006748 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006749 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006750}
6751
Richard Smith2d406342011-10-22 21:10:00 +00006752bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006753 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006754 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006755}
6756
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006757//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006758// Array Evaluation
6759//===----------------------------------------------------------------------===//
6760
6761namespace {
6762 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006763 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006764 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006765 APValue &Result;
6766 public:
6767
Richard Smithd62306a2011-11-10 06:34:14 +00006768 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6769 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006770
6771 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006772 assert((V.isArray() || V.isLValue()) &&
6773 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006774 Result = V;
6775 return true;
6776 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006777
Richard Smithfddd3842011-12-30 21:15:51 +00006778 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006779 const ConstantArrayType *CAT =
6780 Info.Ctx.getAsConstantArrayType(E->getType());
6781 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006782 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006783
6784 Result = APValue(APValue::UninitArray(), 0,
6785 CAT->getSize().getZExtValue());
6786 if (!Result.hasArrayFiller()) return true;
6787
Richard Smithfddd3842011-12-30 21:15:51 +00006788 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006789 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006790 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006791 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006792 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006793 }
6794
Richard Smith52a980a2015-08-28 02:43:42 +00006795 bool VisitCallExpr(const CallExpr *E) {
6796 return handleCallExpr(E, Result, &This);
6797 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006798 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006799 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006800 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006801 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6802 const LValue &Subobject,
6803 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006804 };
6805} // end anonymous namespace
6806
Richard Smithd62306a2011-11-10 06:34:14 +00006807static bool EvaluateArray(const Expr *E, const LValue &This,
6808 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006809 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006810 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006811}
6812
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006813// Return true iff the given array filler may depend on the element index.
6814static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
6815 // For now, just whitelist non-class value-initialization and initialization
6816 // lists comprised of them.
6817 if (isa<ImplicitValueInitExpr>(FillerExpr))
6818 return false;
6819 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
6820 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
6821 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
6822 return true;
6823 }
6824 return false;
6825 }
6826 return true;
6827}
6828
Richard Smithf3e9e432011-11-07 09:22:26 +00006829bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6830 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6831 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006832 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006833
Richard Smithca2cfbf2011-12-22 01:07:19 +00006834 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6835 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006836 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006837 LValue LV;
6838 if (!EvaluateLValue(E->getInit(0), LV, Info))
6839 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006840 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006841 LV.moveInto(Val);
6842 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006843 }
6844
Richard Smith253c2a32012-01-27 01:14:48 +00006845 bool Success = true;
6846
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006847 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6848 "zero-initialized array shouldn't have any initialized elts");
6849 APValue Filler;
6850 if (Result.isArray() && Result.hasArrayFiller())
6851 Filler = Result.getArrayFiller();
6852
Richard Smith9543c5e2013-04-22 14:44:29 +00006853 unsigned NumEltsToInit = E->getNumInits();
6854 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006855 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006856
6857 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006858 // array element.
6859 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00006860 NumEltsToInit = NumElts;
6861
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006862 DEBUG(llvm::dbgs() << "The number of elements to initialize: " <<
6863 NumEltsToInit << ".\n");
6864
Richard Smith9543c5e2013-04-22 14:44:29 +00006865 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006866
6867 // If the array was previously zero-initialized, preserve the
6868 // zero-initialized values.
6869 if (!Filler.isUninit()) {
6870 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6871 Result.getArrayInitializedElt(I) = Filler;
6872 if (Result.hasArrayFiller())
6873 Result.getArrayFiller() = Filler;
6874 }
6875
Richard Smithd62306a2011-11-10 06:34:14 +00006876 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006877 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006878 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6879 const Expr *Init =
6880 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006881 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006882 Info, Subobject, Init) ||
6883 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006884 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006885 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006886 return false;
6887 Success = false;
6888 }
Richard Smithd62306a2011-11-10 06:34:14 +00006889 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006890
Richard Smith9543c5e2013-04-22 14:44:29 +00006891 if (!Result.hasArrayFiller())
6892 return Success;
6893
6894 // If we get here, we have a trivial filler, which we can just evaluate
6895 // once and splat over the rest of the array elements.
6896 assert(FillerExpr && "no array filler for incomplete init list");
6897 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6898 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006899}
6900
Richard Smith410306b2016-12-12 02:53:20 +00006901bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6902 if (E->getCommonExpr() &&
6903 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6904 Info, E->getCommonExpr()->getSourceExpr()))
6905 return false;
6906
6907 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6908
6909 uint64_t Elements = CAT->getSize().getZExtValue();
6910 Result = APValue(APValue::UninitArray(), Elements, Elements);
6911
6912 LValue Subobject = This;
6913 Subobject.addArray(Info, E, CAT);
6914
6915 bool Success = true;
6916 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6917 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6918 Info, Subobject, E->getSubExpr()) ||
6919 !HandleLValueArrayAdjustment(Info, E, Subobject,
6920 CAT->getElementType(), 1)) {
6921 if (!Info.noteFailure())
6922 return false;
6923 Success = false;
6924 }
6925 }
6926
6927 return Success;
6928}
6929
Richard Smith027bf112011-11-17 22:56:20 +00006930bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006931 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6932}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006933
Richard Smith9543c5e2013-04-22 14:44:29 +00006934bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6935 const LValue &Subobject,
6936 APValue *Value,
6937 QualType Type) {
6938 bool HadZeroInit = !Value->isUninit();
6939
6940 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6941 unsigned N = CAT->getSize().getZExtValue();
6942
6943 // Preserve the array filler if we had prior zero-initialization.
6944 APValue Filler =
6945 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6946 : APValue();
6947
6948 *Value = APValue(APValue::UninitArray(), N, N);
6949
6950 if (HadZeroInit)
6951 for (unsigned I = 0; I != N; ++I)
6952 Value->getArrayInitializedElt(I) = Filler;
6953
6954 // Initialize the elements.
6955 LValue ArrayElt = Subobject;
6956 ArrayElt.addArray(Info, E, CAT);
6957 for (unsigned I = 0; I != N; ++I)
6958 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6959 CAT->getElementType()) ||
6960 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6961 CAT->getElementType(), 1))
6962 return false;
6963
6964 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006965 }
Richard Smith027bf112011-11-17 22:56:20 +00006966
Richard Smith9543c5e2013-04-22 14:44:29 +00006967 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006968 return Error(E);
6969
Richard Smithb8348f52016-05-12 22:16:28 +00006970 return RecordExprEvaluator(Info, Subobject, *Value)
6971 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006972}
6973
Richard Smithf3e9e432011-11-07 09:22:26 +00006974//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006975// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006976//
6977// As a GNU extension, we support casting pointers to sufficiently-wide integer
6978// types and back in constant folding. Integer values are thus represented
6979// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006980//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006981
6982namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006983class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006984 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006985 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006986public:
Richard Smith2e312c82012-03-03 22:46:17 +00006987 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006988 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006989
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006990 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006991 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006992 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006993 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006994 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006995 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006996 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006997 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006998 return true;
6999 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007000 bool Success(const llvm::APSInt &SI, const Expr *E) {
7001 return Success(SI, E, Result);
7002 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007003
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007004 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00007005 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007006 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007007 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007008 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007009 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007010 Result.getInt().setIsUnsigned(
7011 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007012 return true;
7013 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007014 bool Success(const llvm::APInt &I, const Expr *E) {
7015 return Success(I, E, Result);
7016 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007017
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007018 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00007019 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007020 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007021 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007022 return true;
7023 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007024 bool Success(uint64_t Value, const Expr *E) {
7025 return Success(Value, E, Result);
7026 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007027
Ken Dyckdbc01912011-03-11 02:13:43 +00007028 bool Success(CharUnits Size, const Expr *E) {
7029 return Success(Size.getQuantity(), E);
7030 }
7031
Richard Smith2e312c82012-03-03 22:46:17 +00007032 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007033 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007034 Result = V;
7035 return true;
7036 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007037 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007038 }
Mike Stump11289f42009-09-09 15:08:12 +00007039
Richard Smithfddd3842011-12-30 21:15:51 +00007040 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007041
Peter Collingbournee9200682011-05-13 03:29:01 +00007042 //===--------------------------------------------------------------------===//
7043 // Visitor Methods
7044 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007045
Chris Lattner7174bf32008-07-12 00:38:25 +00007046 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007047 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007048 }
7049 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007050 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007051 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007052
7053 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7054 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007055 if (CheckReferencedDecl(E, E->getDecl()))
7056 return true;
7057
7058 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007059 }
7060 bool VisitMemberExpr(const MemberExpr *E) {
7061 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007062 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007063 return true;
7064 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007065
7066 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007067 }
7068
Peter Collingbournee9200682011-05-13 03:29:01 +00007069 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007070 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007071 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007072 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007073 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007074
Peter Collingbournee9200682011-05-13 03:29:01 +00007075 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007076 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007077
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007078 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007079 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007080 }
Mike Stump11289f42009-09-09 15:08:12 +00007081
Ted Kremeneke65b0862012-03-06 20:05:56 +00007082 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7083 return Success(E->getValue(), E);
7084 }
Richard Smith410306b2016-12-12 02:53:20 +00007085
7086 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7087 if (Info.ArrayInitIndex == uint64_t(-1)) {
7088 // We were asked to evaluate this subexpression independent of the
7089 // enclosing ArrayInitLoopExpr. We can't do that.
7090 Info.FFDiag(E);
7091 return false;
7092 }
7093 return Success(Info.ArrayInitIndex, E);
7094 }
Daniel Jasperffdee092017-05-02 19:21:42 +00007095
Richard Smith4ce706a2011-10-11 21:43:33 +00007096 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007097 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007098 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007099 }
7100
Douglas Gregor29c42f22012-02-24 07:38:34 +00007101 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7102 return Success(E->getValue(), E);
7103 }
7104
John Wiegley6242b6a2011-04-28 00:16:57 +00007105 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7106 return Success(E->getValue(), E);
7107 }
7108
John Wiegleyf9f65842011-04-25 06:54:41 +00007109 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7110 return Success(E->getValue(), E);
7111 }
7112
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007113 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007114 bool VisitUnaryImag(const UnaryOperator *E);
7115
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007116 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007117 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007118
Eli Friedman4e7a2412009-02-27 04:45:43 +00007119 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007120};
Chris Lattner05706e882008-07-11 18:11:29 +00007121} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007122
Richard Smith11562c52011-10-28 17:51:58 +00007123/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7124/// produce either the integer value or a pointer.
7125///
7126/// GCC has a heinous extension which folds casts between pointer types and
7127/// pointer-sized integral types. We support this by allowing the evaluation of
7128/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7129/// Some simple arithmetic on such values is supported (they are treated much
7130/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007131static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007132 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007133 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007134 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007135}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007136
Richard Smithf57d8cb2011-12-09 22:58:01 +00007137static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007138 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007139 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007140 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007141 if (!Val.isInt()) {
7142 // FIXME: It would be better to produce the diagnostic for casting
7143 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007144 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007145 return false;
7146 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007147 Result = Val.getInt();
7148 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007149}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007150
Richard Smithf57d8cb2011-12-09 22:58:01 +00007151/// Check whether the given declaration can be directly converted to an integral
7152/// rvalue. If not, no diagnostic is produced; there are other things we can
7153/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007154bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007155 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007156 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007157 // Check for signedness/width mismatches between E type and ECD value.
7158 bool SameSign = (ECD->getInitVal().isSigned()
7159 == E->getType()->isSignedIntegerOrEnumerationType());
7160 bool SameWidth = (ECD->getInitVal().getBitWidth()
7161 == Info.Ctx.getIntWidth(E->getType()));
7162 if (SameSign && SameWidth)
7163 return Success(ECD->getInitVal(), E);
7164 else {
7165 // Get rid of mismatch (otherwise Success assertions will fail)
7166 // by computing a new value matching the type of E.
7167 llvm::APSInt Val = ECD->getInitVal();
7168 if (!SameSign)
7169 Val.setIsSigned(!ECD->getInitVal().isSigned());
7170 if (!SameWidth)
7171 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7172 return Success(Val, E);
7173 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007174 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007175 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007176}
7177
Chris Lattner86ee2862008-10-06 06:40:35 +00007178/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7179/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007180static int EvaluateBuiltinClassifyType(const CallExpr *E,
7181 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007182 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007183 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007184 enum gcc_type_class {
7185 no_type_class = -1,
7186 void_type_class, integer_type_class, char_type_class,
7187 enumeral_type_class, boolean_type_class,
7188 pointer_type_class, reference_type_class, offset_type_class,
7189 real_type_class, complex_type_class,
7190 function_type_class, method_type_class,
7191 record_type_class, union_type_class,
7192 array_type_class, string_type_class,
7193 lang_type_class
7194 };
Mike Stump11289f42009-09-09 15:08:12 +00007195
7196 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007197 // ideal, however it is what gcc does.
7198 if (E->getNumArgs() == 0)
7199 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007200
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007201 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7202 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7203
7204 switch (CanTy->getTypeClass()) {
7205#define TYPE(ID, BASE)
7206#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7207#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7208#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7209#include "clang/AST/TypeNodes.def"
7210 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7211
7212 case Type::Builtin:
7213 switch (BT->getKind()) {
7214#define BUILTIN_TYPE(ID, SINGLETON_ID)
7215#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7216#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7217#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7218#include "clang/AST/BuiltinTypes.def"
7219 case BuiltinType::Void:
7220 return void_type_class;
7221
7222 case BuiltinType::Bool:
7223 return boolean_type_class;
7224
7225 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7226 case BuiltinType::UChar:
7227 case BuiltinType::UShort:
7228 case BuiltinType::UInt:
7229 case BuiltinType::ULong:
7230 case BuiltinType::ULongLong:
7231 case BuiltinType::UInt128:
7232 return integer_type_class;
7233
7234 case BuiltinType::NullPtr:
7235 return pointer_type_class;
7236
7237 case BuiltinType::WChar_U:
7238 case BuiltinType::Char16:
7239 case BuiltinType::Char32:
7240 case BuiltinType::ObjCId:
7241 case BuiltinType::ObjCClass:
7242 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007243#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7244 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007245#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007246 case BuiltinType::OCLSampler:
7247 case BuiltinType::OCLEvent:
7248 case BuiltinType::OCLClkEvent:
7249 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007250 case BuiltinType::OCLReserveID:
7251 case BuiltinType::Dependent:
7252 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7253 };
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007254 break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007255
7256 case Type::Enum:
7257 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7258 break;
7259
7260 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007261 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007262 break;
7263
7264 case Type::MemberPointer:
7265 if (CanTy->isMemberDataPointerType())
7266 return offset_type_class;
7267 else {
7268 // We expect member pointers to be either data or function pointers,
7269 // nothing else.
7270 assert(CanTy->isMemberFunctionPointerType());
7271 return method_type_class;
7272 }
7273
7274 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007275 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007276
7277 case Type::FunctionNoProto:
7278 case Type::FunctionProto:
7279 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7280
7281 case Type::Record:
7282 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7283 switch (RT->getDecl()->getTagKind()) {
7284 case TagTypeKind::TTK_Struct:
7285 case TagTypeKind::TTK_Class:
7286 case TagTypeKind::TTK_Interface:
7287 return record_type_class;
7288
7289 case TagTypeKind::TTK_Enum:
7290 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7291
7292 case TagTypeKind::TTK_Union:
7293 return union_type_class;
7294 }
7295 }
David Blaikie83d382b2011-09-23 05:06:16 +00007296 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007297
7298 case Type::ConstantArray:
7299 case Type::VariableArray:
7300 case Type::IncompleteArray:
7301 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7302
7303 case Type::BlockPointer:
7304 case Type::LValueReference:
7305 case Type::RValueReference:
7306 case Type::Vector:
7307 case Type::ExtVector:
7308 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007309 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007310 case Type::ObjCObject:
7311 case Type::ObjCInterface:
7312 case Type::ObjCObjectPointer:
7313 case Type::Pipe:
7314 case Type::Atomic:
7315 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7316 }
7317
7318 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007319}
7320
Richard Smith5fab0c92011-12-28 19:48:30 +00007321/// EvaluateBuiltinConstantPForLValue - Determine the result of
7322/// __builtin_constant_p when applied to the given lvalue.
7323///
7324/// An lvalue is only "constant" if it is a pointer or reference to the first
7325/// character of a string literal.
7326template<typename LValue>
7327static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007328 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007329 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7330}
7331
7332/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7333/// GCC as we can manage.
7334static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7335 QualType ArgType = Arg->getType();
7336
7337 // __builtin_constant_p always has one operand. The rules which gcc follows
7338 // are not precisely documented, but are as follows:
7339 //
7340 // - If the operand is of integral, floating, complex or enumeration type,
7341 // and can be folded to a known value of that type, it returns 1.
7342 // - If the operand and can be folded to a pointer to the first character
7343 // of a string literal (or such a pointer cast to an integral type), it
7344 // returns 1.
7345 //
7346 // Otherwise, it returns 0.
7347 //
7348 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7349 // its support for this does not currently work.
7350 if (ArgType->isIntegralOrEnumerationType()) {
7351 Expr::EvalResult Result;
7352 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7353 return false;
7354
7355 APValue &V = Result.Val;
7356 if (V.getKind() == APValue::Int)
7357 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007358 if (V.getKind() == APValue::LValue)
7359 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007360 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7361 return Arg->isEvaluatable(Ctx);
7362 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7363 LValue LV;
7364 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007365 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007366 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7367 : EvaluatePointer(Arg, LV, Info)) &&
7368 !Status.HasSideEffects)
7369 return EvaluateBuiltinConstantPForLValue(LV);
7370 }
7371
7372 // Anything else isn't considered to be sufficiently constant.
7373 return false;
7374}
7375
John McCall95007602010-05-10 23:27:23 +00007376/// Retrieves the "underlying object type" of the given expression,
7377/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007378static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007379 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7380 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007381 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007382 } else if (const Expr *E = B.get<const Expr*>()) {
7383 if (isa<CompoundLiteralExpr>(E))
7384 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007385 }
7386
7387 return QualType();
7388}
7389
George Burgess IV3a03fab2015-09-04 21:28:13 +00007390/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007391/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007392/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007393/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7394///
7395/// Always returns an RValue with a pointer representation.
7396static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7397 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7398
7399 auto *NoParens = E->IgnoreParens();
7400 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007401 if (Cast == nullptr)
7402 return NoParens;
7403
7404 // We only conservatively allow a few kinds of casts, because this code is
7405 // inherently a simple solution that seeks to support the common case.
7406 auto CastKind = Cast->getCastKind();
7407 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7408 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007409 return NoParens;
7410
7411 auto *SubExpr = Cast->getSubExpr();
7412 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7413 return NoParens;
7414 return ignorePointerCastsAndParens(SubExpr);
7415}
7416
George Burgess IVa51c4072015-10-16 01:49:01 +00007417/// Checks to see if the given LValue's Designator is at the end of the LValue's
7418/// record layout. e.g.
7419/// struct { struct { int a, b; } fst, snd; } obj;
7420/// obj.fst // no
7421/// obj.snd // yes
7422/// obj.fst.a // no
7423/// obj.fst.b // no
7424/// obj.snd.a // no
7425/// obj.snd.b // yes
7426///
7427/// Please note: this function is specialized for how __builtin_object_size
7428/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007429///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007430/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7431/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007432static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7433 assert(!LVal.Designator.Invalid);
7434
George Burgess IV4168d752016-06-27 19:40:41 +00007435 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7436 const RecordDecl *Parent = FD->getParent();
7437 Invalid = Parent->isInvalidDecl();
7438 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007439 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007440 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007441 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7442 };
7443
7444 auto &Base = LVal.getLValueBase();
7445 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7446 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007447 bool Invalid;
7448 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7449 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007450 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007451 for (auto *FD : IFD->chain()) {
7452 bool Invalid;
7453 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7454 return Invalid;
7455 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007456 }
7457 }
7458
George Burgess IVe3763372016-12-22 02:50:20 +00007459 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007460 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007461 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007462 // If we don't know the array bound, conservatively assume we're looking at
7463 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007464 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007465 if (BaseType->isIncompleteArrayType())
7466 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7467 else
7468 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007469 }
7470
7471 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7472 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007473 if (BaseType->isArrayType()) {
7474 // Because __builtin_object_size treats arrays as objects, we can ignore
7475 // the index iff this is the last array in the Designator.
7476 if (I + 1 == E)
7477 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007478 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7479 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007480 if (Index + 1 != CAT->getSize())
7481 return false;
7482 BaseType = CAT->getElementType();
7483 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007484 const auto *CT = BaseType->castAs<ComplexType>();
7485 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007486 if (Index != 1)
7487 return false;
7488 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007489 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007490 bool Invalid;
7491 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7492 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007493 BaseType = FD->getType();
7494 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007495 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007496 return false;
7497 }
7498 }
7499 return true;
7500}
7501
George Burgess IVe3763372016-12-22 02:50:20 +00007502/// Tests to see if the LValue has a user-specified designator (that isn't
7503/// necessarily valid). Note that this always returns 'true' if the LValue has
7504/// an unsized array as its first designator entry, because there's currently no
7505/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007506static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007507 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007508 return false;
7509
George Burgess IVe3763372016-12-22 02:50:20 +00007510 if (!LVal.Designator.Entries.empty())
7511 return LVal.Designator.isMostDerivedAnUnsizedArray();
7512
George Burgess IVa51c4072015-10-16 01:49:01 +00007513 if (!LVal.InvalidBase)
7514 return true;
7515
George Burgess IVe3763372016-12-22 02:50:20 +00007516 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7517 // the LValueBase.
7518 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7519 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007520}
7521
George Burgess IVe3763372016-12-22 02:50:20 +00007522/// Attempts to detect a user writing into a piece of memory that's impossible
7523/// to figure out the size of by just using types.
7524static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7525 const SubobjectDesignator &Designator = LVal.Designator;
7526 // Notes:
7527 // - Users can only write off of the end when we have an invalid base. Invalid
7528 // bases imply we don't know where the memory came from.
7529 // - We used to be a bit more aggressive here; we'd only be conservative if
7530 // the array at the end was flexible, or if it had 0 or 1 elements. This
7531 // broke some common standard library extensions (PR30346), but was
7532 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7533 // with some sort of whitelist. OTOH, it seems that GCC is always
7534 // conservative with the last element in structs (if it's an array), so our
7535 // current behavior is more compatible than a whitelisting approach would
7536 // be.
7537 return LVal.InvalidBase &&
7538 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7539 Designator.MostDerivedIsArrayElement &&
7540 isDesignatorAtObjectEnd(Ctx, LVal);
7541}
7542
7543/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7544/// Fails if the conversion would cause loss of precision.
7545static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7546 CharUnits &Result) {
7547 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7548 if (Int.ugt(CharUnitsMax))
7549 return false;
7550 Result = CharUnits::fromQuantity(Int.getZExtValue());
7551 return true;
7552}
7553
7554/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7555/// determine how many bytes exist from the beginning of the object to either
7556/// the end of the current subobject, or the end of the object itself, depending
7557/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007558///
George Burgess IVe3763372016-12-22 02:50:20 +00007559/// If this returns false, the value of Result is undefined.
7560static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7561 unsigned Type, const LValue &LVal,
7562 CharUnits &EndOffset) {
7563 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007564
George Burgess IV7fb7e362017-01-03 23:35:19 +00007565 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7566 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7567 return false;
7568 return HandleSizeof(Info, ExprLoc, Ty, Result);
7569 };
7570
George Burgess IVe3763372016-12-22 02:50:20 +00007571 // We want to evaluate the size of the entire object. This is a valid fallback
7572 // for when Type=1 and the designator is invalid, because we're asked for an
7573 // upper-bound.
7574 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7575 // Type=3 wants a lower bound, so we can't fall back to this.
7576 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007577 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007578
7579 llvm::APInt APEndOffset;
7580 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7581 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7582 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7583
7584 if (LVal.InvalidBase)
7585 return false;
7586
7587 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007588 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007589 }
7590
George Burgess IVe3763372016-12-22 02:50:20 +00007591 // We want to evaluate the size of a subobject.
7592 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007593
7594 // The following is a moderately common idiom in C:
7595 //
7596 // struct Foo { int a; char c[1]; };
7597 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7598 // strcpy(&F->c[0], Bar);
7599 //
George Burgess IVe3763372016-12-22 02:50:20 +00007600 // In order to not break too much legacy code, we need to support it.
7601 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7602 // If we can resolve this to an alloc_size call, we can hand that back,
7603 // because we know for certain how many bytes there are to write to.
7604 llvm::APInt APEndOffset;
7605 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7606 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7607 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7608
7609 // If we cannot determine the size of the initial allocation, then we can't
7610 // given an accurate upper-bound. However, we are still able to give
7611 // conservative lower-bounds for Type=3.
7612 if (Type == 1)
7613 return false;
7614 }
7615
7616 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007617 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007618 return false;
7619
George Burgess IVe3763372016-12-22 02:50:20 +00007620 // According to the GCC documentation, we want the size of the subobject
7621 // denoted by the pointer. But that's not quite right -- what we actually
7622 // want is the size of the immediately-enclosing array, if there is one.
7623 int64_t ElemsRemaining;
7624 if (Designator.MostDerivedIsArrayElement &&
7625 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7626 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7627 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7628 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7629 } else {
7630 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7631 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007632
George Burgess IVe3763372016-12-22 02:50:20 +00007633 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7634 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007635}
7636
George Burgess IVe3763372016-12-22 02:50:20 +00007637/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7638/// returns true and stores the result in @p Size.
7639///
7640/// If @p WasError is non-null, this will report whether the failure to evaluate
7641/// is to be treated as an Error in IntExprEvaluator.
7642static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7643 EvalInfo &Info, uint64_t &Size) {
7644 // Determine the denoted object.
7645 LValue LVal;
7646 {
7647 // The operand of __builtin_object_size is never evaluated for side-effects.
7648 // If there are any, but we can determine the pointed-to object anyway, then
7649 // ignore the side-effects.
7650 SpeculativeEvaluationRAII SpeculativeEval(Info);
7651 FoldOffsetRAII Fold(Info);
7652
7653 if (E->isGLValue()) {
7654 // It's possible for us to be given GLValues if we're called via
7655 // Expr::tryEvaluateObjectSize.
7656 APValue RVal;
7657 if (!EvaluateAsRValue(Info, E, RVal))
7658 return false;
7659 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007660 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7661 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007662 return false;
7663 }
7664
7665 // If we point to before the start of the object, there are no accessible
7666 // bytes.
7667 if (LVal.getLValueOffset().isNegative()) {
7668 Size = 0;
7669 return true;
7670 }
7671
7672 CharUnits EndOffset;
7673 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7674 return false;
7675
7676 // If we've fallen outside of the end offset, just pretend there's nothing to
7677 // write to/read from.
7678 if (EndOffset <= LVal.getLValueOffset())
7679 Size = 0;
7680 else
7681 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7682 return true;
John McCall95007602010-05-10 23:27:23 +00007683}
7684
Peter Collingbournee9200682011-05-13 03:29:01 +00007685bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007686 if (unsigned BuiltinOp = E->getBuiltinCallee())
7687 return VisitBuiltinCallExpr(E, BuiltinOp);
7688
7689 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7690}
7691
7692bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7693 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007694 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007695 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007696 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007697
7698 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007699 // The type was checked when we built the expression.
7700 unsigned Type =
7701 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7702 assert(Type <= 3 && "unexpected type");
7703
George Burgess IVe3763372016-12-22 02:50:20 +00007704 uint64_t Size;
7705 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7706 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007707
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007708 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007709 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007710
Richard Smith01ade172012-05-23 04:13:20 +00007711 // Expression had no side effects, but we couldn't statically determine the
7712 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007713 switch (Info.EvalMode) {
7714 case EvalInfo::EM_ConstantExpression:
7715 case EvalInfo::EM_PotentialConstantExpression:
7716 case EvalInfo::EM_ConstantFold:
7717 case EvalInfo::EM_EvaluateForOverflow:
7718 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007719 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007720 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007721 return Error(E);
7722 case EvalInfo::EM_ConstantExpressionUnevaluated:
7723 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007724 // Reduce it to a constant now.
7725 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007726 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007727
7728 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007729 }
7730
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007731 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007732 case Builtin::BI__builtin_bswap32:
7733 case Builtin::BI__builtin_bswap64: {
7734 APSInt Val;
7735 if (!EvaluateInteger(E->getArg(0), Val, Info))
7736 return false;
7737
7738 return Success(Val.byteSwap(), E);
7739 }
7740
Richard Smith8889a3d2013-06-13 06:26:32 +00007741 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007742 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007743
7744 // FIXME: BI__builtin_clrsb
7745 // FIXME: BI__builtin_clrsbl
7746 // FIXME: BI__builtin_clrsbll
7747
Richard Smith80b3c8e2013-06-13 05:04:16 +00007748 case Builtin::BI__builtin_clz:
7749 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007750 case Builtin::BI__builtin_clzll:
7751 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007752 APSInt Val;
7753 if (!EvaluateInteger(E->getArg(0), Val, Info))
7754 return false;
7755 if (!Val)
7756 return Error(E);
7757
7758 return Success(Val.countLeadingZeros(), E);
7759 }
7760
Richard Smith8889a3d2013-06-13 06:26:32 +00007761 case Builtin::BI__builtin_constant_p:
7762 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7763
Richard Smith80b3c8e2013-06-13 05:04:16 +00007764 case Builtin::BI__builtin_ctz:
7765 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007766 case Builtin::BI__builtin_ctzll:
7767 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007768 APSInt Val;
7769 if (!EvaluateInteger(E->getArg(0), Val, Info))
7770 return false;
7771 if (!Val)
7772 return Error(E);
7773
7774 return Success(Val.countTrailingZeros(), E);
7775 }
7776
Richard Smith8889a3d2013-06-13 06:26:32 +00007777 case Builtin::BI__builtin_eh_return_data_regno: {
7778 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7779 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7780 return Success(Operand, E);
7781 }
7782
7783 case Builtin::BI__builtin_expect:
7784 return Visit(E->getArg(0));
7785
7786 case Builtin::BI__builtin_ffs:
7787 case Builtin::BI__builtin_ffsl:
7788 case Builtin::BI__builtin_ffsll: {
7789 APSInt Val;
7790 if (!EvaluateInteger(E->getArg(0), Val, Info))
7791 return false;
7792
7793 unsigned N = Val.countTrailingZeros();
7794 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7795 }
7796
7797 case Builtin::BI__builtin_fpclassify: {
7798 APFloat Val(0.0);
7799 if (!EvaluateFloat(E->getArg(5), Val, Info))
7800 return false;
7801 unsigned Arg;
7802 switch (Val.getCategory()) {
7803 case APFloat::fcNaN: Arg = 0; break;
7804 case APFloat::fcInfinity: Arg = 1; break;
7805 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7806 case APFloat::fcZero: Arg = 4; break;
7807 }
7808 return Visit(E->getArg(Arg));
7809 }
7810
7811 case Builtin::BI__builtin_isinf_sign: {
7812 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007813 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007814 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7815 }
7816
Richard Smithea3019d2013-10-15 19:07:14 +00007817 case Builtin::BI__builtin_isinf: {
7818 APFloat Val(0.0);
7819 return EvaluateFloat(E->getArg(0), Val, Info) &&
7820 Success(Val.isInfinity() ? 1 : 0, E);
7821 }
7822
7823 case Builtin::BI__builtin_isfinite: {
7824 APFloat Val(0.0);
7825 return EvaluateFloat(E->getArg(0), Val, Info) &&
7826 Success(Val.isFinite() ? 1 : 0, E);
7827 }
7828
7829 case Builtin::BI__builtin_isnan: {
7830 APFloat Val(0.0);
7831 return EvaluateFloat(E->getArg(0), Val, Info) &&
7832 Success(Val.isNaN() ? 1 : 0, E);
7833 }
7834
7835 case Builtin::BI__builtin_isnormal: {
7836 APFloat Val(0.0);
7837 return EvaluateFloat(E->getArg(0), Val, Info) &&
7838 Success(Val.isNormal() ? 1 : 0, E);
7839 }
7840
Richard Smith8889a3d2013-06-13 06:26:32 +00007841 case Builtin::BI__builtin_parity:
7842 case Builtin::BI__builtin_parityl:
7843 case Builtin::BI__builtin_parityll: {
7844 APSInt Val;
7845 if (!EvaluateInteger(E->getArg(0), Val, Info))
7846 return false;
7847
7848 return Success(Val.countPopulation() % 2, E);
7849 }
7850
Richard Smith80b3c8e2013-06-13 05:04:16 +00007851 case Builtin::BI__builtin_popcount:
7852 case Builtin::BI__builtin_popcountl:
7853 case Builtin::BI__builtin_popcountll: {
7854 APSInt Val;
7855 if (!EvaluateInteger(E->getArg(0), Val, Info))
7856 return false;
7857
7858 return Success(Val.countPopulation(), E);
7859 }
7860
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007861 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007862 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007863 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007864 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007865 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007866 << /*isConstexpr*/0 << /*isConstructor*/0
7867 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007868 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007869 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007870 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007871 case Builtin::BI__builtin_strlen:
7872 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007873 // As an extension, we support __builtin_strlen() as a constant expression,
7874 // and support folding strlen() to a constant.
7875 LValue String;
7876 if (!EvaluatePointer(E->getArg(0), String, Info))
7877 return false;
7878
Richard Smith8110c9d2016-11-29 19:45:17 +00007879 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7880
Richard Smithe6c19f22013-11-15 02:10:04 +00007881 // Fast path: if it's a string literal, search the string value.
7882 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7883 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007884 // The string literal may have embedded null characters. Find the first
7885 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007886 StringRef Str = S->getBytes();
7887 int64_t Off = String.Offset.getQuantity();
7888 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007889 S->getCharByteWidth() == 1 &&
7890 // FIXME: Add fast-path for wchar_t too.
7891 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007892 Str = Str.substr(Off);
7893
7894 StringRef::size_type Pos = Str.find(0);
7895 if (Pos != StringRef::npos)
7896 Str = Str.substr(0, Pos);
7897
7898 return Success(Str.size(), E);
7899 }
7900
7901 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007902 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007903
7904 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007905 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7906 APValue Char;
7907 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7908 !Char.isInt())
7909 return false;
7910 if (!Char.getInt())
7911 return Success(Strlen, E);
7912 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7913 return false;
7914 }
7915 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007916
Richard Smithe151bab2016-11-11 23:43:35 +00007917 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007918 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007919 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007920 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007921 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007922 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007923 // A call to strlen is not a constant expression.
7924 if (Info.getLangOpts().CPlusPlus11)
7925 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7926 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007927 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007928 else
7929 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007930 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00007931 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007932 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007933 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007934 case Builtin::BI__builtin_wcsncmp:
7935 case Builtin::BI__builtin_memcmp:
7936 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007937 LValue String1, String2;
7938 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7939 !EvaluatePointer(E->getArg(1), String2, Info))
7940 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007941
7942 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7943
Richard Smithe151bab2016-11-11 23:43:35 +00007944 uint64_t MaxLength = uint64_t(-1);
7945 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007946 BuiltinOp != Builtin::BIwcscmp &&
7947 BuiltinOp != Builtin::BI__builtin_strcmp &&
7948 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007949 APSInt N;
7950 if (!EvaluateInteger(E->getArg(2), N, Info))
7951 return false;
7952 MaxLength = N.getExtValue();
7953 }
7954 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007955 BuiltinOp != Builtin::BIwmemcmp &&
7956 BuiltinOp != Builtin::BI__builtin_memcmp &&
7957 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007958 for (; MaxLength; --MaxLength) {
7959 APValue Char1, Char2;
7960 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7961 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7962 !Char1.isInt() || !Char2.isInt())
7963 return false;
7964 if (Char1.getInt() != Char2.getInt())
7965 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7966 if (StopAtNull && !Char1.getInt())
7967 return Success(0, E);
7968 assert(!(StopAtNull && !Char2.getInt()));
7969 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7970 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7971 return false;
7972 }
7973 // We hit the strncmp / memcmp limit.
7974 return Success(0, E);
7975 }
7976
Richard Smith01ba47d2012-04-13 00:45:38 +00007977 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007978 case Builtin::BI__atomic_is_lock_free:
7979 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007980 APSInt SizeVal;
7981 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7982 return false;
7983
7984 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7985 // of two less than the maximum inline atomic width, we know it is
7986 // lock-free. If the size isn't a power of two, or greater than the
7987 // maximum alignment where we promote atomics, we know it is not lock-free
7988 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7989 // the answer can only be determined at runtime; for example, 16-byte
7990 // atomics have lock-free implementations on some, but not all,
7991 // x86-64 processors.
7992
7993 // Check power-of-two.
7994 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007995 if (Size.isPowerOfTwo()) {
7996 // Check against inlining width.
7997 unsigned InlineWidthBits =
7998 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7999 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8000 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8001 Size == CharUnits::One() ||
8002 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8003 Expr::NPC_NeverValueDependent))
8004 // OK, we will inline appropriately-aligned operations of this size,
8005 // and _Atomic(T) is appropriately-aligned.
8006 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008007
Richard Smith01ba47d2012-04-13 00:45:38 +00008008 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8009 castAs<PointerType>()->getPointeeType();
8010 if (!PointeeType->isIncompleteType() &&
8011 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8012 // OK, we will inline operations on this object.
8013 return Success(1, E);
8014 }
8015 }
8016 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008017
Richard Smith01ba47d2012-04-13 00:45:38 +00008018 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8019 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008020 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008021 case Builtin::BIomp_is_initial_device:
8022 // We can decide statically which value the runtime would return if called.
8023 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008024 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008025}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008026
Richard Smith8b3497e2011-10-31 01:37:14 +00008027static bool HasSameBase(const LValue &A, const LValue &B) {
8028 if (!A.getLValueBase())
8029 return !B.getLValueBase();
8030 if (!B.getLValueBase())
8031 return false;
8032
Richard Smithce40ad62011-11-12 22:28:03 +00008033 if (A.getLValueBase().getOpaqueValue() !=
8034 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008035 const Decl *ADecl = GetLValueBaseDecl(A);
8036 if (!ADecl)
8037 return false;
8038 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00008039 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00008040 return false;
8041 }
8042
8043 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00008044 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00008045}
8046
Richard Smithd20f1e62014-10-21 23:01:04 +00008047/// \brief Determine whether this is a pointer past the end of the complete
8048/// object referred to by the lvalue.
8049static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8050 const LValue &LV) {
8051 // A null pointer can be viewed as being "past the end" but we don't
8052 // choose to look at it that way here.
8053 if (!LV.getLValueBase())
8054 return false;
8055
8056 // If the designator is valid and refers to a subobject, we're not pointing
8057 // past the end.
8058 if (!LV.getLValueDesignator().Invalid &&
8059 !LV.getLValueDesignator().isOnePastTheEnd())
8060 return false;
8061
David Majnemerc378ca52015-08-29 08:32:55 +00008062 // A pointer to an incomplete type might be past-the-end if the type's size is
8063 // zero. We cannot tell because the type is incomplete.
8064 QualType Ty = getType(LV.getLValueBase());
8065 if (Ty->isIncompleteType())
8066 return true;
8067
Richard Smithd20f1e62014-10-21 23:01:04 +00008068 // We're a past-the-end pointer if we point to the byte after the object,
8069 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008070 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008071 return LV.getLValueOffset() == Size;
8072}
8073
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008074namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008075
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008076/// \brief Data recursive integer evaluator of certain binary operators.
8077///
8078/// We use a data recursive algorithm for binary operators so that we are able
8079/// to handle extreme cases of chained binary operators without causing stack
8080/// overflow.
8081class DataRecursiveIntBinOpEvaluator {
8082 struct EvalResult {
8083 APValue Val;
8084 bool Failed;
8085
8086 EvalResult() : Failed(false) { }
8087
8088 void swap(EvalResult &RHS) {
8089 Val.swap(RHS.Val);
8090 Failed = RHS.Failed;
8091 RHS.Failed = false;
8092 }
8093 };
8094
8095 struct Job {
8096 const Expr *E;
8097 EvalResult LHSResult; // meaningful only for binary operator expression.
8098 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008099
David Blaikie73726062015-08-12 23:09:24 +00008100 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008101 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008102
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008103 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008104 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008105 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008106
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008107 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008108 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008109 };
8110
8111 SmallVector<Job, 16> Queue;
8112
8113 IntExprEvaluator &IntEval;
8114 EvalInfo &Info;
8115 APValue &FinalResult;
8116
8117public:
8118 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8119 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8120
8121 /// \brief True if \param E is a binary operator that we are going to handle
8122 /// data recursively.
8123 /// We handle binary operators that are comma, logical, or that have operands
8124 /// with integral or enumeration type.
8125 static bool shouldEnqueue(const BinaryOperator *E) {
8126 return E->getOpcode() == BO_Comma ||
8127 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00008128 (E->isRValue() &&
8129 E->getType()->isIntegralOrEnumerationType() &&
8130 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008131 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008132 }
8133
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008134 bool Traverse(const BinaryOperator *E) {
8135 enqueue(E);
8136 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008137 while (!Queue.empty())
8138 process(PrevResult);
8139
8140 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008141
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008142 FinalResult.swap(PrevResult.Val);
8143 return true;
8144 }
8145
8146private:
8147 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8148 return IntEval.Success(Value, E, Result);
8149 }
8150 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8151 return IntEval.Success(Value, E, Result);
8152 }
8153 bool Error(const Expr *E) {
8154 return IntEval.Error(E);
8155 }
8156 bool Error(const Expr *E, diag::kind D) {
8157 return IntEval.Error(E, D);
8158 }
8159
8160 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8161 return Info.CCEDiag(E, D);
8162 }
8163
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008164 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8165 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008166 bool &SuppressRHSDiags);
8167
8168 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8169 const BinaryOperator *E, APValue &Result);
8170
8171 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8172 Result.Failed = !Evaluate(Result.Val, Info, E);
8173 if (Result.Failed)
8174 Result.Val = APValue();
8175 }
8176
Richard Trieuba4d0872012-03-21 23:30:30 +00008177 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008178
8179 void enqueue(const Expr *E) {
8180 E = E->IgnoreParens();
8181 Queue.resize(Queue.size()+1);
8182 Queue.back().E = E;
8183 Queue.back().Kind = Job::AnyExprKind;
8184 }
8185};
8186
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008187}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008188
8189bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008190 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008191 bool &SuppressRHSDiags) {
8192 if (E->getOpcode() == BO_Comma) {
8193 // Ignore LHS but note if we could not evaluate it.
8194 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008195 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008196 return true;
8197 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008198
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008199 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008200 bool LHSAsBool;
8201 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008202 // We were able to evaluate the LHS, see if we can get away with not
8203 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008204 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8205 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008206 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008207 }
8208 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008209 LHSResult.Failed = true;
8210
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008211 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008212 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008213 if (!Info.noteSideEffect())
8214 return false;
8215
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008216 // We can't evaluate the LHS; however, sometimes the result
8217 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8218 // Don't ignore RHS and suppress diagnostics from this arm.
8219 SuppressRHSDiags = true;
8220 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008221
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008222 return true;
8223 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008224
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008225 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8226 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008227
George Burgess IVa145e252016-05-25 22:38:36 +00008228 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008229 return false; // Ignore RHS;
8230
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008231 return true;
8232}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008233
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008234static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8235 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008236 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8237 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8238 // offsets.
8239 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8240 CharUnits &Offset = LVal.getLValueOffset();
8241 uint64_t Offset64 = Offset.getQuantity();
8242 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8243 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8244 : Offset64 + Index64);
8245}
8246
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008247bool DataRecursiveIntBinOpEvaluator::
8248 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8249 const BinaryOperator *E, APValue &Result) {
8250 if (E->getOpcode() == BO_Comma) {
8251 if (RHSResult.Failed)
8252 return false;
8253 Result = RHSResult.Val;
8254 return true;
8255 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008256
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008257 if (E->isLogicalOp()) {
8258 bool lhsResult, rhsResult;
8259 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8260 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008261
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008262 if (LHSIsOK) {
8263 if (RHSIsOK) {
8264 if (E->getOpcode() == BO_LOr)
8265 return Success(lhsResult || rhsResult, E, Result);
8266 else
8267 return Success(lhsResult && rhsResult, E, Result);
8268 }
8269 } else {
8270 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008271 // We can't evaluate the LHS; however, sometimes the result
8272 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8273 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008274 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008275 }
8276 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008277
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008278 return false;
8279 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008280
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008281 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8282 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008283
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008284 if (LHSResult.Failed || RHSResult.Failed)
8285 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008286
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008287 const APValue &LHSVal = LHSResult.Val;
8288 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008289
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008290 // Handle cases like (unsigned long)&a + 4.
8291 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8292 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008293 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008294 return true;
8295 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008296
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008297 // Handle cases like 4 + (unsigned long)&a
8298 if (E->getOpcode() == BO_Add &&
8299 RHSVal.isLValue() && LHSVal.isInt()) {
8300 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008301 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008302 return true;
8303 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008304
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008305 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8306 // Handle (intptr_t)&&A - (intptr_t)&&B.
8307 if (!LHSVal.getLValueOffset().isZero() ||
8308 !RHSVal.getLValueOffset().isZero())
8309 return false;
8310 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8311 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8312 if (!LHSExpr || !RHSExpr)
8313 return false;
8314 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8315 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8316 if (!LHSAddrExpr || !RHSAddrExpr)
8317 return false;
8318 // Make sure both labels come from the same function.
8319 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8320 RHSAddrExpr->getLabel()->getDeclContext())
8321 return false;
8322 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8323 return true;
8324 }
Richard Smith43e77732013-05-07 04:50:00 +00008325
8326 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008327 if (!LHSVal.isInt() || !RHSVal.isInt())
8328 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008329
8330 // Set up the width and signedness manually, in case it can't be deduced
8331 // from the operation we're performing.
8332 // FIXME: Don't do this in the cases where we can deduce it.
8333 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8334 E->getType()->isUnsignedIntegerOrEnumerationType());
8335 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8336 RHSVal.getInt(), Value))
8337 return false;
8338 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008339}
8340
Richard Trieuba4d0872012-03-21 23:30:30 +00008341void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008342 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008343
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008344 switch (job.Kind) {
8345 case Job::AnyExprKind: {
8346 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8347 if (shouldEnqueue(Bop)) {
8348 job.Kind = Job::BinOpKind;
8349 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008350 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008351 }
8352 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008353
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008354 EvaluateExpr(job.E, Result);
8355 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008356 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008357 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008358
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008359 case Job::BinOpKind: {
8360 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008361 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008362 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008363 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008364 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008365 }
8366 if (SuppressRHSDiags)
8367 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008368 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008369 job.Kind = Job::BinOpVisitedLHSKind;
8370 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008371 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008372 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008373
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008374 case Job::BinOpVisitedLHSKind: {
8375 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8376 EvalResult RHS;
8377 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008378 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008379 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008380 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008381 }
8382 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008383
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008384 llvm_unreachable("Invalid Job::Kind!");
8385}
8386
George Burgess IV8c892b52016-05-25 22:31:54 +00008387namespace {
8388/// Used when we determine that we should fail, but can keep evaluating prior to
8389/// noting that we had a failure.
8390class DelayedNoteFailureRAII {
8391 EvalInfo &Info;
8392 bool NoteFailure;
8393
8394public:
8395 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8396 : Info(Info), NoteFailure(NoteFailure) {}
8397 ~DelayedNoteFailureRAII() {
8398 if (NoteFailure) {
8399 bool ContinueAfterFailure = Info.noteFailure();
8400 (void)ContinueAfterFailure;
8401 assert(ContinueAfterFailure &&
8402 "Shouldn't have kept evaluating on failure.");
8403 }
8404 }
8405};
8406}
8407
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008408bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008409 // We don't call noteFailure immediately because the assignment happens after
8410 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008411 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008412 return Error(E);
8413
George Burgess IV8c892b52016-05-25 22:31:54 +00008414 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008415 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8416 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008417
Anders Carlssonacc79812008-11-16 07:17:21 +00008418 QualType LHSTy = E->getLHS()->getType();
8419 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008420
Chandler Carruthb29a7432014-10-11 11:03:30 +00008421 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008422 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008423 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008424 if (E->isAssignmentOp()) {
8425 LValue LV;
8426 EvaluateLValue(E->getLHS(), LV, Info);
8427 LHSOK = false;
8428 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008429 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8430 if (LHSOK) {
8431 LHS.makeComplexFloat();
8432 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8433 }
8434 } else {
8435 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8436 }
George Burgess IVa145e252016-05-25 22:38:36 +00008437 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008438 return false;
8439
Chandler Carruthb29a7432014-10-11 11:03:30 +00008440 if (E->getRHS()->getType()->isRealFloatingType()) {
8441 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8442 return false;
8443 RHS.makeComplexFloat();
8444 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8445 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008446 return false;
8447
8448 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008449 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008450 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008451 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008452 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8453
John McCalle3027922010-08-25 11:45:40 +00008454 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008455 return Success((CR_r == APFloat::cmpEqual &&
8456 CR_i == APFloat::cmpEqual), E);
8457 else {
John McCalle3027922010-08-25 11:45:40 +00008458 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008459 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008460 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008461 CR_r == APFloat::cmpLessThan ||
8462 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008463 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008464 CR_i == APFloat::cmpLessThan ||
8465 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008466 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008467 } else {
John McCalle3027922010-08-25 11:45:40 +00008468 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008469 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8470 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8471 else {
John McCalle3027922010-08-25 11:45:40 +00008472 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008473 "Invalid compex comparison.");
8474 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8475 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8476 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008477 }
8478 }
Mike Stump11289f42009-09-09 15:08:12 +00008479
Anders Carlssonacc79812008-11-16 07:17:21 +00008480 if (LHSTy->isRealFloatingType() &&
8481 RHSTy->isRealFloatingType()) {
8482 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008483
Richard Smith253c2a32012-01-27 01:14:48 +00008484 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008485 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008486 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008487
Richard Smith253c2a32012-01-27 01:14:48 +00008488 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008489 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008490
Anders Carlssonacc79812008-11-16 07:17:21 +00008491 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008492
Anders Carlssonacc79812008-11-16 07:17:21 +00008493 switch (E->getOpcode()) {
8494 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008495 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008496 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008497 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008498 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008499 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008500 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008501 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008502 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008503 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008504 E);
John McCalle3027922010-08-25 11:45:40 +00008505 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008506 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008507 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008508 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008509 || CR == APFloat::cmpLessThan
8510 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008511 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008512 }
Mike Stump11289f42009-09-09 15:08:12 +00008513
Eli Friedmana38da572009-04-28 19:17:36 +00008514 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008515 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008516 LValue LHSValue, RHSValue;
8517
8518 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008519 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008520 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008521
Richard Smith253c2a32012-01-27 01:14:48 +00008522 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008523 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008524
Richard Smith8b3497e2011-10-31 01:37:14 +00008525 // Reject differing bases from the normal codepath; we special-case
8526 // comparisons to null.
8527 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008528 if (E->getOpcode() == BO_Sub) {
8529 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008530 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008531 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008532 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008533 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008534 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008535 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008536 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8537 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8538 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008539 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008540 // Make sure both labels come from the same function.
8541 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8542 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008543 return Error(E);
8544 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008545 }
Richard Smith83c68212011-10-31 05:11:32 +00008546 // Inequalities and subtractions between unrelated pointers have
8547 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008548 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008549 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008550 // A constant address may compare equal to the address of a symbol.
8551 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008552 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008553 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8554 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008555 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008556 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008557 // distinct addresses. In clang, the result of such a comparison is
8558 // unspecified, so it is not a constant expression. However, we do know
8559 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008560 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8561 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008562 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008563 // We can't tell whether weak symbols will end up pointing to the same
8564 // object.
8565 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008566 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008567 // We can't compare the address of the start of one object with the
8568 // past-the-end address of another object, per C++ DR1652.
8569 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8570 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8571 (RHSValue.Base && RHSValue.Offset.isZero() &&
8572 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8573 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008574 // We can't tell whether an object is at the same address as another
8575 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008576 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8577 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008578 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008579 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008580 // (Note that clang defaults to -fmerge-all-constants, which can
8581 // lead to inconsistent results for comparisons involving the address
8582 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008583 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008584 }
Eli Friedman64004332009-03-23 04:38:34 +00008585
Richard Smith1b470412012-02-01 08:10:20 +00008586 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8587 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8588
Richard Smith84f6dcf2012-02-02 01:16:57 +00008589 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8590 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8591
John McCalle3027922010-08-25 11:45:40 +00008592 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008593 // C++11 [expr.add]p6:
8594 // Unless both pointers point to elements of the same array object, or
8595 // one past the last element of the array object, the behavior is
8596 // undefined.
8597 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8598 !AreElementsOfSameArray(getType(LHSValue.Base),
8599 LHSDesignator, RHSDesignator))
8600 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8601
Chris Lattner882bdf22010-04-20 17:13:14 +00008602 QualType Type = E->getLHS()->getType();
8603 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008604
Richard Smithd62306a2011-11-10 06:34:14 +00008605 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008606 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008607 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008608
Richard Smith84c6b3d2013-09-10 21:34:14 +00008609 // As an extension, a type may have zero size (empty struct or union in
8610 // C, array of zero length). Pointer subtraction in such cases has
8611 // undefined behavior, so is not constant.
8612 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008613 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008614 << ElementType;
8615 return false;
8616 }
8617
Richard Smith1b470412012-02-01 08:10:20 +00008618 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8619 // and produce incorrect results when it overflows. Such behavior
8620 // appears to be non-conforming, but is common, so perhaps we should
8621 // assume the standard intended for such cases to be undefined behavior
8622 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008623
Richard Smith1b470412012-02-01 08:10:20 +00008624 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8625 // overflow in the final conversion to ptrdiff_t.
8626 APSInt LHS(
8627 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8628 APSInt RHS(
8629 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8630 APSInt ElemSize(
8631 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8632 APSInt TrueResult = (LHS - RHS) / ElemSize;
8633 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8634
Richard Smith0c6124b2015-12-03 01:36:22 +00008635 if (Result.extend(65) != TrueResult &&
8636 !HandleOverflow(Info, E, TrueResult, E->getType()))
8637 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008638 return Success(Result, E);
8639 }
Richard Smithde21b242012-01-31 06:41:30 +00008640
8641 // C++11 [expr.rel]p3:
8642 // Pointers to void (after pointer conversions) can be compared, with a
8643 // result defined as follows: If both pointers represent the same
8644 // address or are both the null pointer value, the result is true if the
8645 // operator is <= or >= and false otherwise; otherwise the result is
8646 // unspecified.
8647 // We interpret this as applying to pointers to *cv* void.
8648 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008649 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008650 CCEDiag(E, diag::note_constexpr_void_comparison);
8651
Richard Smith84f6dcf2012-02-02 01:16:57 +00008652 // C++11 [expr.rel]p2:
8653 // - If two pointers point to non-static data members of the same object,
8654 // or to subobjects or array elements fo such members, recursively, the
8655 // pointer to the later declared member compares greater provided the
8656 // two members have the same access control and provided their class is
8657 // not a union.
8658 // [...]
8659 // - Otherwise pointer comparisons are unspecified.
8660 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8661 E->isRelationalOp()) {
8662 bool WasArrayIndex;
8663 unsigned Mismatch =
8664 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8665 RHSDesignator, WasArrayIndex);
8666 // At the point where the designators diverge, the comparison has a
8667 // specified value if:
8668 // - we are comparing array indices
8669 // - we are comparing fields of a union, or fields with the same access
8670 // Otherwise, the result is unspecified and thus the comparison is not a
8671 // constant expression.
8672 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8673 Mismatch < RHSDesignator.Entries.size()) {
8674 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8675 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8676 if (!LF && !RF)
8677 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8678 else if (!LF)
8679 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8680 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8681 << RF->getParent() << RF;
8682 else if (!RF)
8683 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8684 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8685 << LF->getParent() << LF;
8686 else if (!LF->getParent()->isUnion() &&
8687 LF->getAccess() != RF->getAccess())
8688 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8689 << LF << LF->getAccess() << RF << RF->getAccess()
8690 << LF->getParent();
8691 }
8692 }
8693
Eli Friedman6c31cb42012-04-16 04:30:08 +00008694 // The comparison here must be unsigned, and performed with the same
8695 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008696 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8697 uint64_t CompareLHS = LHSOffset.getQuantity();
8698 uint64_t CompareRHS = RHSOffset.getQuantity();
8699 assert(PtrSize <= 64 && "Unexpected pointer width");
8700 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8701 CompareLHS &= Mask;
8702 CompareRHS &= Mask;
8703
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008704 // If there is a base and this is a relational operator, we can only
8705 // compare pointers within the object in question; otherwise, the result
8706 // depends on where the object is located in memory.
8707 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8708 QualType BaseTy = getType(LHSValue.Base);
8709 if (BaseTy->isIncompleteType())
8710 return Error(E);
8711 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8712 uint64_t OffsetLimit = Size.getQuantity();
8713 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8714 return Error(E);
8715 }
8716
Richard Smith8b3497e2011-10-31 01:37:14 +00008717 switch (E->getOpcode()) {
8718 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008719 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8720 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8721 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8722 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8723 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8724 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008725 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008726 }
8727 }
Richard Smith7bb00672012-02-01 01:42:44 +00008728
8729 if (LHSTy->isMemberPointerType()) {
8730 assert(E->isEqualityOp() && "unexpected member pointer operation");
8731 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8732
8733 MemberPtr LHSValue, RHSValue;
8734
8735 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008736 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008737 return false;
8738
8739 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8740 return false;
8741
8742 // C++11 [expr.eq]p2:
8743 // If both operands are null, they compare equal. Otherwise if only one is
8744 // null, they compare unequal.
8745 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8746 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8747 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8748 }
8749
8750 // Otherwise if either is a pointer to a virtual member function, the
8751 // result is unspecified.
8752 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8753 if (MD->isVirtual())
8754 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8755 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8756 if (MD->isVirtual())
8757 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8758
8759 // Otherwise they compare equal if and only if they would refer to the
8760 // same member of the same most derived object or the same subobject if
8761 // they were dereferenced with a hypothetical object of the associated
8762 // class type.
8763 bool Equal = LHSValue == RHSValue;
8764 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8765 }
8766
Richard Smithab44d9b2012-02-14 22:35:28 +00008767 if (LHSTy->isNullPtrType()) {
8768 assert(E->isComparisonOp() && "unexpected nullptr operation");
8769 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8770 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8771 // are compared, the result is true of the operator is <=, >= or ==, and
8772 // false otherwise.
8773 BinaryOperator::Opcode Opcode = E->getOpcode();
8774 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8775 }
8776
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008777 assert((!LHSTy->isIntegralOrEnumerationType() ||
8778 !RHSTy->isIntegralOrEnumerationType()) &&
8779 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8780 // We can't continue from here for non-integral types.
8781 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008782}
8783
Peter Collingbournee190dee2011-03-11 19:24:49 +00008784/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8785/// a result as the expression's type.
8786bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8787 const UnaryExprOrTypeTraitExpr *E) {
8788 switch(E->getKind()) {
8789 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008790 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008791 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008792 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008793 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008794 }
Eli Friedman64004332009-03-23 04:38:34 +00008795
Peter Collingbournee190dee2011-03-11 19:24:49 +00008796 case UETT_VecStep: {
8797 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008798
Peter Collingbournee190dee2011-03-11 19:24:49 +00008799 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008800 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008801
Peter Collingbournee190dee2011-03-11 19:24:49 +00008802 // The vec_step built-in functions that take a 3-component
8803 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8804 if (n == 3)
8805 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008806
Peter Collingbournee190dee2011-03-11 19:24:49 +00008807 return Success(n, E);
8808 } else
8809 return Success(1, E);
8810 }
8811
8812 case UETT_SizeOf: {
8813 QualType SrcTy = E->getTypeOfArgument();
8814 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8815 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008816 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8817 SrcTy = Ref->getPointeeType();
8818
Richard Smithd62306a2011-11-10 06:34:14 +00008819 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008820 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008821 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008822 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008823 }
Alexey Bataev00396512015-07-02 03:40:19 +00008824 case UETT_OpenMPRequiredSimdAlign:
8825 assert(E->isArgumentType());
8826 return Success(
8827 Info.Ctx.toCharUnitsFromBits(
8828 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8829 .getQuantity(),
8830 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008831 }
8832
8833 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008834}
8835
Peter Collingbournee9200682011-05-13 03:29:01 +00008836bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008837 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008838 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008839 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008840 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008841 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008842 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008843 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008844 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008845 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008846 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008847 APSInt IdxResult;
8848 if (!EvaluateInteger(Idx, IdxResult, Info))
8849 return false;
8850 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8851 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008852 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008853 CurrentType = AT->getElementType();
8854 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8855 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008856 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008857 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008858
James Y Knight7281c352015-12-29 22:31:18 +00008859 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008860 FieldDecl *MemberDecl = ON.getField();
8861 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008862 if (!RT)
8863 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008864 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008865 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008866 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008867 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008868 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008869 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008870 CurrentType = MemberDecl->getType().getNonReferenceType();
8871 break;
8872 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008873
James Y Knight7281c352015-12-29 22:31:18 +00008874 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008875 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008876
James Y Knight7281c352015-12-29 22:31:18 +00008877 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008878 CXXBaseSpecifier *BaseSpec = ON.getBase();
8879 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008880 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008881
8882 // Find the layout of the class whose base we are looking into.
8883 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008884 if (!RT)
8885 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008886 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008887 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008888 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8889
8890 // Find the base class itself.
8891 CurrentType = BaseSpec->getType();
8892 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8893 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008894 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00008895
Douglas Gregord1702062010-04-29 00:18:15 +00008896 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008897 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008898 break;
8899 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008900 }
8901 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008902 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008903}
8904
Chris Lattnere13042c2008-07-11 19:10:17 +00008905bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008906 switch (E->getOpcode()) {
8907 default:
8908 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8909 // See C99 6.6p3.
8910 return Error(E);
8911 case UO_Extension:
8912 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8913 // If so, we could clear the diagnostic ID.
8914 return Visit(E->getSubExpr());
8915 case UO_Plus:
8916 // The result is just the value.
8917 return Visit(E->getSubExpr());
8918 case UO_Minus: {
8919 if (!Visit(E->getSubExpr()))
Aaron Ballmana5038552018-01-09 13:07:03 +00008920 return false;
8921 if (!Result.isInt()) return Error(E);
8922 const APSInt &Value = Result.getInt();
8923 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
8924 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8925 E->getType()))
8926 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008927 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008928 }
8929 case UO_Not: {
8930 if (!Visit(E->getSubExpr()))
8931 return false;
8932 if (!Result.isInt()) return Error(E);
8933 return Success(~Result.getInt(), E);
8934 }
8935 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008936 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008937 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008938 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008939 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008940 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008941 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008942}
Mike Stump11289f42009-09-09 15:08:12 +00008943
Chris Lattner477c4be2008-07-12 01:15:53 +00008944/// HandleCast - This is used to evaluate implicit or explicit casts where the
8945/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008946bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8947 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008948 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008949 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008950
Eli Friedmanc757de22011-03-25 00:43:55 +00008951 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008952 case CK_BaseToDerived:
8953 case CK_DerivedToBase:
8954 case CK_UncheckedDerivedToBase:
8955 case CK_Dynamic:
8956 case CK_ToUnion:
8957 case CK_ArrayToPointerDecay:
8958 case CK_FunctionToPointerDecay:
8959 case CK_NullToPointer:
8960 case CK_NullToMemberPointer:
8961 case CK_BaseToDerivedMemberPointer:
8962 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008963 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008964 case CK_ConstructorConversion:
8965 case CK_IntegralToPointer:
8966 case CK_ToVoid:
8967 case CK_VectorSplat:
8968 case CK_IntegralToFloating:
8969 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008970 case CK_CPointerToObjCPointerCast:
8971 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008972 case CK_AnyPointerToBlockPointerCast:
8973 case CK_ObjCObjectLValueCast:
8974 case CK_FloatingRealToComplex:
8975 case CK_FloatingComplexToReal:
8976 case CK_FloatingComplexCast:
8977 case CK_FloatingComplexToIntegralComplex:
8978 case CK_IntegralRealToComplex:
8979 case CK_IntegralComplexCast:
8980 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008981 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008982 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008983 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008984 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008985 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008986 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008987 llvm_unreachable("invalid cast kind for integral value");
8988
Eli Friedman9faf2f92011-03-25 19:07:11 +00008989 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008990 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008991 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008992 case CK_ARCProduceObject:
8993 case CK_ARCConsumeObject:
8994 case CK_ARCReclaimReturnedObject:
8995 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008996 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008997 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008998
Richard Smith4ef685b2012-01-17 21:17:26 +00008999 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00009000 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009001 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009002 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009003 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009004
9005 case CK_MemberPointerToBoolean:
9006 case CK_PointerToBoolean:
9007 case CK_IntegralToBoolean:
9008 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009009 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009010 case CK_FloatingComplexToBoolean:
9011 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009012 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009013 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009014 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009015 uint64_t IntResult = BoolResult;
9016 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9017 IntResult = (uint64_t)-1;
9018 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009019 }
9020
Eli Friedmanc757de22011-03-25 00:43:55 +00009021 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009022 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009023 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009024
Eli Friedman742421e2009-02-20 01:15:07 +00009025 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009026 // Allow casts of address-of-label differences if they are no-ops
9027 // or narrowing. (The narrowing case isn't actually guaranteed to
9028 // be constant-evaluatable except in some narrow cases which are hard
9029 // to detect here. We let it through on the assumption the user knows
9030 // what they are doing.)
9031 if (Result.isAddrLabelDiff())
9032 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009033 // Only allow casts of lvalues if they are lossless.
9034 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9035 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009036
Richard Smith911e1422012-01-30 22:27:01 +00009037 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9038 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009039 }
Mike Stump11289f42009-09-09 15:08:12 +00009040
Eli Friedmanc757de22011-03-25 00:43:55 +00009041 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009042 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9043
John McCall45d55e42010-05-07 21:00:08 +00009044 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009045 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009046 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009047
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009048 if (LV.getLValueBase()) {
9049 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009050 // FIXME: Allow a larger integer size than the pointer size, and allow
9051 // narrowing back down to pointer width in subsequent integral casts.
9052 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009053 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009054 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009055
Richard Smithcf74da72011-11-16 07:18:12 +00009056 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009057 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009058 return true;
9059 }
9060
Yaxun Liu402804b2016-12-15 08:09:08 +00009061 uint64_t V;
9062 if (LV.isNullPointer())
9063 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9064 else
9065 V = LV.getLValueOffset().getQuantity();
9066
9067 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009068 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009069 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009070
Eli Friedmanc757de22011-03-25 00:43:55 +00009071 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009072 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009073 if (!EvaluateComplex(SubExpr, C, Info))
9074 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009075 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009076 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009077
Eli Friedmanc757de22011-03-25 00:43:55 +00009078 case CK_FloatingToIntegral: {
9079 APFloat F(0.0);
9080 if (!EvaluateFloat(SubExpr, F, Info))
9081 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009082
Richard Smith357362d2011-12-13 06:39:58 +00009083 APSInt Value;
9084 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9085 return false;
9086 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009087 }
9088 }
Mike Stump11289f42009-09-09 15:08:12 +00009089
Eli Friedmanc757de22011-03-25 00:43:55 +00009090 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009091}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009092
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009093bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9094 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009095 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009096 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9097 return false;
9098 if (!LV.isComplexInt())
9099 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009100 return Success(LV.getComplexIntReal(), E);
9101 }
9102
9103 return Visit(E->getSubExpr());
9104}
9105
Eli Friedman4e7a2412009-02-27 04:45:43 +00009106bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009107 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009108 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009109 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9110 return false;
9111 if (!LV.isComplexInt())
9112 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009113 return Success(LV.getComplexIntImag(), E);
9114 }
9115
Richard Smith4a678122011-10-24 18:44:57 +00009116 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009117 return Success(0, E);
9118}
9119
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009120bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9121 return Success(E->getPackLength(), E);
9122}
9123
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009124bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9125 return Success(E->getValue(), E);
9126}
9127
Chris Lattner05706e882008-07-11 18:11:29 +00009128//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009129// Float Evaluation
9130//===----------------------------------------------------------------------===//
9131
9132namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009133class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009134 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009135 APFloat &Result;
9136public:
9137 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009138 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009139
Richard Smith2e312c82012-03-03 22:46:17 +00009140 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009141 Result = V.getFloat();
9142 return true;
9143 }
Eli Friedman24c01542008-08-22 00:06:13 +00009144
Richard Smithfddd3842011-12-30 21:15:51 +00009145 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009146 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9147 return true;
9148 }
9149
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009150 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009151
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009152 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009153 bool VisitBinaryOperator(const BinaryOperator *E);
9154 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009155 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009156
John McCallb1fb0d32010-05-07 22:08:54 +00009157 bool VisitUnaryReal(const UnaryOperator *E);
9158 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009159
Richard Smithfddd3842011-12-30 21:15:51 +00009160 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009161};
9162} // end anonymous namespace
9163
9164static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009165 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009166 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009167}
9168
Jay Foad39c79802011-01-12 09:06:06 +00009169static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009170 QualType ResultTy,
9171 const Expr *Arg,
9172 bool SNaN,
9173 llvm::APFloat &Result) {
9174 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9175 if (!S) return false;
9176
9177 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9178
9179 llvm::APInt fill;
9180
9181 // Treat empty strings as if they were zero.
9182 if (S->getString().empty())
9183 fill = llvm::APInt(32, 0);
9184 else if (S->getString().getAsInteger(0, fill))
9185 return false;
9186
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009187 if (Context.getTargetInfo().isNan2008()) {
9188 if (SNaN)
9189 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9190 else
9191 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9192 } else {
9193 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9194 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9195 // a different encoding to what became a standard in 2008, and for pre-
9196 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9197 // sNaN. This is now known as "legacy NaN" encoding.
9198 if (SNaN)
9199 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9200 else
9201 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9202 }
9203
John McCall16291492010-02-28 13:00:19 +00009204 return true;
9205}
9206
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009207bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009208 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009209 default:
9210 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9211
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009212 case Builtin::BI__builtin_huge_val:
9213 case Builtin::BI__builtin_huge_valf:
9214 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009215 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009216 case Builtin::BI__builtin_inf:
9217 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009218 case Builtin::BI__builtin_infl:
9219 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009220 const llvm::fltSemantics &Sem =
9221 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009222 Result = llvm::APFloat::getInf(Sem);
9223 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009224 }
Mike Stump11289f42009-09-09 15:08:12 +00009225
John McCall16291492010-02-28 13:00:19 +00009226 case Builtin::BI__builtin_nans:
9227 case Builtin::BI__builtin_nansf:
9228 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009229 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009230 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9231 true, Result))
9232 return Error(E);
9233 return true;
John McCall16291492010-02-28 13:00:19 +00009234
Chris Lattner0b7282e2008-10-06 06:31:58 +00009235 case Builtin::BI__builtin_nan:
9236 case Builtin::BI__builtin_nanf:
9237 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009238 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +00009239 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009240 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009241 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9242 false, Result))
9243 return Error(E);
9244 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009245
9246 case Builtin::BI__builtin_fabs:
9247 case Builtin::BI__builtin_fabsf:
9248 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009249 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009250 if (!EvaluateFloat(E->getArg(0), Result, Info))
9251 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009252
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009253 if (Result.isNegative())
9254 Result.changeSign();
9255 return true;
9256
Richard Smith8889a3d2013-06-13 06:26:32 +00009257 // FIXME: Builtin::BI__builtin_powi
9258 // FIXME: Builtin::BI__builtin_powif
9259 // FIXME: Builtin::BI__builtin_powil
9260
Mike Stump11289f42009-09-09 15:08:12 +00009261 case Builtin::BI__builtin_copysign:
9262 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009263 case Builtin::BI__builtin_copysignl:
9264 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009265 APFloat RHS(0.);
9266 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9267 !EvaluateFloat(E->getArg(1), RHS, Info))
9268 return false;
9269 Result.copySign(RHS);
9270 return true;
9271 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009272 }
9273}
9274
John McCallb1fb0d32010-05-07 22:08:54 +00009275bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009276 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9277 ComplexValue CV;
9278 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9279 return false;
9280 Result = CV.FloatReal;
9281 return true;
9282 }
9283
9284 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009285}
9286
9287bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009288 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9289 ComplexValue CV;
9290 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9291 return false;
9292 Result = CV.FloatImag;
9293 return true;
9294 }
9295
Richard Smith4a678122011-10-24 18:44:57 +00009296 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009297 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9298 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009299 return true;
9300}
9301
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009302bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009303 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009304 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009305 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009306 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009307 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009308 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9309 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009310 Result.changeSign();
9311 return true;
9312 }
9313}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009314
Eli Friedman24c01542008-08-22 00:06:13 +00009315bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009316 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9317 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009318
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009319 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009320 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009321 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009322 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009323 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9324 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009325}
9326
9327bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9328 Result = E->getValue();
9329 return true;
9330}
9331
Peter Collingbournee9200682011-05-13 03:29:01 +00009332bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9333 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009334
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009335 switch (E->getCastKind()) {
9336 default:
Richard Smith11562c52011-10-28 17:51:58 +00009337 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009338
9339 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009340 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009341 return EvaluateInteger(SubExpr, IntResult, Info) &&
9342 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9343 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009344 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009345
9346 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009347 if (!Visit(SubExpr))
9348 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009349 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9350 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009351 }
John McCalld7646252010-11-14 08:17:51 +00009352
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009353 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009354 ComplexValue V;
9355 if (!EvaluateComplex(SubExpr, V, Info))
9356 return false;
9357 Result = V.getComplexFloatReal();
9358 return true;
9359 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009360 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009361}
9362
Eli Friedman24c01542008-08-22 00:06:13 +00009363//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009364// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009365//===----------------------------------------------------------------------===//
9366
9367namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009368class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009369 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009370 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009371
Anders Carlsson537969c2008-11-16 20:27:53 +00009372public:
John McCall93d91dc2010-05-07 17:22:02 +00009373 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009374 : ExprEvaluatorBaseTy(info), Result(Result) {}
9375
Richard Smith2e312c82012-03-03 22:46:17 +00009376 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009377 Result.setFrom(V);
9378 return true;
9379 }
Mike Stump11289f42009-09-09 15:08:12 +00009380
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009381 bool ZeroInitialization(const Expr *E);
9382
Anders Carlsson537969c2008-11-16 20:27:53 +00009383 //===--------------------------------------------------------------------===//
9384 // Visitor Methods
9385 //===--------------------------------------------------------------------===//
9386
Peter Collingbournee9200682011-05-13 03:29:01 +00009387 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009388 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009389 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009390 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009391 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009392};
9393} // end anonymous namespace
9394
John McCall93d91dc2010-05-07 17:22:02 +00009395static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9396 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009397 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009398 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009399}
9400
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009401bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009402 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009403 if (ElemTy->isRealFloatingType()) {
9404 Result.makeComplexFloat();
9405 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9406 Result.FloatReal = Zero;
9407 Result.FloatImag = Zero;
9408 } else {
9409 Result.makeComplexInt();
9410 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9411 Result.IntReal = Zero;
9412 Result.IntImag = Zero;
9413 }
9414 return true;
9415}
9416
Peter Collingbournee9200682011-05-13 03:29:01 +00009417bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9418 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009419
9420 if (SubExpr->getType()->isRealFloatingType()) {
9421 Result.makeComplexFloat();
9422 APFloat &Imag = Result.FloatImag;
9423 if (!EvaluateFloat(SubExpr, Imag, Info))
9424 return false;
9425
9426 Result.FloatReal = APFloat(Imag.getSemantics());
9427 return true;
9428 } else {
9429 assert(SubExpr->getType()->isIntegerType() &&
9430 "Unexpected imaginary literal.");
9431
9432 Result.makeComplexInt();
9433 APSInt &Imag = Result.IntImag;
9434 if (!EvaluateInteger(SubExpr, Imag, Info))
9435 return false;
9436
9437 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9438 return true;
9439 }
9440}
9441
Peter Collingbournee9200682011-05-13 03:29:01 +00009442bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009443
John McCallfcef3cf2010-12-14 17:51:41 +00009444 switch (E->getCastKind()) {
9445 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009446 case CK_BaseToDerived:
9447 case CK_DerivedToBase:
9448 case CK_UncheckedDerivedToBase:
9449 case CK_Dynamic:
9450 case CK_ToUnion:
9451 case CK_ArrayToPointerDecay:
9452 case CK_FunctionToPointerDecay:
9453 case CK_NullToPointer:
9454 case CK_NullToMemberPointer:
9455 case CK_BaseToDerivedMemberPointer:
9456 case CK_DerivedToBaseMemberPointer:
9457 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009458 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009459 case CK_ConstructorConversion:
9460 case CK_IntegralToPointer:
9461 case CK_PointerToIntegral:
9462 case CK_PointerToBoolean:
9463 case CK_ToVoid:
9464 case CK_VectorSplat:
9465 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009466 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009467 case CK_IntegralToBoolean:
9468 case CK_IntegralToFloating:
9469 case CK_FloatingToIntegral:
9470 case CK_FloatingToBoolean:
9471 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009472 case CK_CPointerToObjCPointerCast:
9473 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009474 case CK_AnyPointerToBlockPointerCast:
9475 case CK_ObjCObjectLValueCast:
9476 case CK_FloatingComplexToReal:
9477 case CK_FloatingComplexToBoolean:
9478 case CK_IntegralComplexToReal:
9479 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009480 case CK_ARCProduceObject:
9481 case CK_ARCConsumeObject:
9482 case CK_ARCReclaimReturnedObject:
9483 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009484 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009485 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009486 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009487 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009488 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009489 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009490 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009491 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009492
John McCallfcef3cf2010-12-14 17:51:41 +00009493 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009494 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009495 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009496 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009497
9498 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009499 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009500 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009501 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009502
9503 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009504 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009505 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009506 return false;
9507
John McCallfcef3cf2010-12-14 17:51:41 +00009508 Result.makeComplexFloat();
9509 Result.FloatImag = APFloat(Real.getSemantics());
9510 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009511 }
9512
John McCallfcef3cf2010-12-14 17:51:41 +00009513 case CK_FloatingComplexCast: {
9514 if (!Visit(E->getSubExpr()))
9515 return false;
9516
9517 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9518 QualType From
9519 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9520
Richard Smith357362d2011-12-13 06:39:58 +00009521 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9522 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009523 }
9524
9525 case CK_FloatingComplexToIntegralComplex: {
9526 if (!Visit(E->getSubExpr()))
9527 return false;
9528
9529 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9530 QualType From
9531 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9532 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009533 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9534 To, Result.IntReal) &&
9535 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9536 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009537 }
9538
9539 case CK_IntegralRealToComplex: {
9540 APSInt &Real = Result.IntReal;
9541 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9542 return false;
9543
9544 Result.makeComplexInt();
9545 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9546 return true;
9547 }
9548
9549 case CK_IntegralComplexCast: {
9550 if (!Visit(E->getSubExpr()))
9551 return false;
9552
9553 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9554 QualType From
9555 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9556
Richard Smith911e1422012-01-30 22:27:01 +00009557 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9558 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009559 return true;
9560 }
9561
9562 case CK_IntegralComplexToFloatingComplex: {
9563 if (!Visit(E->getSubExpr()))
9564 return false;
9565
Ted Kremenek28831752012-08-23 20:46:57 +00009566 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009567 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009568 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009569 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009570 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9571 To, Result.FloatReal) &&
9572 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9573 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009574 }
9575 }
9576
9577 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009578}
9579
John McCall93d91dc2010-05-07 17:22:02 +00009580bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009581 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009582 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9583
Chandler Carrutha216cad2014-10-11 00:57:18 +00009584 // Track whether the LHS or RHS is real at the type system level. When this is
9585 // the case we can simplify our evaluation strategy.
9586 bool LHSReal = false, RHSReal = false;
9587
9588 bool LHSOK;
9589 if (E->getLHS()->getType()->isRealFloatingType()) {
9590 LHSReal = true;
9591 APFloat &Real = Result.FloatReal;
9592 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9593 if (LHSOK) {
9594 Result.makeComplexFloat();
9595 Result.FloatImag = APFloat(Real.getSemantics());
9596 }
9597 } else {
9598 LHSOK = Visit(E->getLHS());
9599 }
George Burgess IVa145e252016-05-25 22:38:36 +00009600 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009601 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009602
John McCall93d91dc2010-05-07 17:22:02 +00009603 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009604 if (E->getRHS()->getType()->isRealFloatingType()) {
9605 RHSReal = true;
9606 APFloat &Real = RHS.FloatReal;
9607 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9608 return false;
9609 RHS.makeComplexFloat();
9610 RHS.FloatImag = APFloat(Real.getSemantics());
9611 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009612 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009613
Chandler Carrutha216cad2014-10-11 00:57:18 +00009614 assert(!(LHSReal && RHSReal) &&
9615 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009616 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009617 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009618 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009619 if (Result.isComplexFloat()) {
9620 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9621 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009622 if (LHSReal)
9623 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9624 else if (!RHSReal)
9625 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9626 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009627 } else {
9628 Result.getComplexIntReal() += RHS.getComplexIntReal();
9629 Result.getComplexIntImag() += RHS.getComplexIntImag();
9630 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009631 break;
John McCalle3027922010-08-25 11:45:40 +00009632 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009633 if (Result.isComplexFloat()) {
9634 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9635 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009636 if (LHSReal) {
9637 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9638 Result.getComplexFloatImag().changeSign();
9639 } else if (!RHSReal) {
9640 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9641 APFloat::rmNearestTiesToEven);
9642 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009643 } else {
9644 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9645 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9646 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009647 break;
John McCalle3027922010-08-25 11:45:40 +00009648 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009649 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009650 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009651 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009652 // following naming scheme:
9653 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009654 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009655 APFloat &A = LHS.getComplexFloatReal();
9656 APFloat &B = LHS.getComplexFloatImag();
9657 APFloat &C = RHS.getComplexFloatReal();
9658 APFloat &D = RHS.getComplexFloatImag();
9659 APFloat &ResR = Result.getComplexFloatReal();
9660 APFloat &ResI = Result.getComplexFloatImag();
9661 if (LHSReal) {
9662 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9663 ResR = A * C;
9664 ResI = A * D;
9665 } else if (RHSReal) {
9666 ResR = C * A;
9667 ResI = C * B;
9668 } else {
9669 // In the fully general case, we need to handle NaNs and infinities
9670 // robustly.
9671 APFloat AC = A * C;
9672 APFloat BD = B * D;
9673 APFloat AD = A * D;
9674 APFloat BC = B * C;
9675 ResR = AC - BD;
9676 ResI = AD + BC;
9677 if (ResR.isNaN() && ResI.isNaN()) {
9678 bool Recalc = false;
9679 if (A.isInfinity() || B.isInfinity()) {
9680 A = APFloat::copySign(
9681 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9682 B = APFloat::copySign(
9683 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9684 if (C.isNaN())
9685 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9686 if (D.isNaN())
9687 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9688 Recalc = true;
9689 }
9690 if (C.isInfinity() || D.isInfinity()) {
9691 C = APFloat::copySign(
9692 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9693 D = APFloat::copySign(
9694 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9695 if (A.isNaN())
9696 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9697 if (B.isNaN())
9698 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9699 Recalc = true;
9700 }
9701 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9702 AD.isInfinity() || BC.isInfinity())) {
9703 if (A.isNaN())
9704 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9705 if (B.isNaN())
9706 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9707 if (C.isNaN())
9708 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9709 if (D.isNaN())
9710 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9711 Recalc = true;
9712 }
9713 if (Recalc) {
9714 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9715 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9716 }
9717 }
9718 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009719 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009720 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009721 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009722 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9723 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009724 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009725 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9726 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9727 }
9728 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009729 case BO_Div:
9730 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009731 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009732 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009733 // following naming scheme:
9734 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009735 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009736 APFloat &A = LHS.getComplexFloatReal();
9737 APFloat &B = LHS.getComplexFloatImag();
9738 APFloat &C = RHS.getComplexFloatReal();
9739 APFloat &D = RHS.getComplexFloatImag();
9740 APFloat &ResR = Result.getComplexFloatReal();
9741 APFloat &ResI = Result.getComplexFloatImag();
9742 if (RHSReal) {
9743 ResR = A / C;
9744 ResI = B / C;
9745 } else {
9746 if (LHSReal) {
9747 // No real optimizations we can do here, stub out with zero.
9748 B = APFloat::getZero(A.getSemantics());
9749 }
9750 int DenomLogB = 0;
9751 APFloat MaxCD = maxnum(abs(C), abs(D));
9752 if (MaxCD.isFinite()) {
9753 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009754 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9755 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009756 }
9757 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009758 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9759 APFloat::rmNearestTiesToEven);
9760 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9761 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009762 if (ResR.isNaN() && ResI.isNaN()) {
9763 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9764 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9765 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9766 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9767 D.isFinite()) {
9768 A = APFloat::copySign(
9769 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9770 B = APFloat::copySign(
9771 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9772 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9773 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9774 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9775 C = APFloat::copySign(
9776 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9777 D = APFloat::copySign(
9778 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9779 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9780 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9781 }
9782 }
9783 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009784 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009785 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9786 return Error(E, diag::note_expr_divide_by_zero);
9787
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009788 ComplexValue LHS = Result;
9789 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9790 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9791 Result.getComplexIntReal() =
9792 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9793 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9794 Result.getComplexIntImag() =
9795 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9796 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9797 }
9798 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009799 }
9800
John McCall93d91dc2010-05-07 17:22:02 +00009801 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009802}
9803
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009804bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9805 // Get the operand value into 'Result'.
9806 if (!Visit(E->getSubExpr()))
9807 return false;
9808
9809 switch (E->getOpcode()) {
9810 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009811 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009812 case UO_Extension:
9813 return true;
9814 case UO_Plus:
9815 // The result is always just the subexpr.
9816 return true;
9817 case UO_Minus:
9818 if (Result.isComplexFloat()) {
9819 Result.getComplexFloatReal().changeSign();
9820 Result.getComplexFloatImag().changeSign();
9821 }
9822 else {
9823 Result.getComplexIntReal() = -Result.getComplexIntReal();
9824 Result.getComplexIntImag() = -Result.getComplexIntImag();
9825 }
9826 return true;
9827 case UO_Not:
9828 if (Result.isComplexFloat())
9829 Result.getComplexFloatImag().changeSign();
9830 else
9831 Result.getComplexIntImag() = -Result.getComplexIntImag();
9832 return true;
9833 }
9834}
9835
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009836bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9837 if (E->getNumInits() == 2) {
9838 if (E->getType()->isComplexType()) {
9839 Result.makeComplexFloat();
9840 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9841 return false;
9842 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9843 return false;
9844 } else {
9845 Result.makeComplexInt();
9846 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9847 return false;
9848 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9849 return false;
9850 }
9851 return true;
9852 }
9853 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9854}
9855
Anders Carlsson537969c2008-11-16 20:27:53 +00009856//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009857// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9858// implicit conversion.
9859//===----------------------------------------------------------------------===//
9860
9861namespace {
9862class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009863 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009864 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009865 APValue &Result;
9866public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009867 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9868 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009869
9870 bool Success(const APValue &V, const Expr *E) {
9871 Result = V;
9872 return true;
9873 }
9874
9875 bool ZeroInitialization(const Expr *E) {
9876 ImplicitValueInitExpr VIE(
9877 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009878 // For atomic-qualified class (and array) types in C++, initialize the
9879 // _Atomic-wrapped subobject directly, in-place.
9880 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9881 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009882 }
9883
9884 bool VisitCastExpr(const CastExpr *E) {
9885 switch (E->getCastKind()) {
9886 default:
9887 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9888 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009889 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9890 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009891 }
9892 }
9893};
9894} // end anonymous namespace
9895
Richard Smith64cb9ca2017-02-22 22:09:50 +00009896static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9897 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009898 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009899 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009900}
9901
9902//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009903// Void expression evaluation, primarily for a cast to void on the LHS of a
9904// comma operator
9905//===----------------------------------------------------------------------===//
9906
9907namespace {
9908class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009909 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009910public:
9911 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9912
Richard Smith2e312c82012-03-03 22:46:17 +00009913 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009914
Richard Smith7cd577b2017-08-17 19:35:50 +00009915 bool ZeroInitialization(const Expr *E) { return true; }
9916
Richard Smith42d3af92011-12-07 00:43:50 +00009917 bool VisitCastExpr(const CastExpr *E) {
9918 switch (E->getCastKind()) {
9919 default:
9920 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9921 case CK_ToVoid:
9922 VisitIgnoredValue(E->getSubExpr());
9923 return true;
9924 }
9925 }
Hal Finkela8443c32014-07-17 14:49:58 +00009926
9927 bool VisitCallExpr(const CallExpr *E) {
9928 switch (E->getBuiltinCallee()) {
9929 default:
9930 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9931 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009932 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009933 // The argument is not evaluated!
9934 return true;
9935 }
9936 }
Richard Smith42d3af92011-12-07 00:43:50 +00009937};
9938} // end anonymous namespace
9939
9940static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9941 assert(E->isRValue() && E->getType()->isVoidType());
9942 return VoidExprEvaluator(Info).Visit(E);
9943}
9944
9945//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009946// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009947//===----------------------------------------------------------------------===//
9948
Richard Smith2e312c82012-03-03 22:46:17 +00009949static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009950 // In C, function designators are not lvalues, but we evaluate them as if they
9951 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009952 QualType T = E->getType();
9953 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009954 LValue LV;
9955 if (!EvaluateLValue(E, LV, Info))
9956 return false;
9957 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009958 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009959 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009960 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009961 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009962 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009963 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009964 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009965 LValue LV;
9966 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009967 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009968 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009969 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009970 llvm::APFloat F(0.0);
9971 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009972 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009973 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009974 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009975 ComplexValue C;
9976 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009977 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009978 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009979 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009980 MemberPtr P;
9981 if (!EvaluateMemberPointer(E, P, Info))
9982 return false;
9983 P.moveInto(Result);
9984 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009985 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009986 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009987 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009988 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9989 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009990 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009991 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009992 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009993 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009994 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009995 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9996 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009997 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009998 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009999 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010000 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010001 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000010002 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000010003 if (!EvaluateVoid(E, Info))
10004 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010005 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010006 QualType Unqual = T.getAtomicUnqualifiedType();
10007 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10008 LValue LV;
10009 LV.set(E, Info.CurrentCall->Index);
10010 APValue &Value = Info.CurrentCall->createTemporary(E, false);
10011 if (!EvaluateAtomic(E, &LV, Value, Info))
10012 return false;
10013 } else {
10014 if (!EvaluateAtomic(E, nullptr, Result, Info))
10015 return false;
10016 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010017 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010018 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010019 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010020 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010021 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010022 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010023 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010024
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010025 return true;
10026}
10027
Richard Smithb228a862012-02-15 02:18:13 +000010028/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10029/// cases, the in-place evaluation is essential, since later initializers for
10030/// an object can indirectly refer to subobjects which were initialized earlier.
10031static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010032 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010033 assert(!E->isValueDependent());
10034
Richard Smith7525ff62013-05-09 07:14:00 +000010035 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010036 return false;
10037
10038 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010039 // Evaluate arrays and record types in-place, so that later initializers can
10040 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010041 QualType T = E->getType();
10042 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010043 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010044 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010045 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010046 else if (T->isAtomicType()) {
10047 QualType Unqual = T.getAtomicUnqualifiedType();
10048 if (Unqual->isArrayType() || Unqual->isRecordType())
10049 return EvaluateAtomic(E, &This, Result, Info);
10050 }
Richard Smithed5165f2011-11-04 05:33:44 +000010051 }
10052
10053 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010054 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010055}
10056
Richard Smithf57d8cb2011-12-09 22:58:01 +000010057/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10058/// lvalue-to-rvalue cast if it is an lvalue.
10059static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010060 if (E->getType().isNull())
10061 return false;
10062
Nick Lewyckyc190f962017-05-02 01:06:16 +000010063 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010064 return false;
10065
Richard Smith2e312c82012-03-03 22:46:17 +000010066 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010067 return false;
10068
10069 if (E->isGLValue()) {
10070 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010071 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010072 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010073 return false;
10074 }
10075
Richard Smith2e312c82012-03-03 22:46:17 +000010076 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010077 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010078}
Richard Smith11562c52011-10-28 17:51:58 +000010079
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010080static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010081 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010082 // Fast-path evaluations of integer literals, since we sometimes see files
10083 // containing vast quantities of these.
10084 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10085 Result.Val = APValue(APSInt(L->getValue(),
10086 L->getType()->isUnsignedIntegerType()));
10087 IsConst = true;
10088 return true;
10089 }
James Dennett0492ef02014-03-14 17:44:10 +000010090
10091 // This case should be rare, but we need to check it before we check on
10092 // the type below.
10093 if (Exp->getType().isNull()) {
10094 IsConst = false;
10095 return true;
10096 }
Daniel Jasperffdee092017-05-02 19:21:42 +000010097
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010098 // FIXME: Evaluating values of large array and record types can cause
10099 // performance problems. Only do so in C++11 for now.
10100 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10101 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010102 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010103 IsConst = false;
10104 return true;
10105 }
10106 return false;
10107}
10108
10109
Richard Smith7b553f12011-10-29 00:50:52 +000010110/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010111/// any crazy technique (that has nothing to do with language standards) that
10112/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010113/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10114/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010115bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010116 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010117 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010118 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +000010119
Richard Smith6d4c6582013-11-05 22:18:15 +000010120 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010121 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010122}
10123
Jay Foad39c79802011-01-12 09:06:06 +000010124bool Expr::EvaluateAsBooleanCondition(bool &Result,
10125 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010126 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010127 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010128 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010129}
10130
Richard Smithce8eca52015-12-08 03:21:47 +000010131static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10132 Expr::SideEffectsKind SEK) {
10133 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10134 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10135}
10136
Richard Smith5fab0c92011-12-28 19:48:30 +000010137bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10138 SideEffectsKind AllowSideEffects) const {
10139 if (!getType()->isIntegralOrEnumerationType())
10140 return false;
10141
Richard Smith11562c52011-10-28 17:51:58 +000010142 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010143 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010144 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010145 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010146
Richard Smith11562c52011-10-28 17:51:58 +000010147 Result = ExprResult.Val.getInt();
10148 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010149}
10150
Richard Trieube234c32016-04-21 21:04:55 +000010151bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10152 SideEffectsKind AllowSideEffects) const {
10153 if (!getType()->isRealFloatingType())
10154 return false;
10155
10156 EvalResult ExprResult;
10157 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10158 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10159 return false;
10160
10161 Result = ExprResult.Val.getFloat();
10162 return true;
10163}
10164
Jay Foad39c79802011-01-12 09:06:06 +000010165bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010166 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010167
John McCall45d55e42010-05-07 21:00:08 +000010168 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010169 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10170 !CheckLValueConstantExpression(Info, getExprLoc(),
10171 Ctx.getLValueReferenceType(getType()), LV))
10172 return false;
10173
Richard Smith2e312c82012-03-03 22:46:17 +000010174 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010175 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010176}
10177
Richard Smithd0b4dd62011-12-19 06:19:21 +000010178bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10179 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010180 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010181 // FIXME: Evaluating initializers for large array and record types can cause
10182 // performance problems. Only do so in C++11 for now.
10183 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010184 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010185 return false;
10186
Richard Smithd0b4dd62011-12-19 06:19:21 +000010187 Expr::EvalStatus EStatus;
10188 EStatus.Diag = &Notes;
10189
Richard Smith0c6124b2015-12-03 01:36:22 +000010190 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10191 ? EvalInfo::EM_ConstantExpression
10192 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010193 InitInfo.setEvaluatingDecl(VD, Value);
10194
10195 LValue LVal;
10196 LVal.set(VD);
10197
Richard Smithfddd3842011-12-30 21:15:51 +000010198 // C++11 [basic.start.init]p2:
10199 // Variables with static storage duration or thread storage duration shall be
10200 // zero-initialized before any other initialization takes place.
10201 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010202 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010203 !VD->getType()->isReferenceType()) {
10204 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010205 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010206 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010207 return false;
10208 }
10209
Richard Smith7525ff62013-05-09 07:14:00 +000010210 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10211 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010212 EStatus.HasSideEffects)
10213 return false;
10214
10215 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10216 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010217}
10218
Richard Smith7b553f12011-10-29 00:50:52 +000010219/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10220/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010221bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010222 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010223 return EvaluateAsRValue(Result, Ctx) &&
10224 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010225}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010226
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010227APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010228 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010229 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010230 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010231 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010232 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010233 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010234 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010235
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010236 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010237}
John McCall864e3962010-05-07 05:32:02 +000010238
Richard Smithe9ff7702013-11-05 22:23:30 +000010239void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010240 bool IsConst;
10241 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010242 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010243 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010244 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10245 }
10246}
10247
Richard Smithe6c01442013-06-05 00:46:14 +000010248bool Expr::EvalResult::isGlobalLValue() const {
10249 assert(Val.isLValue());
10250 return IsGlobalLValue(Val.getLValueBase());
10251}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010252
10253
John McCall864e3962010-05-07 05:32:02 +000010254/// isIntegerConstantExpr - this recursive routine will test if an expression is
10255/// an integer constant expression.
10256
10257/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10258/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010259
10260// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010261// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10262// and a (possibly null) SourceLocation indicating the location of the problem.
10263//
John McCall864e3962010-05-07 05:32:02 +000010264// Note that to reduce code duplication, this helper does no evaluation
10265// itself; the caller checks whether the expression is evaluatable, and
10266// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010267// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010268
Dan Gohman28ade552010-07-26 21:25:24 +000010269namespace {
10270
Richard Smith9e575da2012-12-28 13:25:52 +000010271enum ICEKind {
10272 /// This expression is an ICE.
10273 IK_ICE,
10274 /// This expression is not an ICE, but if it isn't evaluated, it's
10275 /// a legal subexpression for an ICE. This return value is used to handle
10276 /// the comma operator in C99 mode, and non-constant subexpressions.
10277 IK_ICEIfUnevaluated,
10278 /// This expression is not an ICE, and is not a legal subexpression for one.
10279 IK_NotICE
10280};
10281
John McCall864e3962010-05-07 05:32:02 +000010282struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010283 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010284 SourceLocation Loc;
10285
Richard Smith9e575da2012-12-28 13:25:52 +000010286 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010287};
10288
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010289}
Dan Gohman28ade552010-07-26 21:25:24 +000010290
Richard Smith9e575da2012-12-28 13:25:52 +000010291static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10292
10293static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010294
Craig Toppera31a8822013-08-22 07:09:37 +000010295static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010296 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010297 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010298 !EVResult.Val.isInt())
10299 return ICEDiag(IK_NotICE, E->getLocStart());
10300
John McCall864e3962010-05-07 05:32:02 +000010301 return NoDiag();
10302}
10303
Craig Toppera31a8822013-08-22 07:09:37 +000010304static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010305 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010306 if (!E->getType()->isIntegralOrEnumerationType())
10307 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010308
10309 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010310#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010311#define STMT(Node, Base) case Expr::Node##Class:
10312#define EXPR(Node, Base)
10313#include "clang/AST/StmtNodes.inc"
10314 case Expr::PredefinedExprClass:
10315 case Expr::FloatingLiteralClass:
10316 case Expr::ImaginaryLiteralClass:
10317 case Expr::StringLiteralClass:
10318 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010319 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010320 case Expr::MemberExprClass:
10321 case Expr::CompoundAssignOperatorClass:
10322 case Expr::CompoundLiteralExprClass:
10323 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010324 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010325 case Expr::ArrayInitLoopExprClass:
10326 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010327 case Expr::NoInitExprClass:
10328 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010329 case Expr::ImplicitValueInitExprClass:
10330 case Expr::ParenListExprClass:
10331 case Expr::VAArgExprClass:
10332 case Expr::AddrLabelExprClass:
10333 case Expr::StmtExprClass:
10334 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010335 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010336 case Expr::CXXDynamicCastExprClass:
10337 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010338 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010339 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010340 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010341 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010342 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010343 case Expr::CXXThisExprClass:
10344 case Expr::CXXThrowExprClass:
10345 case Expr::CXXNewExprClass:
10346 case Expr::CXXDeleteExprClass:
10347 case Expr::CXXPseudoDestructorExprClass:
10348 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010349 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010350 case Expr::DependentScopeDeclRefExprClass:
10351 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010352 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010353 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010354 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010355 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010356 case Expr::CXXTemporaryObjectExprClass:
10357 case Expr::CXXUnresolvedConstructExprClass:
10358 case Expr::CXXDependentScopeMemberExprClass:
10359 case Expr::UnresolvedMemberExprClass:
10360 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010361 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010362 case Expr::ObjCArrayLiteralClass:
10363 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010364 case Expr::ObjCEncodeExprClass:
10365 case Expr::ObjCMessageExprClass:
10366 case Expr::ObjCSelectorExprClass:
10367 case Expr::ObjCProtocolExprClass:
10368 case Expr::ObjCIvarRefExprClass:
10369 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010370 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010371 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010372 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010373 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010374 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010375 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010376 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010377 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010378 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010379 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010380 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010381 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010382 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010383 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010384 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010385 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010386 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010387 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010388 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010389 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010390 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010391 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010392
Richard Smithf137f932014-01-25 20:50:08 +000010393 case Expr::InitListExprClass: {
10394 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10395 // form "T x = { a };" is equivalent to "T x = a;".
10396 // Unless we're initializing a reference, T is a scalar as it is known to be
10397 // of integral or enumeration type.
10398 if (E->isRValue())
10399 if (cast<InitListExpr>(E)->getNumInits() == 1)
10400 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10401 return ICEDiag(IK_NotICE, E->getLocStart());
10402 }
10403
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010404 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010405 case Expr::GNUNullExprClass:
10406 // GCC considers the GNU __null value to be an integral constant expression.
10407 return NoDiag();
10408
John McCall7c454bb2011-07-15 05:09:51 +000010409 case Expr::SubstNonTypeTemplateParmExprClass:
10410 return
10411 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10412
John McCall864e3962010-05-07 05:32:02 +000010413 case Expr::ParenExprClass:
10414 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010415 case Expr::GenericSelectionExprClass:
10416 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010417 case Expr::IntegerLiteralClass:
10418 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010419 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010420 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010421 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010422 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010423 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010424 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010425 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010426 return NoDiag();
10427 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010428 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010429 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10430 // constant expressions, but they can never be ICEs because an ICE cannot
10431 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010432 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010433 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010434 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010435 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010436 }
Richard Smith6365c912012-02-24 22:12:32 +000010437 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010438 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10439 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000010440 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010441 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010442 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010443 // Parameter variables are never constants. Without this check,
10444 // getAnyInitializer() can find a default argument, which leads
10445 // to chaos.
10446 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010447 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010448
10449 // C++ 7.1.5.1p2
10450 // A variable of non-volatile const-qualified integral or enumeration
10451 // type initialized by an ICE can be used in ICEs.
10452 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010453 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010454 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010455
Richard Smithd0b4dd62011-12-19 06:19:21 +000010456 const VarDecl *VD;
10457 // Look for a declaration of this variable that has an initializer, and
10458 // check whether it is an ICE.
10459 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10460 return NoDiag();
10461 else
Richard Smith9e575da2012-12-28 13:25:52 +000010462 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010463 }
10464 }
Richard Smith9e575da2012-12-28 13:25:52 +000010465 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010466 }
John McCall864e3962010-05-07 05:32:02 +000010467 case Expr::UnaryOperatorClass: {
10468 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10469 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010470 case UO_PostInc:
10471 case UO_PostDec:
10472 case UO_PreInc:
10473 case UO_PreDec:
10474 case UO_AddrOf:
10475 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010476 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010477 // C99 6.6/3 allows increment and decrement within unevaluated
10478 // subexpressions of constant expressions, but they can never be ICEs
10479 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010480 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010481 case UO_Extension:
10482 case UO_LNot:
10483 case UO_Plus:
10484 case UO_Minus:
10485 case UO_Not:
10486 case UO_Real:
10487 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010488 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010489 }
Richard Smith9e575da2012-12-28 13:25:52 +000010490
John McCall864e3962010-05-07 05:32:02 +000010491 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010492 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010493 }
10494 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010495 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10496 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10497 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10498 // compliance: we should warn earlier for offsetof expressions with
10499 // array subscripts that aren't ICEs, and if the array subscripts
10500 // are ICEs, the value of the offsetof must be an integer constant.
10501 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010502 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010503 case Expr::UnaryExprOrTypeTraitExprClass: {
10504 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10505 if ((Exp->getKind() == UETT_SizeOf) &&
10506 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010507 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010508 return NoDiag();
10509 }
10510 case Expr::BinaryOperatorClass: {
10511 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10512 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010513 case BO_PtrMemD:
10514 case BO_PtrMemI:
10515 case BO_Assign:
10516 case BO_MulAssign:
10517 case BO_DivAssign:
10518 case BO_RemAssign:
10519 case BO_AddAssign:
10520 case BO_SubAssign:
10521 case BO_ShlAssign:
10522 case BO_ShrAssign:
10523 case BO_AndAssign:
10524 case BO_XorAssign:
10525 case BO_OrAssign:
Richard Smithc70f1d62017-12-14 15:16:18 +000010526 case BO_Cmp: // FIXME: Re-enable once we can evaluate this.
Richard Smith62f65952011-10-24 22:35:48 +000010527 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10528 // constant expressions, but they can never be ICEs because an ICE cannot
10529 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010530 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010531
John McCalle3027922010-08-25 11:45:40 +000010532 case BO_Mul:
10533 case BO_Div:
10534 case BO_Rem:
10535 case BO_Add:
10536 case BO_Sub:
10537 case BO_Shl:
10538 case BO_Shr:
10539 case BO_LT:
10540 case BO_GT:
10541 case BO_LE:
10542 case BO_GE:
10543 case BO_EQ:
10544 case BO_NE:
10545 case BO_And:
10546 case BO_Xor:
10547 case BO_Or:
10548 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010549 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10550 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010551 if (Exp->getOpcode() == BO_Div ||
10552 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010553 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010554 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010555 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010556 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010557 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010558 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010559 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010560 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010561 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010562 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010563 }
10564 }
10565 }
John McCalle3027922010-08-25 11:45:40 +000010566 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010567 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010568 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10569 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010570 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10571 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010572 } else {
10573 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010574 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010575 }
10576 }
Richard Smith9e575da2012-12-28 13:25:52 +000010577 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010578 }
John McCalle3027922010-08-25 11:45:40 +000010579 case BO_LAnd:
10580 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010581 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10582 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010583 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010584 // Rare case where the RHS has a comma "side-effect"; we need
10585 // to actually check the condition to see whether the side
10586 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010587 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010588 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010589 return RHSResult;
10590 return NoDiag();
10591 }
10592
Richard Smith9e575da2012-12-28 13:25:52 +000010593 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010594 }
10595 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010596 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010597 }
10598 case Expr::ImplicitCastExprClass:
10599 case Expr::CStyleCastExprClass:
10600 case Expr::CXXFunctionalCastExprClass:
10601 case Expr::CXXStaticCastExprClass:
10602 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010603 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010604 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010605 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010606 if (isa<ExplicitCastExpr>(E)) {
10607 if (const FloatingLiteral *FL
10608 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10609 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10610 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10611 APSInt IgnoredVal(DestWidth, !DestSigned);
10612 bool Ignored;
10613 // If the value does not fit in the destination type, the behavior is
10614 // undefined, so we are not required to treat it as a constant
10615 // expression.
10616 if (FL->getValue().convertToInteger(IgnoredVal,
10617 llvm::APFloat::rmTowardZero,
10618 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010619 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010620 return NoDiag();
10621 }
10622 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010623 switch (cast<CastExpr>(E)->getCastKind()) {
10624 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010625 case CK_AtomicToNonAtomic:
10626 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010627 case CK_NoOp:
10628 case CK_IntegralToBoolean:
10629 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010630 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010631 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010632 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010633 }
John McCall864e3962010-05-07 05:32:02 +000010634 }
John McCallc07a0c72011-02-17 10:25:35 +000010635 case Expr::BinaryConditionalOperatorClass: {
10636 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10637 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010638 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010639 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010640 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10641 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10642 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010643 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010644 return FalseResult;
10645 }
John McCall864e3962010-05-07 05:32:02 +000010646 case Expr::ConditionalOperatorClass: {
10647 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10648 // If the condition (ignoring parens) is a __builtin_constant_p call,
10649 // then only the true side is actually considered in an integer constant
10650 // expression, and it is fully evaluated. This is an important GNU
10651 // extension. See GCC PR38377 for discussion.
10652 if (const CallExpr *CallCE
10653 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010654 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010655 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010656 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010657 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010658 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010659
Richard Smithf57d8cb2011-12-09 22:58:01 +000010660 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10661 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010662
Richard Smith9e575da2012-12-28 13:25:52 +000010663 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010664 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010665 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010666 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010667 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010668 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010669 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010670 return NoDiag();
10671 // Rare case where the diagnostics depend on which side is evaluated
10672 // Note that if we get here, CondResult is 0, and at least one of
10673 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010674 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010675 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010676 return TrueResult;
10677 }
10678 case Expr::CXXDefaultArgExprClass:
10679 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010680 case Expr::CXXDefaultInitExprClass:
10681 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010682 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010683 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010684 }
10685 }
10686
David Blaikiee4d798f2012-01-20 21:50:17 +000010687 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010688}
10689
Richard Smithf57d8cb2011-12-09 22:58:01 +000010690/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010691static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010692 const Expr *E,
10693 llvm::APSInt *Value,
10694 SourceLocation *Loc) {
10695 if (!E->getType()->isIntegralOrEnumerationType()) {
10696 if (Loc) *Loc = E->getExprLoc();
10697 return false;
10698 }
10699
Richard Smith66e05fe2012-01-18 05:21:49 +000010700 APValue Result;
10701 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010702 return false;
10703
Richard Smith98710fc2014-11-13 23:03:19 +000010704 if (!Result.isInt()) {
10705 if (Loc) *Loc = E->getExprLoc();
10706 return false;
10707 }
10708
Richard Smith66e05fe2012-01-18 05:21:49 +000010709 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010710 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010711}
10712
Craig Toppera31a8822013-08-22 07:09:37 +000010713bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10714 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010715 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010716 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010717
Richard Smith9e575da2012-12-28 13:25:52 +000010718 ICEDiag D = CheckICE(this, Ctx);
10719 if (D.Kind != IK_ICE) {
10720 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010721 return false;
10722 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010723 return true;
10724}
10725
Craig Toppera31a8822013-08-22 07:09:37 +000010726bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010727 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010728 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010729 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10730
10731 if (!isIntegerConstantExpr(Ctx, Loc))
10732 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010733 // The only possible side-effects here are due to UB discovered in the
10734 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10735 // required to treat the expression as an ICE, so we produce the folded
10736 // value.
10737 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010738 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010739 return true;
10740}
Richard Smith66e05fe2012-01-18 05:21:49 +000010741
Craig Toppera31a8822013-08-22 07:09:37 +000010742bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010743 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010744}
10745
Craig Toppera31a8822013-08-22 07:09:37 +000010746bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010747 SourceLocation *Loc) const {
10748 // We support this checking in C++98 mode in order to diagnose compatibility
10749 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010750 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010751
Richard Smith98a0a492012-02-14 21:38:30 +000010752 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010753 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010754 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010755 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010756 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010757
10758 APValue Scratch;
10759 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10760
10761 if (!Diags.empty()) {
10762 IsConstExpr = false;
10763 if (Loc) *Loc = Diags[0].first;
10764 } else if (!IsConstExpr) {
10765 // FIXME: This shouldn't happen.
10766 if (Loc) *Loc = getExprLoc();
10767 }
10768
10769 return IsConstExpr;
10770}
Richard Smith253c2a32012-01-27 01:14:48 +000010771
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010772bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10773 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010774 ArrayRef<const Expr*> Args,
10775 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010776 Expr::EvalStatus Status;
10777 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10778
George Burgess IV177399e2017-01-09 04:12:14 +000010779 LValue ThisVal;
10780 const LValue *ThisPtr = nullptr;
10781 if (This) {
10782#ifndef NDEBUG
10783 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10784 assert(MD && "Don't provide `this` for non-methods.");
10785 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10786#endif
10787 if (EvaluateObjectArgument(Info, This, ThisVal))
10788 ThisPtr = &ThisVal;
10789 if (Info.EvalStatus.HasSideEffects)
10790 return false;
10791 }
10792
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010793 ArgVector ArgValues(Args.size());
10794 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10795 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010796 if ((*I)->isValueDependent() ||
10797 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010798 // If evaluation fails, throw away the argument entirely.
10799 ArgValues[I - Args.begin()] = APValue();
10800 if (Info.EvalStatus.HasSideEffects)
10801 return false;
10802 }
10803
10804 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010805 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010806 ArgValues.data());
10807 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10808}
10809
Richard Smith253c2a32012-01-27 01:14:48 +000010810bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010811 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010812 PartialDiagnosticAt> &Diags) {
10813 // FIXME: It would be useful to check constexpr function templates, but at the
10814 // moment the constant expression evaluator cannot cope with the non-rigorous
10815 // ASTs which we build for dependent expressions.
10816 if (FD->isDependentContext())
10817 return true;
10818
10819 Expr::EvalStatus Status;
10820 Status.Diag = &Diags;
10821
Richard Smith6d4c6582013-11-05 22:18:15 +000010822 EvalInfo Info(FD->getASTContext(), Status,
10823 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010824
10825 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010826 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010827
Richard Smith7525ff62013-05-09 07:14:00 +000010828 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010829 // is a temporary being used as the 'this' pointer.
10830 LValue This;
10831 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010832 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010833
Richard Smith253c2a32012-01-27 01:14:48 +000010834 ArrayRef<const Expr*> Args;
10835
Richard Smith2e312c82012-03-03 22:46:17 +000010836 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010837 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10838 // Evaluate the call as a constant initializer, to allow the construction
10839 // of objects of non-literal types.
10840 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010841 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10842 } else {
10843 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010844 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010845 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010846 }
Richard Smith253c2a32012-01-27 01:14:48 +000010847
10848 return Diags.empty();
10849}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010850
10851bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10852 const FunctionDecl *FD,
10853 SmallVectorImpl<
10854 PartialDiagnosticAt> &Diags) {
10855 Expr::EvalStatus Status;
10856 Status.Diag = &Diags;
10857
10858 EvalInfo Info(FD->getASTContext(), Status,
10859 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10860
10861 // Fabricate a call stack frame to give the arguments a plausible cover story.
10862 ArrayRef<const Expr*> Args;
10863 ArgVector ArgValues(0);
10864 bool Success = EvaluateArgs(Args, ArgValues, Info);
10865 (void)Success;
10866 assert(Success &&
10867 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010868 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010869
10870 APValue ResultScratch;
10871 Evaluate(ResultScratch, Info, E);
10872 return Diags.empty();
10873}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010874
10875bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10876 unsigned Type) const {
10877 if (!getType()->isPointerType())
10878 return false;
10879
10880 Expr::EvalStatus Status;
10881 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010882 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010883}