blob: 8a2cbdc1871c77e8373eb91eb446341beb4bf065 [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();
Richard Smith69cf59e2018-03-09 02:00:01 +000066 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
Richard Smith69cf59e2018-03-09 02:00:01 +000068 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000069 //
70 // extern int arr[]; void f() { extern int arr[3]; };
71 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000072 //
73 // For now, we take the array bound from the most recent declaration.
74 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
75 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
76 QualType T = Redecl->getType();
77 if (!T->isIncompleteArrayType())
78 return T;
79 }
80 return D->getType();
81 }
Richard Smith84401042013-06-03 05:03:02 +000082
83 const Expr *Base = B.get<const Expr*>();
84
85 // For a materialized temporary, the type of the temporary we materialized
86 // may not be the type of the expression.
87 if (const MaterializeTemporaryExpr *MTE =
88 dyn_cast<MaterializeTemporaryExpr>(Base)) {
89 SmallVector<const Expr *, 2> CommaLHSs;
90 SmallVector<SubobjectAdjustment, 2> Adjustments;
91 const Expr *Temp = MTE->GetTemporaryExpr();
92 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
93 Adjustments);
94 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000095 // for it directly. Otherwise use the type after adjustment.
96 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000097 return Inner->getType();
98 }
99
100 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000101 }
102
Richard Smithd62306a2011-11-10 06:34:14 +0000103 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +0000105 static
Richard Smith84f6dcf2012-02-02 01:16:57 +0000106 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +0000107 APValue::BaseOrMemberType Value;
108 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return Value;
110 }
111
112 /// Get an LValue path entry, which is known to not be an array index, as a
113 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000114 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000115 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000116 }
117 /// Get an LValue path entry, which is known to not be an array index, as a
118 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000119 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000120 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000121 }
122 /// Determine whether this LValue path entry for a base class names a virtual
123 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000124 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000125 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000126 }
127
George Burgess IVe3763372016-12-22 02:50:20 +0000128 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
129 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
130 const FunctionDecl *Callee = CE->getDirectCallee();
131 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
132 }
133
134 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
135 /// This will look through a single cast.
136 ///
137 /// Returns null if we couldn't unwrap a function with alloc_size.
138 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
139 if (!E->getType()->isPointerType())
140 return nullptr;
141
142 E = E->IgnoreParens();
143 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000144 // probably be a cast of some kind. In exotic cases, we might also see a
145 // top-level ExprWithCleanups. Ignore them either way.
146 if (const auto *EC = dyn_cast<ExprWithCleanups>(E))
147 E = EC->getSubExpr()->IgnoreParens();
148
George Burgess IVe3763372016-12-22 02:50:20 +0000149 if (const auto *Cast = dyn_cast<CastExpr>(E))
150 E = Cast->getSubExpr()->IgnoreParens();
151
152 if (const auto *CE = dyn_cast<CallExpr>(E))
153 return getAllocSizeAttr(CE) ? CE : nullptr;
154 return nullptr;
155 }
156
157 /// Determines whether or not the given Base contains a call to a function
158 /// with the alloc_size attribute.
159 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
160 const auto *E = Base.dyn_cast<const Expr *>();
161 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
162 }
163
Richard Smith6f4f0f12017-10-20 22:56:25 +0000164 /// The bound to claim that an array of unknown bound has.
165 /// The value in MostDerivedArraySize is undefined in this case. So, set it
166 /// to an arbitrary value that's likely to loudly break things if it's used.
167 static const uint64_t AssumedSizeForUnsizedArray =
168 std::numeric_limits<uint64_t>::max() / 2;
169
George Burgess IVe3763372016-12-22 02:50:20 +0000170 /// Determines if an LValue with the given LValueBase will have an unsized
171 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000172 /// Find the path length and type of the most-derived subobject in the given
173 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000174 static unsigned
175 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
176 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000177 uint64_t &ArraySize, QualType &Type, bool &IsArray,
178 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000179 // This only accepts LValueBases from APValues, and APValues don't support
180 // arrays that lack size info.
181 assert(!isBaseAnAllocSizeCall(Base) &&
182 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000183 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000184 Type = getType(Base);
185
Richard Smith80815602011-11-07 05:07:52 +0000186 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000187 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000188 const ArrayType *AT = Ctx.getAsArrayType(Type);
189 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000190 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000191 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000192
193 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
194 ArraySize = CAT->getSize().getZExtValue();
195 } else {
196 assert(I == 0 && "unexpected unsized array designator");
197 FirstEntryIsUnsizedArray = true;
198 ArraySize = AssumedSizeForUnsizedArray;
199 }
Richard Smith66c96992012-02-18 22:04:06 +0000200 } else if (Type->isAnyComplexType()) {
201 const ComplexType *CT = Type->castAs<ComplexType>();
202 Type = CT->getElementType();
203 ArraySize = 2;
204 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000205 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000206 } else if (const FieldDecl *FD = getAsField(Path[I])) {
207 Type = FD->getType();
208 ArraySize = 0;
209 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000210 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000211 } else {
Richard Smith80815602011-11-07 05:07:52 +0000212 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000213 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000214 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000215 }
Richard Smith80815602011-11-07 05:07:52 +0000216 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000218 }
219
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 // The order of this enum is important for diagnostics.
221 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000222 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000223 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000224 };
225
Richard Smith96e0c102011-11-04 02:25:55 +0000226 /// A path from a glvalue to a subobject of that glvalue.
227 struct SubobjectDesignator {
228 /// True if the subobject was named in a manner not supported by C++11. Such
229 /// lvalues can still be folded, but they are not core constant expressions
230 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000231 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000232
Richard Smitha8105bc2012-01-06 16:39:00 +0000233 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000234 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000235
Daniel Jasperffdee092017-05-02 19:21:42 +0000236 /// Indicator of whether the first entry is an unsized array.
237 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000238
George Burgess IVa51c4072015-10-16 01:49:01 +0000239 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000240 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000241
Richard Smitha8105bc2012-01-06 16:39:00 +0000242 /// The length of the path to the most-derived object of which this is a
243 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000244 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000245
George Burgess IVa51c4072015-10-16 01:49:01 +0000246 /// The size of the array of which the most-derived object is an element.
247 /// This will always be 0 if the most-derived object is not an array
248 /// element. 0 is not an indicator of whether or not the most-derived object
249 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000250 ///
251 /// If the current array is an unsized array, the value of this is
252 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000253 uint64_t MostDerivedArraySize;
254
255 /// The type of the most derived object referred to by this address.
256 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000257
Richard Smith80815602011-11-07 05:07:52 +0000258 typedef APValue::LValuePathEntry PathEntry;
259
Richard Smith96e0c102011-11-04 02:25:55 +0000260 /// The entries on the path from the glvalue to the designated subobject.
261 SmallVector<PathEntry, 8> Entries;
262
Richard Smitha8105bc2012-01-06 16:39:00 +0000263 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000264
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000266 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000267 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000268 MostDerivedPathLength(0), MostDerivedArraySize(0),
269 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000270
271 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000272 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000273 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000274 MostDerivedPathLength(0), MostDerivedArraySize(0) {
275 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000276 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000277 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000278 ArrayRef<PathEntry> VEntries = V.getLValuePath();
279 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000280 if (V.getLValueBase()) {
281 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000282 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000283 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000284 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000285 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000286 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000287 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000288 }
Richard Smith80815602011-11-07 05:07:52 +0000289 }
290 }
291
Richard Smith96e0c102011-11-04 02:25:55 +0000292 void setInvalid() {
293 Invalid = true;
294 Entries.clear();
295 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000296
George Burgess IVe3763372016-12-22 02:50:20 +0000297 /// Determine whether the most derived subobject is an array without a
298 /// known bound.
299 bool isMostDerivedAnUnsizedArray() const {
300 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000301 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000302 }
303
304 /// Determine what the most derived array's size is. Results in an assertion
305 /// failure if the most derived array lacks a size.
306 uint64_t getMostDerivedArraySize() const {
307 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
308 return MostDerivedArraySize;
309 }
310
Richard Smitha8105bc2012-01-06 16:39:00 +0000311 /// Determine whether this is a one-past-the-end pointer.
312 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000313 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000314 if (IsOnePastTheEnd)
315 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000316 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000317 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
318 return true;
319 return false;
320 }
321
Richard Smith06f71b52018-08-04 00:57:17 +0000322 /// Get the range of valid index adjustments in the form
323 /// {maximum value that can be subtracted from this pointer,
324 /// maximum value that can be added to this pointer}
325 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
326 if (Invalid || isMostDerivedAnUnsizedArray())
327 return {0, 0};
328
329 // [expr.add]p4: For the purposes of these operators, a pointer to a
330 // nonarray object behaves the same as a pointer to the first element of
331 // an array of length one with the type of the object as its element type.
332 bool IsArray = MostDerivedPathLength == Entries.size() &&
333 MostDerivedIsArrayElement;
334 uint64_t ArrayIndex =
335 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
336 uint64_t ArraySize =
337 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
338 return {ArrayIndex, ArraySize - ArrayIndex};
339 }
340
Richard Smitha8105bc2012-01-06 16:39:00 +0000341 /// Check that this refers to a valid subobject.
342 bool isValidSubobject() const {
343 if (Invalid)
344 return false;
345 return !isOnePastTheEnd();
346 }
347 /// Check that this refers to a valid subobject, and if not, produce a
348 /// relevant diagnostic and set the designator as invalid.
349 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
350
Richard Smith06f71b52018-08-04 00:57:17 +0000351 /// Get the type of the designated object.
352 QualType getType(ASTContext &Ctx) const {
353 assert(!Invalid && "invalid designator has no subobject type");
354 return MostDerivedPathLength == Entries.size()
355 ? MostDerivedType
356 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
357 }
358
Richard Smitha8105bc2012-01-06 16:39:00 +0000359 /// Update this designator to refer to the first element within this array.
360 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000361 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000362 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000363 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000364
365 // This is a most-derived object.
366 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000367 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000368 MostDerivedArraySize = CAT->getSize().getZExtValue();
369 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000370 }
George Burgess IVe3763372016-12-22 02:50:20 +0000371 /// Update this designator to refer to the first element within the array of
372 /// elements of type T. This is an array of unknown size.
373 void addUnsizedArrayUnchecked(QualType ElemTy) {
374 PathEntry Entry;
375 Entry.ArrayIndex = 0;
376 Entries.push_back(Entry);
377
378 MostDerivedType = ElemTy;
379 MostDerivedIsArrayElement = true;
380 // The value in MostDerivedArraySize is undefined in this case. So, set it
381 // to an arbitrary value that's likely to loudly break things if it's
382 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000383 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000384 MostDerivedPathLength = Entries.size();
385 }
Richard Smith96e0c102011-11-04 02:25:55 +0000386 /// Update this designator to refer to the given base or member of this
387 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000388 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000389 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000390 APValue::BaseOrMemberType Value(D, Virtual);
391 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000392 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000393
394 // If this isn't a base class, it's a new most-derived object.
395 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
396 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000397 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000398 MostDerivedArraySize = 0;
399 MostDerivedPathLength = Entries.size();
400 }
Richard Smith96e0c102011-11-04 02:25:55 +0000401 }
Richard Smith66c96992012-02-18 22:04:06 +0000402 /// Update this designator to refer to the given complex component.
403 void addComplexUnchecked(QualType EltTy, bool Imag) {
404 PathEntry Entry;
405 Entry.ArrayIndex = Imag;
406 Entries.push_back(Entry);
407
408 // This is technically a most-derived object, though in practice this
409 // is unlikely to matter.
410 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000411 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000412 MostDerivedArraySize = 2;
413 MostDerivedPathLength = Entries.size();
414 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000415 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000416 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
417 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000418 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000419 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
420 if (Invalid || !N) return;
421 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
422 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000423 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000424 // Can't verify -- trust that the user is doing the right thing (or if
425 // not, trust that the caller will catch the bad behavior).
426 // FIXME: Should we reject if this overflows, at least?
427 Entries.back().ArrayIndex += TruncatedN;
428 return;
429 }
430
431 // [expr.add]p4: For the purposes of these operators, a pointer to a
432 // nonarray object behaves the same as a pointer to the first element of
433 // an array of length one with the type of the object as its element type.
434 bool IsArray = MostDerivedPathLength == Entries.size() &&
435 MostDerivedIsArrayElement;
436 uint64_t ArrayIndex =
437 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
438 uint64_t ArraySize =
439 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
440
441 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
442 // Calculate the actual index in a wide enough type, so we can include
443 // it in the note.
444 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
445 (llvm::APInt&)N += ArrayIndex;
446 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
447 diagnosePointerArithmetic(Info, E, N);
448 setInvalid();
449 return;
450 }
451
452 ArrayIndex += TruncatedN;
453 assert(ArrayIndex <= ArraySize &&
454 "bounds check succeeded for out-of-bounds index");
455
456 if (IsArray)
457 Entries.back().ArrayIndex = ArrayIndex;
458 else
459 IsOnePastTheEnd = (ArrayIndex != 0);
460 }
Richard Smith96e0c102011-11-04 02:25:55 +0000461 };
462
Richard Smith254a73d2011-10-28 22:34:42 +0000463 /// A stack frame in the constexpr call stack.
464 struct CallStackFrame {
465 EvalInfo &Info;
466
467 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000468 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000469
Richard Smithf6f003a2011-12-16 19:06:07 +0000470 /// Callee - The function which was called.
471 const FunctionDecl *Callee;
472
Richard Smithd62306a2011-11-10 06:34:14 +0000473 /// This - The binding for the this pointer in this call, if any.
474 const LValue *This;
475
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000476 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000477 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000478 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000479
Eli Friedman4830ec82012-06-25 21:21:08 +0000480 // Note that we intentionally use std::map here so that references to
481 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000482 typedef std::pair<const void *, unsigned> MapKeyTy;
483 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000484 /// Temporaries - Temporary lvalues materialized within this stack frame.
485 MapTy Temporaries;
486
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000487 /// CallLoc - The location of the call expression for this call.
488 SourceLocation CallLoc;
489
490 /// Index - The call index of this call.
491 unsigned Index;
492
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000493 /// The stack of integers for tracking version numbers for temporaries.
494 SmallVector<unsigned, 2> TempVersionStack = {1};
495 unsigned CurTempVersion = TempVersionStack.back();
496
497 unsigned getTempVersion() const { return TempVersionStack.back(); }
498
499 void pushTempVersion() {
500 TempVersionStack.push_back(++CurTempVersion);
501 }
502
503 void popTempVersion() {
504 TempVersionStack.pop_back();
505 }
506
Faisal Vali051e3a22017-02-16 04:12:21 +0000507 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
508 // on the overall stack usage of deeply-recursing constexpr evaluataions.
509 // (We should cache this map rather than recomputing it repeatedly.)
510 // But let's try this and see how it goes; we can look into caching the map
511 // as a later change.
512
513 /// LambdaCaptureFields - Mapping from captured variables/this to
514 /// corresponding data members in the closure class.
515 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
516 FieldDecl *LambdaThisCaptureField;
517
Richard Smithf6f003a2011-12-16 19:06:07 +0000518 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
519 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000520 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000521 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000522
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000523 // Return the temporary for Key whose version number is Version.
524 APValue *getTemporary(const void *Key, unsigned Version) {
525 MapKeyTy KV(Key, Version);
526 auto LB = Temporaries.lower_bound(KV);
527 if (LB != Temporaries.end() && LB->first == KV)
528 return &LB->second;
529 // Pair (Key,Version) wasn't found in the map. Check that no elements
530 // in the map have 'Key' as their key.
531 assert((LB == Temporaries.end() || LB->first.first != Key) &&
532 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
533 "Element with key 'Key' found in map");
534 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000535 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000536
537 // Return the current temporary for Key in the map.
538 APValue *getCurrentTemporary(const void *Key) {
539 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
540 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
541 return &std::prev(UB)->second;
542 return nullptr;
543 }
544
545 // Return the version number of the current temporary for Key.
546 unsigned getCurrentTemporaryVersion(const void *Key) const {
547 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
548 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
549 return std::prev(UB)->first.second;
550 return 0;
551 }
552
Richard Smith08d6a2c2013-07-24 07:11:57 +0000553 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000554 };
555
Richard Smith852c9db2013-04-20 22:23:05 +0000556 /// Temporarily override 'this'.
557 class ThisOverrideRAII {
558 public:
559 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
560 : Frame(Frame), OldThis(Frame.This) {
561 if (Enable)
562 Frame.This = NewThis;
563 }
564 ~ThisOverrideRAII() {
565 Frame.This = OldThis;
566 }
567 private:
568 CallStackFrame &Frame;
569 const LValue *OldThis;
570 };
571
Richard Smith92b1ce02011-12-12 09:28:41 +0000572 /// A partial diagnostic which we might know in advance that we are not going
573 /// to emit.
574 class OptionalDiagnostic {
575 PartialDiagnostic *Diag;
576
577 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000578 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
579 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000580
581 template<typename T>
582 OptionalDiagnostic &operator<<(const T &v) {
583 if (Diag)
584 *Diag << v;
585 return *this;
586 }
Richard Smithfe800032012-01-31 04:08:20 +0000587
588 OptionalDiagnostic &operator<<(const APSInt &I) {
589 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000590 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000591 I.toString(Buffer);
592 *Diag << StringRef(Buffer.data(), Buffer.size());
593 }
594 return *this;
595 }
596
597 OptionalDiagnostic &operator<<(const APFloat &F) {
598 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000599 // FIXME: Force the precision of the source value down so we don't
600 // print digits which are usually useless (we don't really care here if
601 // we truncate a digit by accident in edge cases). Ideally,
Fangrui Song6907ce22018-07-30 19:24:48 +0000602 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000603 // representation which rounds to the correct value, but it's a bit
604 // tricky to implement.
605 unsigned precision =
606 llvm::APFloat::semanticsPrecision(F.getSemantics());
607 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000608 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000609 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000610 *Diag << StringRef(Buffer.data(), Buffer.size());
611 }
612 return *this;
613 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000614 };
615
Richard Smith08d6a2c2013-07-24 07:11:57 +0000616 /// A cleanup, and a flag indicating whether it is lifetime-extended.
617 class Cleanup {
618 llvm::PointerIntPair<APValue*, 1, bool> Value;
619
620 public:
621 Cleanup(APValue *Val, bool IsLifetimeExtended)
622 : Value(Val, IsLifetimeExtended) {}
623
624 bool isLifetimeExtended() const { return Value.getInt(); }
625 void endLifetime() {
626 *Value.getPointer() = APValue();
627 }
628 };
629
Richard Smithb228a862012-02-15 02:18:13 +0000630 /// EvalInfo - This is a private struct used by the evaluator to capture
631 /// information about a subexpression as it is folded. It retains information
632 /// about the AST context, but also maintains information about the folded
633 /// expression.
634 ///
635 /// If an expression could be evaluated, it is still possible it is not a C
636 /// "integer constant expression" or constant expression. If not, this struct
637 /// captures information about how and why not.
638 ///
639 /// One bit of information passed *into* the request for constant folding
640 /// indicates whether the subexpression is "evaluated" or not according to C
641 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
642 /// evaluate the expression regardless of what the RHS is, but C only allows
643 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000644 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000645 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000646
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000647 /// EvalStatus - Contains information about the evaluation.
648 Expr::EvalStatus &EvalStatus;
649
650 /// CurrentCall - The top of the constexpr call stack.
651 CallStackFrame *CurrentCall;
652
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000653 /// CallStackDepth - The number of calls in the call stack right now.
654 unsigned CallStackDepth;
655
Richard Smithb228a862012-02-15 02:18:13 +0000656 /// NextCallIndex - The next call index to assign.
657 unsigned NextCallIndex;
658
Richard Smitha3d3bd22013-05-08 02:12:03 +0000659 /// StepsLeft - The remaining number of evaluation steps we're permitted
660 /// to perform. This is essentially a limit for the number of statements
661 /// we will evaluate.
662 unsigned StepsLeft;
663
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000664 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000665 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000666 CallStackFrame BottomFrame;
667
Richard Smith08d6a2c2013-07-24 07:11:57 +0000668 /// A stack of values whose lifetimes end at the end of some surrounding
669 /// evaluation frame.
670 llvm::SmallVector<Cleanup, 16> CleanupStack;
671
Richard Smithd62306a2011-11-10 06:34:14 +0000672 /// EvaluatingDecl - This is the declaration whose initializer is being
673 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000674 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000675
676 /// EvaluatingDeclValue - This is the value being constructed for the
677 /// declaration whose initializer is being evaluated, if any.
678 APValue *EvaluatingDeclValue;
679
Erik Pilkington42925492017-10-04 00:18:55 +0000680 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
681 /// the call index that that lvalue was allocated in.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000682 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
683 EvaluatingObject;
Erik Pilkington42925492017-10-04 00:18:55 +0000684
685 /// EvaluatingConstructors - Set of objects that are currently being
686 /// constructed.
687 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
688
689 struct EvaluatingConstructorRAII {
690 EvalInfo &EI;
691 EvaluatingObject Object;
692 bool DidInsert;
693 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
694 : EI(EI), Object(Object) {
695 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
696 }
697 ~EvaluatingConstructorRAII() {
698 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
699 }
700 };
701
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000702 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
703 unsigned Version) {
704 return EvaluatingConstructors.count(
705 EvaluatingObject(Decl, {CallIndex, Version}));
Erik Pilkington42925492017-10-04 00:18:55 +0000706 }
707
Richard Smith410306b2016-12-12 02:53:20 +0000708 /// The current array initialization index, if we're performing array
709 /// initialization.
710 uint64_t ArrayInitIndex = -1;
711
Richard Smith357362d2011-12-13 06:39:58 +0000712 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
713 /// notes attached to it will also be stored, otherwise they will not be.
714 bool HasActiveDiagnostic;
715
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000716 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000717 /// fold (not just why it's not strictly a constant expression)?
718 bool HasFoldFailureDiagnostic;
719
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000720 /// Whether or not we're currently speculatively evaluating.
George Burgess IV8c892b52016-05-25 22:31:54 +0000721 bool IsSpeculativelyEvaluating;
722
Richard Smith6d4c6582013-11-05 22:18:15 +0000723 enum EvaluationMode {
724 /// Evaluate as a constant expression. Stop if we find that the expression
725 /// is not a constant expression.
726 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000727
Richard Smith6d4c6582013-11-05 22:18:15 +0000728 /// Evaluate as a potential constant expression. Keep going if we hit a
729 /// construct that we can't evaluate yet (because we don't yet know the
730 /// value of something) but stop if we hit something that could never be
731 /// a constant expression.
732 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000733
Richard Smith6d4c6582013-11-05 22:18:15 +0000734 /// Fold the expression to a constant. Stop if we hit a side-effect that
735 /// we can't model.
736 EM_ConstantFold,
737
738 /// Evaluate the expression looking for integer overflow and similar
739 /// issues. Don't worry about side-effects, and try to visit all
740 /// subexpressions.
741 EM_EvaluateForOverflow,
742
743 /// Evaluate in any way we know how. Don't worry about side-effects that
744 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000745 EM_IgnoreSideEffects,
746
747 /// Evaluate as a constant expression. Stop if we find that the expression
748 /// is not a constant expression. Some expressions can be retried in the
749 /// optimizer if we don't constant fold them here, but in an unevaluated
750 /// context we try to fold them immediately since the optimizer never
751 /// gets a chance to look at it.
752 EM_ConstantExpressionUnevaluated,
753
754 /// Evaluate as a potential constant expression. Keep going if we hit a
755 /// construct that we can't evaluate yet (because we don't yet know the
756 /// value of something) but stop if we hit something that could never be
757 /// a constant expression. Some expressions can be retried in the
758 /// optimizer if we don't constant fold them here, but in an unevaluated
759 /// context we try to fold them immediately since the optimizer never
760 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000761 EM_PotentialConstantExpressionUnevaluated,
762
George Burgess IVf9013bf2017-02-10 22:52:29 +0000763 /// Evaluate as a constant expression. In certain scenarios, if:
764 /// - we find a MemberExpr with a base that can't be evaluated, or
765 /// - we find a variable initialized with a call to a function that has
766 /// the alloc_size attribute on it
767 /// then we may consider evaluation to have succeeded.
768 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000769 /// In either case, the LValue returned shall have an invalid base; in the
770 /// former, the base will be the invalid MemberExpr, in the latter, the
771 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
772 /// said CallExpr.
773 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000774 } EvalMode;
775
776 /// Are we checking whether the expression is a potential constant
777 /// expression?
778 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000779 return EvalMode == EM_PotentialConstantExpression ||
780 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000781 }
782
783 /// Are we checking an expression for overflow?
784 // FIXME: We should check for any kind of undefined or suspicious behavior
785 // in such constructs, not just overflow.
786 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
787
788 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000789 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000790 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000791 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000792 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
793 EvaluatingDecl((const ValueDecl *)nullptr),
794 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000795 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
796 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000797
Richard Smith7525ff62013-05-09 07:14:00 +0000798 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
799 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000800 EvaluatingDeclValue = &Value;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000801 EvaluatingConstructors.insert({Base, {0, 0}});
Richard Smithd62306a2011-11-10 06:34:14 +0000802 }
803
David Blaikiebbafb8a2012-03-11 07:00:24 +0000804 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000805
Richard Smith357362d2011-12-13 06:39:58 +0000806 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000807 // Don't perform any constexpr calls (other than the call we're checking)
808 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000809 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000810 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000811 if (NextCallIndex == 0) {
812 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000813 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000814 return false;
815 }
Richard Smith357362d2011-12-13 06:39:58 +0000816 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
817 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000818 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000819 << getLangOpts().ConstexprCallDepth;
820 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000821 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000822
Richard Smithb228a862012-02-15 02:18:13 +0000823 CallStackFrame *getCallFrame(unsigned CallIndex) {
824 assert(CallIndex && "no call index in getCallFrame");
825 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
826 // be null in this loop.
827 CallStackFrame *Frame = CurrentCall;
828 while (Frame->Index > CallIndex)
829 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000830 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000831 }
832
Richard Smitha3d3bd22013-05-08 02:12:03 +0000833 bool nextStep(const Stmt *S) {
834 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000835 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000836 return false;
837 }
838 --StepsLeft;
839 return true;
840 }
841
Richard Smith357362d2011-12-13 06:39:58 +0000842 private:
843 /// Add a diagnostic to the diagnostics list.
844 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
845 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
846 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
847 return EvalStatus.Diag->back().second;
848 }
849
Richard Smithf6f003a2011-12-16 19:06:07 +0000850 /// Add notes containing a call stack to the current point of evaluation.
851 void addCallStack(unsigned Limit);
852
Faisal Valie690b7a2016-07-02 22:34:24 +0000853 private:
854 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
855 unsigned ExtraNotes, bool IsCCEDiag) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000856
Richard Smith92b1ce02011-12-12 09:28:41 +0000857 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000858 // If we have a prior diagnostic, it will be noting that the expression
859 // isn't a constant expression. This diagnostic is more important,
860 // unless we require this evaluation to produce a constant expression.
861 //
862 // FIXME: We might want to show both diagnostics to the user in
863 // EM_ConstantFold mode.
864 if (!EvalStatus.Diag->empty()) {
865 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000866 case EM_ConstantFold:
867 case EM_IgnoreSideEffects:
868 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000869 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000870 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000871 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000872 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000873 case EM_ConstantExpression:
874 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000875 case EM_ConstantExpressionUnevaluated:
876 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000877 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000878 HasActiveDiagnostic = false;
879 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000880 }
881 }
882
Richard Smithf6f003a2011-12-16 19:06:07 +0000883 unsigned CallStackNotes = CallStackDepth - 1;
884 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
885 if (Limit)
886 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000887 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000888 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000889
Richard Smith357362d2011-12-13 06:39:58 +0000890 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000891 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000892 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000893 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
894 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000895 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000896 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000897 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000898 }
Richard Smith357362d2011-12-13 06:39:58 +0000899 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000900 return OptionalDiagnostic();
901 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000902 public:
903 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
904 OptionalDiagnostic
905 FFDiag(SourceLocation Loc,
906 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
907 unsigned ExtraNotes = 0) {
908 return Diag(Loc, DiagId, ExtraNotes, false);
909 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000910
Faisal Valie690b7a2016-07-02 22:34:24 +0000911 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000912 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000913 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000914 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000915 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000916 HasActiveDiagnostic = false;
917 return OptionalDiagnostic();
918 }
919
Richard Smith92b1ce02011-12-12 09:28:41 +0000920 /// Diagnose that the evaluation does not produce a C++11 core constant
921 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000922 ///
923 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
924 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000925 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000926 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000927 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000928 // Don't override a previous diagnostic. Don't bother collecting
929 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000930 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000931 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000932 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000933 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000934 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000935 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000936 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
937 = diag::note_invalid_subexpr_in_const_expr,
938 unsigned ExtraNotes = 0) {
939 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
940 }
Richard Smith357362d2011-12-13 06:39:58 +0000941 /// Add a note to a prior diagnostic.
942 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
943 if (!HasActiveDiagnostic)
944 return OptionalDiagnostic();
945 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000946 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000947
948 /// Add a stack of notes to a prior diagnostic.
949 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
950 if (HasActiveDiagnostic) {
951 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
952 Diags.begin(), Diags.end());
953 }
954 }
Richard Smith253c2a32012-01-27 01:14:48 +0000955
Richard Smith6d4c6582013-11-05 22:18:15 +0000956 /// Should we continue evaluation after encountering a side-effect that we
957 /// couldn't model?
958 bool keepEvaluatingAfterSideEffect() {
959 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000960 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000961 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000962 case EM_EvaluateForOverflow:
963 case EM_IgnoreSideEffects:
964 return true;
965
Richard Smith6d4c6582013-11-05 22:18:15 +0000966 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000967 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000968 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000969 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000970 return false;
971 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000972 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000973 }
974
975 /// Note that we have had a side-effect, and determine whether we should
976 /// keep evaluating.
977 bool noteSideEffect() {
978 EvalStatus.HasSideEffects = true;
979 return keepEvaluatingAfterSideEffect();
980 }
981
Richard Smithce8eca52015-12-08 03:21:47 +0000982 /// Should we continue evaluation after encountering undefined behavior?
983 bool keepEvaluatingAfterUndefinedBehavior() {
984 switch (EvalMode) {
985 case EM_EvaluateForOverflow:
986 case EM_IgnoreSideEffects:
987 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000988 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000989 return true;
990
991 case EM_PotentialConstantExpression:
992 case EM_PotentialConstantExpressionUnevaluated:
993 case EM_ConstantExpression:
994 case EM_ConstantExpressionUnevaluated:
995 return false;
996 }
997 llvm_unreachable("Missed EvalMode case");
998 }
999
1000 /// Note that we hit something that was technically undefined behavior, but
1001 /// that we can evaluate past it (such as signed overflow or floating-point
1002 /// division by zero.)
1003 bool noteUndefinedBehavior() {
1004 EvalStatus.HasUndefinedBehavior = true;
1005 return keepEvaluatingAfterUndefinedBehavior();
1006 }
1007
Richard Smith253c2a32012-01-27 01:14:48 +00001008 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001009 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +00001010 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +00001011 if (!StepsLeft)
1012 return false;
1013
1014 switch (EvalMode) {
1015 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001016 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001017 case EM_EvaluateForOverflow:
1018 return true;
1019
1020 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001021 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001022 case EM_ConstantFold:
1023 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00001024 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +00001025 return false;
1026 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001027 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001028 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001029
George Burgess IV8c892b52016-05-25 22:31:54 +00001030 /// Notes that we failed to evaluate an expression that other expressions
1031 /// directly depend on, and determine if we should keep evaluating. This
1032 /// should only be called if we actually intend to keep evaluating.
1033 ///
1034 /// Call noteSideEffect() instead if we may be able to ignore the value that
1035 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1036 ///
1037 /// (Foo(), 1) // use noteSideEffect
1038 /// (Foo() || true) // use noteSideEffect
1039 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001040 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001041 // Failure when evaluating some expression often means there is some
1042 // subexpression whose evaluation was skipped. Therefore, (because we
1043 // don't track whether we skipped an expression when unwinding after an
1044 // evaluation failure) every evaluation failure that bubbles up from a
1045 // subexpression implies that a side-effect has potentially happened. We
1046 // skip setting the HasSideEffects flag to true until we decide to
1047 // continue evaluating after that point, which happens here.
1048 bool KeepGoing = keepEvaluatingAfterFailure();
1049 EvalStatus.HasSideEffects |= KeepGoing;
1050 return KeepGoing;
1051 }
1052
Richard Smith410306b2016-12-12 02:53:20 +00001053 class ArrayInitLoopIndex {
1054 EvalInfo &Info;
1055 uint64_t OuterIndex;
1056
1057 public:
1058 ArrayInitLoopIndex(EvalInfo &Info)
1059 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1060 Info.ArrayInitIndex = 0;
1061 }
1062 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1063
1064 operator uint64_t&() { return Info.ArrayInitIndex; }
1065 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001066 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001067
1068 /// Object used to treat all foldable expressions as constant expressions.
1069 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001070 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001071 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001072 bool HadNoPriorDiags;
1073 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001074
Richard Smith6d4c6582013-11-05 22:18:15 +00001075 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1076 : Info(Info),
1077 Enabled(Enabled),
1078 HadNoPriorDiags(Info.EvalStatus.Diag &&
1079 Info.EvalStatus.Diag->empty() &&
1080 !Info.EvalStatus.HasSideEffects),
1081 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001082 if (Enabled &&
1083 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1084 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001085 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001086 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001087 void keepDiagnostics() { Enabled = false; }
1088 ~FoldConstant() {
1089 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001090 !Info.EvalStatus.HasSideEffects)
1091 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001092 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001093 }
1094 };
Richard Smith17100ba2012-02-16 02:46:34 +00001095
George Burgess IV3a03fab2015-09-04 21:28:13 +00001096 /// RAII object used to treat the current evaluation as the correct pointer
1097 /// offset fold for the current EvalMode
1098 struct FoldOffsetRAII {
1099 EvalInfo &Info;
1100 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +00001101 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001102 : Info(Info), OldMode(Info.EvalMode) {
1103 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +00001104 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001105 }
1106
1107 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1108 };
1109
George Burgess IV8c892b52016-05-25 22:31:54 +00001110 /// RAII object used to optionally suppress diagnostics and side-effects from
1111 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001112 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001113 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001114 Expr::EvalStatus OldStatus;
1115 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001116
George Burgess IV8c892b52016-05-25 22:31:54 +00001117 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001118 Info = Other.Info;
1119 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001120 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001121 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001122 }
1123
1124 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001125 if (!Info)
1126 return;
1127
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001128 Info->EvalStatus = OldStatus;
1129 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001130 }
1131
Richard Smith17100ba2012-02-16 02:46:34 +00001132 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001133 SpeculativeEvaluationRAII() = default;
1134
1135 SpeculativeEvaluationRAII(
1136 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001137 : Info(&Info), OldStatus(Info.EvalStatus),
1138 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001139 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001140 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001141 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001142
1143 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1144 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1145 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001146 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001147
1148 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1149 maybeRestoreState();
1150 moveFromAndCancel(std::move(Other));
1151 return *this;
1152 }
1153
1154 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001155 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001156
1157 /// RAII object wrapping a full-expression or block scope, and handling
1158 /// the ending of the lifetime of temporaries created within it.
1159 template<bool IsFullExpression>
1160 class ScopeRAII {
1161 EvalInfo &Info;
1162 unsigned OldStackSize;
1163 public:
1164 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001165 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1166 // Push a new temporary version. This is needed to distinguish between
1167 // temporaries created in different iterations of a loop.
1168 Info.CurrentCall->pushTempVersion();
1169 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001170 ~ScopeRAII() {
1171 // Body moved to a static method to encourage the compiler to inline away
1172 // instances of this class.
1173 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001174 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001175 }
1176 private:
1177 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1178 unsigned NewEnd = OldStackSize;
1179 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1180 I != N; ++I) {
1181 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1182 // Full-expression cleanup of a lifetime-extended temporary: nothing
1183 // to do, just move this cleanup to the right place in the stack.
1184 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1185 ++NewEnd;
1186 } else {
1187 // End the lifetime of the object.
1188 Info.CleanupStack[I].endLifetime();
1189 }
1190 }
1191 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1192 Info.CleanupStack.end());
1193 }
1194 };
1195 typedef ScopeRAII<false> BlockScopeRAII;
1196 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001197}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001198
Richard Smitha8105bc2012-01-06 16:39:00 +00001199bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1200 CheckSubobjectKind CSK) {
1201 if (Invalid)
1202 return false;
1203 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001204 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001205 << CSK;
1206 setInvalid();
1207 return false;
1208 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001209 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1210 // must actually be at least one array element; even a VLA cannot have a
1211 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001212 return true;
1213}
1214
Richard Smith6f4f0f12017-10-20 22:56:25 +00001215void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1216 const Expr *E) {
1217 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1218 // Do not set the designator as invalid: we can represent this situation,
1219 // and correct handling of __builtin_object_size requires us to do so.
1220}
1221
Richard Smitha8105bc2012-01-06 16:39:00 +00001222void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001223 const Expr *E,
1224 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001225 // If we're complaining, we must be able to statically determine the size of
1226 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001227 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001228 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001229 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001230 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001231 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001232 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001233 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001234 setInvalid();
1235}
1236
Richard Smithf6f003a2011-12-16 19:06:07 +00001237CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1238 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001239 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001240 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1241 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001242 Info.CurrentCall = this;
1243 ++Info.CallStackDepth;
1244}
1245
1246CallStackFrame::~CallStackFrame() {
1247 assert(Info.CurrentCall == this && "calls retired out of order");
1248 --Info.CallStackDepth;
1249 Info.CurrentCall = Caller;
1250}
1251
Richard Smith08d6a2c2013-07-24 07:11:57 +00001252APValue &CallStackFrame::createTemporary(const void *Key,
1253 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001254 unsigned Version = Info.CurrentCall->getTempVersion();
1255 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smith08d6a2c2013-07-24 07:11:57 +00001256 assert(Result.isUninit() && "temporary created multiple times");
1257 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1258 return Result;
1259}
1260
Richard Smith84401042013-06-03 05:03:02 +00001261static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001262
1263void EvalInfo::addCallStack(unsigned Limit) {
1264 // Determine which calls to skip, if any.
1265 unsigned ActiveCalls = CallStackDepth - 1;
1266 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1267 if (Limit && Limit < ActiveCalls) {
1268 SkipStart = Limit / 2 + Limit % 2;
1269 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001270 }
1271
Richard Smithf6f003a2011-12-16 19:06:07 +00001272 // Walk the call stack and add the diagnostics.
1273 unsigned CallIdx = 0;
1274 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1275 Frame = Frame->Caller, ++CallIdx) {
1276 // Skip this call?
1277 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1278 if (CallIdx == SkipStart) {
1279 // Note that we're skipping calls.
1280 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1281 << unsigned(ActiveCalls - Limit);
1282 }
1283 continue;
1284 }
1285
Richard Smith5179eb72016-06-28 19:03:57 +00001286 // Use a different note for an inheriting constructor, because from the
1287 // user's perspective it's not really a function at all.
1288 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1289 if (CD->isInheritingConstructor()) {
1290 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1291 << CD->getParent();
1292 continue;
1293 }
1294 }
1295
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001296 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001297 llvm::raw_svector_ostream Out(Buffer);
1298 describeCall(Frame, Out);
1299 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1300 }
1301}
1302
1303namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001304 struct ComplexValue {
1305 private:
1306 bool IsInt;
1307
1308 public:
1309 APSInt IntReal, IntImag;
1310 APFloat FloatReal, FloatImag;
1311
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001312 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001313
1314 void makeComplexFloat() { IsInt = false; }
1315 bool isComplexFloat() const { return !IsInt; }
1316 APFloat &getComplexFloatReal() { return FloatReal; }
1317 APFloat &getComplexFloatImag() { return FloatImag; }
1318
1319 void makeComplexInt() { IsInt = true; }
1320 bool isComplexInt() const { return IsInt; }
1321 APSInt &getComplexIntReal() { return IntReal; }
1322 APSInt &getComplexIntImag() { return IntImag; }
1323
Richard Smith2e312c82012-03-03 22:46:17 +00001324 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001325 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001326 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001327 else
Richard Smith2e312c82012-03-03 22:46:17 +00001328 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001329 }
Richard Smith2e312c82012-03-03 22:46:17 +00001330 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001331 assert(v.isComplexFloat() || v.isComplexInt());
1332 if (v.isComplexFloat()) {
1333 makeComplexFloat();
1334 FloatReal = v.getComplexFloatReal();
1335 FloatImag = v.getComplexFloatImag();
1336 } else {
1337 makeComplexInt();
1338 IntReal = v.getComplexIntReal();
1339 IntImag = v.getComplexIntImag();
1340 }
1341 }
John McCall93d91dc2010-05-07 17:22:02 +00001342 };
John McCall45d55e42010-05-07 21:00:08 +00001343
1344 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001345 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001346 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001347 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001348 bool IsNullPtr : 1;
1349 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001350
Richard Smithce40ad62011-11-12 22:28:03 +00001351 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001352 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001353 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001354 SubobjectDesignator &getLValueDesignator() { return Designator; }
1355 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001356 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001357
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001358 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1359 unsigned getLValueVersion() const { return Base.getVersion(); }
1360
Richard Smith2e312c82012-03-03 22:46:17 +00001361 void moveInto(APValue &V) const {
1362 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001363 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001364 else {
1365 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001366 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001367 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001368 }
John McCall45d55e42010-05-07 21:00:08 +00001369 }
Richard Smith2e312c82012-03-03 22:46:17 +00001370 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001371 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001372 Base = V.getLValueBase();
1373 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001374 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001375 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001376 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001377 }
1378
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001379 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001380#ifndef NDEBUG
1381 // We only allow a few types of invalid bases. Enforce that here.
1382 if (BInvalid) {
1383 const auto *E = B.get<const Expr *>();
1384 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1385 "Unexpected type of invalid base");
1386 }
1387#endif
1388
Richard Smithce40ad62011-11-12 22:28:03 +00001389 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001390 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001391 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001392 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001393 IsNullPtr = false;
1394 }
1395
1396 void setNull(QualType PointerTy, uint64_t TargetVal) {
1397 Base = (Expr *)nullptr;
1398 Offset = CharUnits::fromQuantity(TargetVal);
1399 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001400 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1401 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001402 }
1403
George Burgess IV3a03fab2015-09-04 21:28:13 +00001404 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001405 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001406 }
1407
Richard Smitha8105bc2012-01-06 16:39:00 +00001408 // Check that this LValue is not based on a null pointer. If it is, produce
1409 // a diagnostic and mark the designator as invalid.
1410 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1411 CheckSubobjectKind CSK) {
1412 if (Designator.Invalid)
1413 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001414 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001415 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001416 << CSK;
1417 Designator.setInvalid();
1418 return false;
1419 }
1420 return true;
1421 }
1422
1423 // Check this LValue refers to an object. If not, set the designator to be
1424 // invalid and emit a diagnostic.
1425 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001426 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001427 Designator.checkSubobject(Info, E, CSK);
1428 }
1429
1430 void addDecl(EvalInfo &Info, const Expr *E,
1431 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001432 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1433 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001434 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001435 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1436 if (!Designator.Entries.empty()) {
1437 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1438 Designator.setInvalid();
1439 return;
1440 }
Richard Smithefdb5032017-11-15 03:03:56 +00001441 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1442 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1443 Designator.FirstEntryIsAnUnsizedArray = true;
1444 Designator.addUnsizedArrayUnchecked(ElemTy);
1445 }
George Burgess IVe3763372016-12-22 02:50:20 +00001446 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001447 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001448 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1449 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001450 }
Richard Smith66c96992012-02-18 22:04:06 +00001451 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001452 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1453 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001454 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001455 void clearIsNullPointer() {
1456 IsNullPtr = false;
1457 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001458 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1459 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001460 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1461 // but we're not required to diagnose it and it's valid in C++.)
1462 if (!Index)
1463 return;
1464
1465 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1466 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1467 // offsets.
1468 uint64_t Offset64 = Offset.getQuantity();
1469 uint64_t ElemSize64 = ElementSize.getQuantity();
1470 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1471 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1472
1473 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001474 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001475 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001476 }
1477 void adjustOffset(CharUnits N) {
1478 Offset += N;
1479 if (N.getQuantity())
1480 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001481 }
John McCall45d55e42010-05-07 21:00:08 +00001482 };
Richard Smith027bf112011-11-17 22:56:20 +00001483
1484 struct MemberPtr {
1485 MemberPtr() {}
1486 explicit MemberPtr(const ValueDecl *Decl) :
1487 DeclAndIsDerivedMember(Decl, false), Path() {}
1488
1489 /// The member or (direct or indirect) field referred to by this member
1490 /// pointer, or 0 if this is a null member pointer.
1491 const ValueDecl *getDecl() const {
1492 return DeclAndIsDerivedMember.getPointer();
1493 }
1494 /// Is this actually a member of some type derived from the relevant class?
1495 bool isDerivedMember() const {
1496 return DeclAndIsDerivedMember.getInt();
1497 }
1498 /// Get the class which the declaration actually lives in.
1499 const CXXRecordDecl *getContainingRecord() const {
1500 return cast<CXXRecordDecl>(
1501 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1502 }
1503
Richard Smith2e312c82012-03-03 22:46:17 +00001504 void moveInto(APValue &V) const {
1505 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001506 }
Richard Smith2e312c82012-03-03 22:46:17 +00001507 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001508 assert(V.isMemberPointer());
1509 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1510 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1511 Path.clear();
1512 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1513 Path.insert(Path.end(), P.begin(), P.end());
1514 }
1515
1516 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1517 /// whether the member is a member of some class derived from the class type
1518 /// of the member pointer.
1519 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1520 /// Path - The path of base/derived classes from the member declaration's
1521 /// class (exclusive) to the class type of the member pointer (inclusive).
1522 SmallVector<const CXXRecordDecl*, 4> Path;
1523
1524 /// Perform a cast towards the class of the Decl (either up or down the
1525 /// hierarchy).
1526 bool castBack(const CXXRecordDecl *Class) {
1527 assert(!Path.empty());
1528 const CXXRecordDecl *Expected;
1529 if (Path.size() >= 2)
1530 Expected = Path[Path.size() - 2];
1531 else
1532 Expected = getContainingRecord();
1533 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1534 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1535 // if B does not contain the original member and is not a base or
1536 // derived class of the class containing the original member, the result
1537 // of the cast is undefined.
1538 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1539 // (D::*). We consider that to be a language defect.
1540 return false;
1541 }
1542 Path.pop_back();
1543 return true;
1544 }
1545 /// Perform a base-to-derived member pointer cast.
1546 bool castToDerived(const CXXRecordDecl *Derived) {
1547 if (!getDecl())
1548 return true;
1549 if (!isDerivedMember()) {
1550 Path.push_back(Derived);
1551 return true;
1552 }
1553 if (!castBack(Derived))
1554 return false;
1555 if (Path.empty())
1556 DeclAndIsDerivedMember.setInt(false);
1557 return true;
1558 }
1559 /// Perform a derived-to-base member pointer cast.
1560 bool castToBase(const CXXRecordDecl *Base) {
1561 if (!getDecl())
1562 return true;
1563 if (Path.empty())
1564 DeclAndIsDerivedMember.setInt(true);
1565 if (isDerivedMember()) {
1566 Path.push_back(Base);
1567 return true;
1568 }
1569 return castBack(Base);
1570 }
1571 };
Richard Smith357362d2011-12-13 06:39:58 +00001572
Richard Smith7bb00672012-02-01 01:42:44 +00001573 /// Compare two member pointers, which are assumed to be of the same type.
1574 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1575 if (!LHS.getDecl() || !RHS.getDecl())
1576 return !LHS.getDecl() && !RHS.getDecl();
1577 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1578 return false;
1579 return LHS.Path == RHS.Path;
1580 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001581}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001582
Richard Smith2e312c82012-03-03 22:46:17 +00001583static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001584static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1585 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001586 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001587static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1588 bool InvalidBaseOK = false);
1589static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1590 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001591static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1592 EvalInfo &Info);
1593static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001594static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001595static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001596 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001597static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001598static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001599static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1600 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001601static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001602
1603//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001604// Misc utilities
1605//===----------------------------------------------------------------------===//
1606
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001607/// A helper function to create a temporary and set an LValue.
1608template <class KeyTy>
1609static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1610 LValue &LV, CallStackFrame &Frame) {
1611 LV.set({Key, Frame.Info.CurrentCall->Index,
1612 Frame.Info.CurrentCall->getTempVersion()});
1613 return Frame.createTemporary(Key, IsLifetimeExtended);
1614}
1615
Richard Smithd6cc1982017-01-31 02:23:02 +00001616/// Negate an APSInt in place, converting it to a signed form if necessary, and
1617/// preserving its value (by extending by up to one bit as needed).
1618static void negateAsSigned(APSInt &Int) {
1619 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1620 Int = Int.extend(Int.getBitWidth() + 1);
1621 Int.setIsSigned(true);
1622 }
1623 Int = -Int;
1624}
1625
Richard Smith84401042013-06-03 05:03:02 +00001626/// Produce a string describing the given constexpr call.
1627static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1628 unsigned ArgIndex = 0;
1629 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1630 !isa<CXXConstructorDecl>(Frame->Callee) &&
1631 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1632
1633 if (!IsMemberCall)
1634 Out << *Frame->Callee << '(';
1635
1636 if (Frame->This && IsMemberCall) {
1637 APValue Val;
1638 Frame->This->moveInto(Val);
1639 Val.printPretty(Out, Frame->Info.Ctx,
1640 Frame->This->Designator.MostDerivedType);
1641 // FIXME: Add parens around Val if needed.
1642 Out << "->" << *Frame->Callee << '(';
1643 IsMemberCall = false;
1644 }
1645
1646 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1647 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1648 if (ArgIndex > (unsigned)IsMemberCall)
1649 Out << ", ";
1650
1651 const ParmVarDecl *Param = *I;
1652 const APValue &Arg = Frame->Arguments[ArgIndex];
1653 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1654
1655 if (ArgIndex == 0 && IsMemberCall)
1656 Out << "->" << *Frame->Callee << '(';
1657 }
1658
1659 Out << ')';
1660}
1661
Richard Smithd9f663b2013-04-22 15:31:51 +00001662/// Evaluate an expression to see if it had side-effects, and discard its
1663/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001664/// \return \c true if the caller should keep evaluating.
1665static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001666 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001667 if (!Evaluate(Scratch, Info, E))
1668 // We don't need the value, but we might have skipped a side effect here.
1669 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001670 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001671}
1672
Richard Smithd62306a2011-11-10 06:34:14 +00001673/// Should this call expression be treated as a string literal?
1674static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001675 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001676 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1677 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1678}
1679
Richard Smithce40ad62011-11-12 22:28:03 +00001680static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001681 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1682 // constant expression of pointer type that evaluates to...
1683
1684 // ... a null pointer value, or a prvalue core constant expression of type
1685 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001686 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001687
Richard Smithce40ad62011-11-12 22:28:03 +00001688 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1689 // ... the address of an object with static storage duration,
1690 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1691 return VD->hasGlobalStorage();
1692 // ... the address of a function,
1693 return isa<FunctionDecl>(D);
1694 }
1695
1696 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001697 switch (E->getStmtClass()) {
1698 default:
1699 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001700 case Expr::CompoundLiteralExprClass: {
1701 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1702 return CLE->isFileScope() && CLE->isLValue();
1703 }
Richard Smithe6c01442013-06-05 00:46:14 +00001704 case Expr::MaterializeTemporaryExprClass:
1705 // A materialized temporary might have been lifetime-extended to static
1706 // storage duration.
1707 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001708 // A string literal has static storage duration.
1709 case Expr::StringLiteralClass:
1710 case Expr::PredefinedExprClass:
1711 case Expr::ObjCStringLiteralClass:
1712 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001713 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001714 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001715 return true;
1716 case Expr::CallExprClass:
1717 return IsStringLiteralCall(cast<CallExpr>(E));
1718 // For GCC compatibility, &&label has static storage duration.
1719 case Expr::AddrLabelExprClass:
1720 return true;
1721 // A Block literal expression may be used as the initialization value for
1722 // Block variables at global or local static scope.
1723 case Expr::BlockExprClass:
1724 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001725 case Expr::ImplicitValueInitExprClass:
1726 // FIXME:
1727 // We can never form an lvalue with an implicit value initialization as its
1728 // base through expression evaluation, so these only appear in one case: the
1729 // implicit variable declaration we invent when checking whether a constexpr
1730 // constructor can produce a constant expression. We must assume that such
1731 // an expression might be a global lvalue.
1732 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001733 }
John McCall95007602010-05-10 23:27:23 +00001734}
1735
Richard Smith06f71b52018-08-04 00:57:17 +00001736static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1737 return LVal.Base.dyn_cast<const ValueDecl*>();
1738}
1739
1740static bool IsLiteralLValue(const LValue &Value) {
1741 if (Value.getLValueCallIndex())
1742 return false;
1743 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1744 return E && !isa<MaterializeTemporaryExpr>(E);
1745}
1746
1747static bool IsWeakLValue(const LValue &Value) {
1748 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1749 return Decl && Decl->isWeak();
1750}
1751
1752static bool isZeroSized(const LValue &Value) {
1753 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1754 if (Decl && isa<VarDecl>(Decl)) {
1755 QualType Ty = Decl->getType();
1756 if (Ty->isArrayType())
1757 return Ty->isIncompleteType() ||
1758 Decl->getASTContext().getTypeSize(Ty) == 0;
1759 }
1760 return false;
1761}
1762
1763static bool HasSameBase(const LValue &A, const LValue &B) {
1764 if (!A.getLValueBase())
1765 return !B.getLValueBase();
1766 if (!B.getLValueBase())
1767 return false;
1768
1769 if (A.getLValueBase().getOpaqueValue() !=
1770 B.getLValueBase().getOpaqueValue()) {
1771 const Decl *ADecl = GetLValueBaseDecl(A);
1772 if (!ADecl)
1773 return false;
1774 const Decl *BDecl = GetLValueBaseDecl(B);
1775 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1776 return false;
1777 }
1778
1779 return IsGlobalLValue(A.getLValueBase()) ||
1780 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1781 A.getLValueVersion() == B.getLValueVersion());
1782}
1783
Richard Smithb228a862012-02-15 02:18:13 +00001784static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1785 assert(Base && "no location for a null lvalue");
1786 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1787 if (VD)
1788 Info.Note(VD->getLocation(), diag::note_declared_at);
1789 else
Ted Kremenek28831752012-08-23 20:46:57 +00001790 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001791 diag::note_constexpr_temporary_here);
1792}
1793
Richard Smith80815602011-11-07 05:07:52 +00001794/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001795/// value for an address or reference constant expression. Return true if we
1796/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001797static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001798 QualType Type, const LValue &LVal,
1799 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001800 bool IsReferenceType = Type->isReferenceType();
1801
Richard Smith357362d2011-12-13 06:39:58 +00001802 APValue::LValueBase Base = LVal.getLValueBase();
1803 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1804
Richard Smith0dea49e2012-02-18 04:58:18 +00001805 // Check that the object is a global. Note that the fake 'this' object we
1806 // manufacture when checking potential constant expressions is conservatively
1807 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001808 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001809 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001810 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001811 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001812 << IsReferenceType << !Designator.Entries.empty()
1813 << !!VD << VD;
1814 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001815 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001816 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001817 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001818 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001819 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001820 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001821 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001822 LVal.getLValueCallIndex() == 0) &&
1823 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001824
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001825 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1826 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001827 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001828 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001829 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001830
Hans Wennborg82dd8772014-06-25 22:19:48 +00001831 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001832 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001833 return false;
1834 }
1835 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1836 // __declspec(dllimport) must be handled very carefully:
1837 // We must never initialize an expression with the thunk in C++.
1838 // Doing otherwise would allow the same id-expression to yield
1839 // different addresses for the same function in different translation
1840 // units. However, this means that we must dynamically initialize the
1841 // expression with the contents of the import address table at runtime.
1842 //
1843 // The C language has no notion of ODR; furthermore, it has no notion of
1844 // dynamic initialization. This means that we are permitted to
1845 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001846 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1847 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001848 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001849 }
1850 }
1851
Richard Smitha8105bc2012-01-06 16:39:00 +00001852 // Allow address constant expressions to be past-the-end pointers. This is
1853 // an extension: the standard requires them to point to an object.
1854 if (!IsReferenceType)
1855 return true;
1856
1857 // A reference constant expression must refer to an object.
1858 if (!Base) {
1859 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001860 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001861 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001862 }
1863
Richard Smith357362d2011-12-13 06:39:58 +00001864 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001865 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001866 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001867 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001868 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001869 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001870 }
1871
Richard Smith80815602011-11-07 05:07:52 +00001872 return true;
1873}
1874
Reid Klecknercd016d82017-07-07 22:04:29 +00001875/// Member pointers are constant expressions unless they point to a
1876/// non-virtual dllimport member function.
1877static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1878 SourceLocation Loc,
1879 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001880 const APValue &Value,
1881 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00001882 const ValueDecl *Member = Value.getMemberPointerDecl();
1883 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1884 if (!FD)
1885 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001886 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1887 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00001888}
1889
Richard Smithfddd3842011-12-30 21:15:51 +00001890/// Check that this core constant expression is of literal type, and if not,
1891/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001892static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001893 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001894 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001895 return true;
1896
Richard Smith7525ff62013-05-09 07:14:00 +00001897 // C++1y: A constant initializer for an object o [...] may also invoke
1898 // constexpr constructors for o and its subobjects even if those objects
1899 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001900 //
1901 // C++11 missed this detail for aggregates, so classes like this:
1902 // struct foo_t { union { int i; volatile int j; } u; };
1903 // are not (obviously) initializable like so:
1904 // __attribute__((__require_constant_initialization__))
1905 // static const foo_t x = {{0}};
1906 // because "i" is a subobject with non-literal initialization (due to the
1907 // volatile member of the union). See:
1908 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1909 // Therefore, we use the C++1y behavior.
1910 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001911 return true;
1912
Richard Smithfddd3842011-12-30 21:15:51 +00001913 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001914 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001915 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001916 << E->getType();
1917 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001918 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001919 return false;
1920}
1921
Richard Smith0b0a0b62011-10-29 20:57:55 +00001922/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001923/// constant expression. If not, report an appropriate diagnostic. Does not
1924/// check that the expression is of literal type.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001925static bool
1926CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1927 const APValue &Value,
1928 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
Richard Smith1a90f592013-06-18 17:51:51 +00001929 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001930 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001931 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001932 return false;
1933 }
1934
Richard Smith77be48a2014-07-31 06:31:19 +00001935 // We allow _Atomic(T) to be initialized from anything that T can be
1936 // initialized from.
1937 if (const AtomicType *AT = Type->getAs<AtomicType>())
1938 Type = AT->getValueType();
1939
Richard Smithb228a862012-02-15 02:18:13 +00001940 // Core issue 1454: For a literal constant expression of array or class type,
1941 // each subobject of its value shall have been initialized by a constant
1942 // expression.
1943 if (Value.isArray()) {
1944 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1945 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1946 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001947 Value.getArrayInitializedElt(I), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001948 return false;
1949 }
1950 if (!Value.hasArrayFiller())
1951 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001952 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1953 Usage);
Richard Smith80815602011-11-07 05:07:52 +00001954 }
Richard Smithb228a862012-02-15 02:18:13 +00001955 if (Value.isUnion() && Value.getUnionField()) {
1956 return CheckConstantExpression(Info, DiagLoc,
1957 Value.getUnionField()->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001958 Value.getUnionValue(), Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001959 }
1960 if (Value.isStruct()) {
1961 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1962 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1963 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001964 for (const CXXBaseSpecifier &BS : CD->bases()) {
1965 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
1966 Value.getStructBase(BaseIndex), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001967 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001968 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00001969 }
1970 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001971 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001972 if (I->isUnnamedBitfield())
1973 continue;
1974
David Blaikie2d7c57e2012-04-30 02:36:29 +00001975 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001976 Value.getStructField(I->getFieldIndex()),
1977 Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001978 return false;
1979 }
1980 }
1981
1982 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001983 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001984 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00001985 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001986 }
1987
Reid Klecknercd016d82017-07-07 22:04:29 +00001988 if (Value.isMemberPointer())
Reid Kleckner1a840d22018-05-10 18:57:35 +00001989 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00001990
Richard Smithb228a862012-02-15 02:18:13 +00001991 // Everything else is fine.
1992 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001993}
1994
Richard Smith2e312c82012-03-03 22:46:17 +00001995static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001996 // A null base expression indicates a null pointer. These are always
1997 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001998 if (!Value.getLValueBase()) {
1999 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002000 return true;
2001 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002002
Richard Smith027bf112011-11-17 22:56:20 +00002003 // We have a non-null base. These are generally known to be true, but if it's
2004 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002005 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002006 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002007 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002008}
2009
Richard Smith2e312c82012-03-03 22:46:17 +00002010static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002011 switch (Val.getKind()) {
2012 case APValue::Uninitialized:
2013 return false;
2014 case APValue::Int:
2015 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002016 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002017 case APValue::Float:
2018 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002019 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002020 case APValue::ComplexInt:
2021 Result = Val.getComplexIntReal().getBoolValue() ||
2022 Val.getComplexIntImag().getBoolValue();
2023 return true;
2024 case APValue::ComplexFloat:
2025 Result = !Val.getComplexFloatReal().isZero() ||
2026 !Val.getComplexFloatImag().isZero();
2027 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002028 case APValue::LValue:
2029 return EvalPointerValueAsBool(Val, Result);
2030 case APValue::MemberPointer:
2031 Result = Val.getMemberPointerDecl();
2032 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002033 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002034 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002035 case APValue::Struct:
2036 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002037 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002038 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002039 }
2040
Richard Smith11562c52011-10-28 17:51:58 +00002041 llvm_unreachable("unknown APValue kind");
2042}
2043
2044static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2045 EvalInfo &Info) {
2046 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002047 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002048 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002049 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002050 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002051}
2052
Richard Smith357362d2011-12-13 06:39:58 +00002053template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002054static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002055 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002056 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002057 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002058 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002059}
2060
2061static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2062 QualType SrcType, const APFloat &Value,
2063 QualType DestType, APSInt &Result) {
2064 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002065 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002066 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002067
Richard Smith357362d2011-12-13 06:39:58 +00002068 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002069 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002070 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2071 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002072 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002073 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002074}
2075
Richard Smith357362d2011-12-13 06:39:58 +00002076static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2077 QualType SrcType, QualType DestType,
2078 APFloat &Result) {
2079 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002080 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002081 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2082 APFloat::rmNearestTiesToEven, &ignored)
2083 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002084 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002085 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002086}
2087
Richard Smith911e1422012-01-30 22:27:01 +00002088static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2089 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002090 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002091 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002092 APSInt Result = Value;
2093 // Figure out if this is a truncate, extend or noop cast.
2094 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00002095 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002096 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002097 return Result;
2098}
2099
Richard Smith357362d2011-12-13 06:39:58 +00002100static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2101 QualType SrcType, const APSInt &Value,
2102 QualType DestType, APFloat &Result) {
2103 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2104 if (Result.convertFromAPInt(Value, Value.isSigned(),
2105 APFloat::rmNearestTiesToEven)
2106 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002107 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002108 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002109}
2110
Richard Smith49ca8aa2013-08-06 07:09:20 +00002111static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2112 APValue &Value, const FieldDecl *FD) {
2113 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2114
2115 if (!Value.isInt()) {
2116 // Trying to store a pointer-cast-to-integer into a bitfield.
2117 // FIXME: In this case, we should provide the diagnostic for casting
2118 // a pointer to an integer.
2119 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002120 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002121 return false;
2122 }
2123
2124 APSInt &Int = Value.getInt();
2125 unsigned OldBitWidth = Int.getBitWidth();
2126 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2127 if (NewBitWidth < OldBitWidth)
2128 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2129 return true;
2130}
2131
Eli Friedman803acb32011-12-22 03:51:45 +00002132static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2133 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002134 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002135 if (!Evaluate(SVal, Info, E))
2136 return false;
2137 if (SVal.isInt()) {
2138 Res = SVal.getInt();
2139 return true;
2140 }
2141 if (SVal.isFloat()) {
2142 Res = SVal.getFloat().bitcastToAPInt();
2143 return true;
2144 }
2145 if (SVal.isVector()) {
2146 QualType VecTy = E->getType();
2147 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2148 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2149 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2150 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2151 Res = llvm::APInt::getNullValue(VecSize);
2152 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2153 APValue &Elt = SVal.getVectorElt(i);
2154 llvm::APInt EltAsInt;
2155 if (Elt.isInt()) {
2156 EltAsInt = Elt.getInt();
2157 } else if (Elt.isFloat()) {
2158 EltAsInt = Elt.getFloat().bitcastToAPInt();
2159 } else {
2160 // Don't try to handle vectors of anything other than int or float
2161 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002162 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002163 return false;
2164 }
2165 unsigned BaseEltSize = EltAsInt.getBitWidth();
2166 if (BigEndian)
2167 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2168 else
2169 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2170 }
2171 return true;
2172 }
2173 // Give up if the input isn't an int, float, or vector. For example, we
2174 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002175 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002176 return false;
2177}
2178
Richard Smith43e77732013-05-07 04:50:00 +00002179/// Perform the given integer operation, which is known to need at most BitWidth
2180/// bits, and check for overflow in the original type (if that type was not an
2181/// unsigned type).
2182template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002183static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2184 const APSInt &LHS, const APSInt &RHS,
2185 unsigned BitWidth, Operation Op,
2186 APSInt &Result) {
2187 if (LHS.isUnsigned()) {
2188 Result = Op(LHS, RHS);
2189 return true;
2190 }
Richard Smith43e77732013-05-07 04:50:00 +00002191
2192 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002193 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002194 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002195 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002196 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002197 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002198 << Result.toString(10) << E->getType();
2199 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002200 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002201 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002202 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002203}
2204
2205/// Perform the given binary integer operation.
2206static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2207 BinaryOperatorKind Opcode, APSInt RHS,
2208 APSInt &Result) {
2209 switch (Opcode) {
2210 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002211 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002212 return false;
2213 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002214 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2215 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002216 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002217 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2218 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002219 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002220 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2221 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002222 case BO_And: Result = LHS & RHS; return true;
2223 case BO_Xor: Result = LHS ^ RHS; return true;
2224 case BO_Or: Result = LHS | RHS; return true;
2225 case BO_Div:
2226 case BO_Rem:
2227 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002228 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002229 return false;
2230 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002231 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2232 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2233 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002234 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2235 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002236 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2237 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002238 return true;
2239 case BO_Shl: {
2240 if (Info.getLangOpts().OpenCL)
2241 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2242 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2243 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2244 RHS.isUnsigned());
2245 else if (RHS.isSigned() && RHS.isNegative()) {
2246 // During constant-folding, a negative shift is an opposite shift. Such
2247 // a shift is not a constant expression.
2248 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2249 RHS = -RHS;
2250 goto shift_right;
2251 }
2252 shift_left:
2253 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2254 // the shifted type.
2255 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2256 if (SA != RHS) {
2257 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2258 << RHS << E->getType() << LHS.getBitWidth();
2259 } else if (LHS.isSigned()) {
2260 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2261 // operand, and must not overflow the corresponding unsigned type.
2262 if (LHS.isNegative())
2263 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2264 else if (LHS.countLeadingZeros() < SA)
2265 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2266 }
2267 Result = LHS << SA;
2268 return true;
2269 }
2270 case BO_Shr: {
2271 if (Info.getLangOpts().OpenCL)
2272 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2273 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2274 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2275 RHS.isUnsigned());
2276 else if (RHS.isSigned() && RHS.isNegative()) {
2277 // During constant-folding, a negative shift is an opposite shift. Such a
2278 // shift is not a constant expression.
2279 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2280 RHS = -RHS;
2281 goto shift_left;
2282 }
2283 shift_right:
2284 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2285 // shifted type.
2286 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2287 if (SA != RHS)
2288 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2289 << RHS << E->getType() << LHS.getBitWidth();
2290 Result = LHS >> SA;
2291 return true;
2292 }
2293
2294 case BO_LT: Result = LHS < RHS; return true;
2295 case BO_GT: Result = LHS > RHS; return true;
2296 case BO_LE: Result = LHS <= RHS; return true;
2297 case BO_GE: Result = LHS >= RHS; return true;
2298 case BO_EQ: Result = LHS == RHS; return true;
2299 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002300 case BO_Cmp:
2301 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002302 }
2303}
2304
Richard Smith861b5b52013-05-07 23:34:45 +00002305/// Perform the given binary floating-point operation, in-place, on LHS.
2306static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2307 APFloat &LHS, BinaryOperatorKind Opcode,
2308 const APFloat &RHS) {
2309 switch (Opcode) {
2310 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002311 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002312 return false;
2313 case BO_Mul:
2314 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2315 break;
2316 case BO_Add:
2317 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2318 break;
2319 case BO_Sub:
2320 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2321 break;
2322 case BO_Div:
2323 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2324 break;
2325 }
2326
Richard Smith0c6124b2015-12-03 01:36:22 +00002327 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002328 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002329 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002330 }
Richard Smith861b5b52013-05-07 23:34:45 +00002331 return true;
2332}
2333
Richard Smitha8105bc2012-01-06 16:39:00 +00002334/// Cast an lvalue referring to a base subobject to a derived class, by
2335/// truncating the lvalue's path to the given length.
2336static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2337 const RecordDecl *TruncatedType,
2338 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002339 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002340
2341 // Check we actually point to a derived class object.
2342 if (TruncatedElements == D.Entries.size())
2343 return true;
2344 assert(TruncatedElements >= D.MostDerivedPathLength &&
2345 "not casting to a derived class");
2346 if (!Result.checkSubobject(Info, E, CSK_Derived))
2347 return false;
2348
2349 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002350 const RecordDecl *RD = TruncatedType;
2351 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002352 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002353 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2354 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002355 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002356 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002357 else
Richard Smithd62306a2011-11-10 06:34:14 +00002358 Result.Offset -= Layout.getBaseClassOffset(Base);
2359 RD = Base;
2360 }
Richard Smith027bf112011-11-17 22:56:20 +00002361 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002362 return true;
2363}
2364
John McCalld7bca762012-05-01 00:38:49 +00002365static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002366 const CXXRecordDecl *Derived,
2367 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002368 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002369 if (!RL) {
2370 if (Derived->isInvalidDecl()) return false;
2371 RL = &Info.Ctx.getASTRecordLayout(Derived);
2372 }
2373
Richard Smithd62306a2011-11-10 06:34:14 +00002374 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002375 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002376 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002377}
2378
Richard Smitha8105bc2012-01-06 16:39:00 +00002379static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002380 const CXXRecordDecl *DerivedDecl,
2381 const CXXBaseSpecifier *Base) {
2382 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2383
John McCalld7bca762012-05-01 00:38:49 +00002384 if (!Base->isVirtual())
2385 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002386
Richard Smitha8105bc2012-01-06 16:39:00 +00002387 SubobjectDesignator &D = Obj.Designator;
2388 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002389 return false;
2390
Richard Smitha8105bc2012-01-06 16:39:00 +00002391 // Extract most-derived object and corresponding type.
2392 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2393 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2394 return false;
2395
2396 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002397 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002398 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2399 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002400 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002401 return true;
2402}
2403
Richard Smith84401042013-06-03 05:03:02 +00002404static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2405 QualType Type, LValue &Result) {
2406 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2407 PathE = E->path_end();
2408 PathI != PathE; ++PathI) {
2409 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2410 *PathI))
2411 return false;
2412 Type = (*PathI)->getType();
2413 }
2414 return true;
2415}
2416
Richard Smithd62306a2011-11-10 06:34:14 +00002417/// Update LVal to refer to the given field, which must be a member of the type
2418/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002419static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002420 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002421 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002422 if (!RL) {
2423 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002424 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002425 }
Richard Smithd62306a2011-11-10 06:34:14 +00002426
2427 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002428 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002429 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002430 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002431}
2432
Richard Smith1b78b3d2012-01-25 22:15:11 +00002433/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002434static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002435 LValue &LVal,
2436 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002437 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002438 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002439 return false;
2440 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002441}
2442
Richard Smithd62306a2011-11-10 06:34:14 +00002443/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002444static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2445 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002446 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2447 // extension.
2448 if (Type->isVoidType() || Type->isFunctionType()) {
2449 Size = CharUnits::One();
2450 return true;
2451 }
2452
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002453 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002454 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002455 return false;
2456 }
2457
Richard Smithd62306a2011-11-10 06:34:14 +00002458 if (!Type->isConstantSizeType()) {
2459 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002460 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002461 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002462 return false;
2463 }
2464
2465 Size = Info.Ctx.getTypeSizeInChars(Type);
2466 return true;
2467}
2468
2469/// Update a pointer value to model pointer arithmetic.
2470/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002471/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002472/// \param LVal - The pointer value to be updated.
2473/// \param EltTy - The pointee type represented by LVal.
2474/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002475static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2476 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002477 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002478 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002479 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002480 return false;
2481
Yaxun Liu402804b2016-12-15 08:09:08 +00002482 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002483 return true;
2484}
2485
Richard Smithd6cc1982017-01-31 02:23:02 +00002486static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2487 LValue &LVal, QualType EltTy,
2488 int64_t Adjustment) {
2489 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2490 APSInt::get(Adjustment));
2491}
2492
Richard Smith66c96992012-02-18 22:04:06 +00002493/// Update an lvalue to refer to a component of a complex number.
2494/// \param Info - Information about the ongoing evaluation.
2495/// \param LVal - The lvalue to be updated.
2496/// \param EltTy - The complex number's component type.
2497/// \param Imag - False for the real component, true for the imaginary.
2498static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2499 LValue &LVal, QualType EltTy,
2500 bool Imag) {
2501 if (Imag) {
2502 CharUnits SizeOfComponent;
2503 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2504 return false;
2505 LVal.Offset += SizeOfComponent;
2506 }
2507 LVal.addComplex(Info, E, EltTy, Imag);
2508 return true;
2509}
2510
Faisal Vali051e3a22017-02-16 04:12:21 +00002511static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2512 QualType Type, const LValue &LVal,
2513 APValue &RVal);
2514
Richard Smith27908702011-10-24 17:54:18 +00002515/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002516///
2517/// \param Info Information about the ongoing evaluation.
2518/// \param E An expression to be used when printing diagnostics.
2519/// \param VD The variable whose initializer should be obtained.
2520/// \param Frame The frame in which the variable was created. Must be null
2521/// if this variable is not local to the evaluation.
2522/// \param Result Filled in with a pointer to the value of the variable.
2523static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2524 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002525 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002526
Richard Smith254a73d2011-10-28 22:34:42 +00002527 // If this is a parameter to an active constexpr function call, perform
2528 // argument substitution.
2529 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002530 // Assume arguments of a potential constant expression are unknown
2531 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002532 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002533 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002534 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002535 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002536 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002537 }
Richard Smith3229b742013-05-05 21:17:10 +00002538 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002539 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002540 }
Richard Smith27908702011-10-24 17:54:18 +00002541
Richard Smithd9f663b2013-04-22 15:31:51 +00002542 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002543 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002544 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2545 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002546 if (!Result) {
2547 // Assume variables referenced within a lambda's call operator that were
2548 // not declared within the call operator are captures and during checking
2549 // of a potential constant expression, assume they are unknown constant
2550 // expressions.
2551 assert(isLambdaCallOperator(Frame->Callee) &&
2552 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2553 "missing value for local variable");
2554 if (Info.checkingPotentialConstantExpression())
2555 return false;
2556 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002557 Info.FFDiag(E->getBeginLoc(),
2558 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002559 << "captures not currently allowed";
2560 return false;
2561 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002562 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002563 }
2564
Richard Smithd0b4dd62011-12-19 06:19:21 +00002565 // Dig out the initializer, and use the declaration which it's attached to.
2566 const Expr *Init = VD->getAnyInitializer(VD);
2567 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002568 // If we're checking a potential constant expression, the variable could be
2569 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002570 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002571 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002572 return false;
2573 }
2574
Richard Smithd62306a2011-11-10 06:34:14 +00002575 // If we're currently evaluating the initializer of this declaration, use that
2576 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002577 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002578 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002579 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002580 }
2581
Richard Smithcecf1842011-11-01 21:06:14 +00002582 // Never evaluate the initializer of a weak variable. We can't be sure that
2583 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002584 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002585 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002586 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002587 }
Richard Smithcecf1842011-11-01 21:06:14 +00002588
Richard Smithd0b4dd62011-12-19 06:19:21 +00002589 // Check that we can fold the initializer. In C++, we will have already done
2590 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002591 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002592 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002593 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002594 Notes.size() + 1) << VD;
2595 Info.Note(VD->getLocation(), diag::note_declared_at);
2596 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002597 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002598 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002599 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002600 Notes.size() + 1) << VD;
2601 Info.Note(VD->getLocation(), diag::note_declared_at);
2602 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002603 }
Richard Smith27908702011-10-24 17:54:18 +00002604
Richard Smith3229b742013-05-05 21:17:10 +00002605 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002606 return true;
Richard Smith27908702011-10-24 17:54:18 +00002607}
2608
Richard Smith11562c52011-10-28 17:51:58 +00002609static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002610 Qualifiers Quals = T.getQualifiers();
2611 return Quals.hasConst() && !Quals.hasVolatile();
2612}
2613
Richard Smithe97cbd72011-11-11 04:05:33 +00002614/// Get the base index of the given base class within an APValue representing
2615/// the given derived class.
2616static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2617 const CXXRecordDecl *Base) {
2618 Base = Base->getCanonicalDecl();
2619 unsigned Index = 0;
2620 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2621 E = Derived->bases_end(); I != E; ++I, ++Index) {
2622 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2623 return Index;
2624 }
2625
2626 llvm_unreachable("base class missing from derived class's bases list");
2627}
2628
Richard Smith3da88fa2013-04-26 14:36:30 +00002629/// Extract the value of a character from a string literal.
2630static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2631 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002632 // FIXME: Support MakeStringConstant
2633 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2634 std::string Str;
2635 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2636 assert(Index <= Str.size() && "Index too large");
2637 return APSInt::getUnsigned(Str.c_str()[Index]);
2638 }
2639
Alexey Bataevec474782014-10-09 08:45:04 +00002640 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2641 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002642 const StringLiteral *S = cast<StringLiteral>(Lit);
2643 const ConstantArrayType *CAT =
2644 Info.Ctx.getAsConstantArrayType(S->getType());
2645 assert(CAT && "string literal isn't an array");
2646 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002647 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002648
2649 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002650 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002651 if (Index < S->getLength())
2652 Value = S->getCodeUnit(Index);
2653 return Value;
2654}
2655
Richard Smith3da88fa2013-04-26 14:36:30 +00002656// Expand a string literal into an array of characters.
2657static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2658 APValue &Result) {
2659 const StringLiteral *S = cast<StringLiteral>(Lit);
2660 const ConstantArrayType *CAT =
2661 Info.Ctx.getAsConstantArrayType(S->getType());
2662 assert(CAT && "string literal isn't an array");
2663 QualType CharType = CAT->getElementType();
2664 assert(CharType->isIntegerType() && "unexpected character type");
2665
2666 unsigned Elts = CAT->getSize().getZExtValue();
2667 Result = APValue(APValue::UninitArray(),
2668 std::min(S->getLength(), Elts), Elts);
2669 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2670 CharType->isUnsignedIntegerType());
2671 if (Result.hasArrayFiller())
2672 Result.getArrayFiller() = APValue(Value);
2673 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2674 Value = S->getCodeUnit(I);
2675 Result.getArrayInitializedElt(I) = APValue(Value);
2676 }
2677}
2678
2679// Expand an array so that it has more than Index filled elements.
2680static void expandArray(APValue &Array, unsigned Index) {
2681 unsigned Size = Array.getArraySize();
2682 assert(Index < Size);
2683
2684 // Always at least double the number of elements for which we store a value.
2685 unsigned OldElts = Array.getArrayInitializedElts();
2686 unsigned NewElts = std::max(Index+1, OldElts * 2);
2687 NewElts = std::min(Size, std::max(NewElts, 8u));
2688
2689 // Copy the data across.
2690 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2691 for (unsigned I = 0; I != OldElts; ++I)
2692 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2693 for (unsigned I = OldElts; I != NewElts; ++I)
2694 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2695 if (NewValue.hasArrayFiller())
2696 NewValue.getArrayFiller() = Array.getArrayFiller();
2697 Array.swap(NewValue);
2698}
2699
Richard Smithb01fe402014-09-16 01:24:02 +00002700/// Determine whether a type would actually be read by an lvalue-to-rvalue
2701/// conversion. If it's of class type, we may assume that the copy operation
2702/// is trivial. Note that this is never true for a union type with fields
2703/// (because the copy always "reads" the active member) and always true for
2704/// a non-class type.
2705static bool isReadByLvalueToRvalueConversion(QualType T) {
2706 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2707 if (!RD || (RD->isUnion() && !RD->field_empty()))
2708 return true;
2709 if (RD->isEmpty())
2710 return false;
2711
2712 for (auto *Field : RD->fields())
2713 if (isReadByLvalueToRvalueConversion(Field->getType()))
2714 return true;
2715
2716 for (auto &BaseSpec : RD->bases())
2717 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2718 return true;
2719
2720 return false;
2721}
2722
2723/// Diagnose an attempt to read from any unreadable field within the specified
2724/// type, which might be a class type.
2725static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2726 QualType T) {
2727 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2728 if (!RD)
2729 return false;
2730
2731 if (!RD->hasMutableFields())
2732 return false;
2733
2734 for (auto *Field : RD->fields()) {
2735 // If we're actually going to read this field in some way, then it can't
2736 // be mutable. If we're in a union, then assigning to a mutable field
2737 // (even an empty one) can change the active member, so that's not OK.
2738 // FIXME: Add core issue number for the union case.
2739 if (Field->isMutable() &&
2740 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002741 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002742 Info.Note(Field->getLocation(), diag::note_declared_at);
2743 return true;
2744 }
2745
2746 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2747 return true;
2748 }
2749
2750 for (auto &BaseSpec : RD->bases())
2751 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2752 return true;
2753
2754 // All mutable fields were empty, and thus not actually read.
2755 return false;
2756}
2757
Richard Smith861b5b52013-05-07 23:34:45 +00002758/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002759enum AccessKinds {
2760 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002761 AK_Assign,
2762 AK_Increment,
2763 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002764};
2765
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002766namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002767/// A handle to a complete object (an object that is not a subobject of
2768/// another object).
2769struct CompleteObject {
2770 /// The value of the complete object.
2771 APValue *Value;
2772 /// The type of the complete object.
2773 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002774 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002775
Craig Topper36250ad2014-05-12 05:36:57 +00002776 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002777 CompleteObject(APValue *Value, QualType Type,
2778 bool LifetimeStartedInEvaluation)
2779 : Value(Value), Type(Type),
2780 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002781 assert(Value && "missing value for complete object");
2782 }
2783
Aaron Ballman67347662015-02-15 22:00:28 +00002784 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002785};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002786} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002787
Richard Smith3da88fa2013-04-26 14:36:30 +00002788/// Find the designated sub-object of an rvalue.
2789template<typename SubobjectHandler>
2790typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002791findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002792 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002793 if (Sub.Invalid)
2794 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002795 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002796 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002797 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002798 Info.FFDiag(E, Sub.isOnePastTheEnd()
2799 ? diag::note_constexpr_access_past_end
2800 : diag::note_constexpr_access_unsized_array)
2801 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002802 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002803 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002804 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002805 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002806
Richard Smith3229b742013-05-05 21:17:10 +00002807 APValue *O = Obj.Value;
2808 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002809 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002810 const bool MayReadMutableMembers =
2811 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002812
Richard Smithd62306a2011-11-10 06:34:14 +00002813 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002814 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2815 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002816 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002817 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002818 return handler.failed();
2819 }
2820
Richard Smith49ca8aa2013-08-06 07:09:20 +00002821 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002822 // If we are reading an object of class type, there may still be more
2823 // things we need to check: if there are any mutable subobjects, we
2824 // cannot perform this read. (This only happens when performing a trivial
2825 // copy or assignment.)
2826 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002827 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002828 return handler.failed();
2829
Richard Smith49ca8aa2013-08-06 07:09:20 +00002830 if (!handler.found(*O, ObjType))
2831 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002832
Richard Smith49ca8aa2013-08-06 07:09:20 +00002833 // If we modified a bit-field, truncate it to the right width.
2834 if (handler.AccessKind != AK_Read &&
2835 LastField && LastField->isBitField() &&
2836 !truncateBitfieldValue(Info, E, *O, LastField))
2837 return false;
2838
2839 return true;
2840 }
2841
Craig Topper36250ad2014-05-12 05:36:57 +00002842 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002843 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002844 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002845 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002846 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002847 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002848 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002849 // Note, it should not be possible to form a pointer with a valid
2850 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002851 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002852 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002853 << handler.AccessKind;
2854 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002855 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002856 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002857 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002858
2859 ObjType = CAT->getElementType();
2860
Richard Smith14a94132012-02-17 03:35:37 +00002861 // An array object is represented as either an Array APValue or as an
2862 // LValue which refers to a string literal.
2863 if (O->isLValue()) {
2864 assert(I == N - 1 && "extracting subobject of character?");
2865 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002866 if (handler.AccessKind != AK_Read)
2867 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2868 *O);
2869 else
2870 return handler.foundString(*O, ObjType, Index);
2871 }
2872
2873 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002874 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002875 else if (handler.AccessKind != AK_Read) {
2876 expandArray(*O, Index);
2877 O = &O->getArrayInitializedElt(Index);
2878 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002879 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002880 } else if (ObjType->isAnyComplexType()) {
2881 // Next subobject is a complex number.
2882 uint64_t Index = Sub.Entries[I].ArrayIndex;
2883 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002884 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002885 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002886 << handler.AccessKind;
2887 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002888 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002889 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002890 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002891
2892 bool WasConstQualified = ObjType.isConstQualified();
2893 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2894 if (WasConstQualified)
2895 ObjType.addConst();
2896
Richard Smith66c96992012-02-18 22:04:06 +00002897 assert(I == N - 1 && "extracting subobject of scalar?");
2898 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002899 return handler.found(Index ? O->getComplexIntImag()
2900 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002901 } else {
2902 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002903 return handler.found(Index ? O->getComplexFloatImag()
2904 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002905 }
Richard Smithd62306a2011-11-10 06:34:14 +00002906 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002907 // In C++14 onwards, it is permitted to read a mutable member whose
2908 // lifetime began within the evaluation.
2909 // FIXME: Should we also allow this in C++11?
2910 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2911 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002912 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002913 << Field;
2914 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002915 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002916 }
2917
Richard Smithd62306a2011-11-10 06:34:14 +00002918 // Next subobject is a class, struct or union field.
2919 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2920 if (RD->isUnion()) {
2921 const FieldDecl *UnionField = O->getUnionField();
2922 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002923 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002924 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002925 << handler.AccessKind << Field << !UnionField << UnionField;
2926 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002927 }
Richard Smithd62306a2011-11-10 06:34:14 +00002928 O = &O->getUnionValue();
2929 } else
2930 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002931
2932 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002933 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002934 if (WasConstQualified && !Field->isMutable())
2935 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002936
2937 if (ObjType.isVolatileQualified()) {
2938 if (Info.getLangOpts().CPlusPlus) {
2939 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002940 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002941 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002942 Info.Note(Field->getLocation(), diag::note_declared_at);
2943 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002944 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002945 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002946 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002947 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002948
2949 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002950 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002951 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002952 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2953 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2954 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002955
2956 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002957 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002958 if (WasConstQualified)
2959 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002960 }
2961 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002962}
2963
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002964namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002965struct ExtractSubobjectHandler {
2966 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002967 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002968
2969 static const AccessKinds AccessKind = AK_Read;
2970
2971 typedef bool result_type;
2972 bool failed() { return false; }
2973 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002974 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002975 return true;
2976 }
2977 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002978 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002979 return true;
2980 }
2981 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002982 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002983 return true;
2984 }
2985 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002986 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002987 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2988 return true;
2989 }
2990};
Richard Smith3229b742013-05-05 21:17:10 +00002991} // end anonymous namespace
2992
Richard Smith3da88fa2013-04-26 14:36:30 +00002993const AccessKinds ExtractSubobjectHandler::AccessKind;
2994
2995/// Extract the designated sub-object of an rvalue.
2996static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002997 const CompleteObject &Obj,
2998 const SubobjectDesignator &Sub,
2999 APValue &Result) {
3000 ExtractSubobjectHandler Handler = { Info, Result };
3001 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003002}
3003
Richard Smith3229b742013-05-05 21:17:10 +00003004namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003005struct ModifySubobjectHandler {
3006 EvalInfo &Info;
3007 APValue &NewVal;
3008 const Expr *E;
3009
3010 typedef bool result_type;
3011 static const AccessKinds AccessKind = AK_Assign;
3012
3013 bool checkConst(QualType QT) {
3014 // Assigning to a const object has undefined behavior.
3015 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003016 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003017 return false;
3018 }
3019 return true;
3020 }
3021
3022 bool failed() { return false; }
3023 bool found(APValue &Subobj, QualType SubobjType) {
3024 if (!checkConst(SubobjType))
3025 return false;
3026 // We've been given ownership of NewVal, so just swap it in.
3027 Subobj.swap(NewVal);
3028 return true;
3029 }
3030 bool found(APSInt &Value, QualType SubobjType) {
3031 if (!checkConst(SubobjType))
3032 return false;
3033 if (!NewVal.isInt()) {
3034 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003035 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003036 return false;
3037 }
3038 Value = NewVal.getInt();
3039 return true;
3040 }
3041 bool found(APFloat &Value, QualType SubobjType) {
3042 if (!checkConst(SubobjType))
3043 return false;
3044 Value = NewVal.getFloat();
3045 return true;
3046 }
3047 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3048 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
3049 }
3050};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003051} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003052
Richard Smith3229b742013-05-05 21:17:10 +00003053const AccessKinds ModifySubobjectHandler::AccessKind;
3054
Richard Smith3da88fa2013-04-26 14:36:30 +00003055/// Update the designated sub-object of an rvalue to the given value.
3056static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003057 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003058 const SubobjectDesignator &Sub,
3059 APValue &NewVal) {
3060 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003061 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003062}
3063
Richard Smith84f6dcf2012-02-02 01:16:57 +00003064/// Find the position where two subobject designators diverge, or equivalently
3065/// the length of the common initial subsequence.
3066static unsigned FindDesignatorMismatch(QualType ObjType,
3067 const SubobjectDesignator &A,
3068 const SubobjectDesignator &B,
3069 bool &WasArrayIndex) {
3070 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3071 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003072 if (!ObjType.isNull() &&
3073 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003074 // Next subobject is an array element.
3075 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3076 WasArrayIndex = true;
3077 return I;
3078 }
Richard Smith66c96992012-02-18 22:04:06 +00003079 if (ObjType->isAnyComplexType())
3080 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3081 else
3082 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003083 } else {
3084 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3085 WasArrayIndex = false;
3086 return I;
3087 }
3088 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3089 // Next subobject is a field.
3090 ObjType = FD->getType();
3091 else
3092 // Next subobject is a base class.
3093 ObjType = QualType();
3094 }
3095 }
3096 WasArrayIndex = false;
3097 return I;
3098}
3099
3100/// Determine whether the given subobject designators refer to elements of the
3101/// same array object.
3102static bool AreElementsOfSameArray(QualType ObjType,
3103 const SubobjectDesignator &A,
3104 const SubobjectDesignator &B) {
3105 if (A.Entries.size() != B.Entries.size())
3106 return false;
3107
George Burgess IVa51c4072015-10-16 01:49:01 +00003108 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003109 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3110 // A is a subobject of the array element.
3111 return false;
3112
3113 // If A (and B) designates an array element, the last entry will be the array
3114 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3115 // of length 1' case, and the entire path must match.
3116 bool WasArrayIndex;
3117 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3118 return CommonLength >= A.Entries.size() - IsArray;
3119}
3120
Richard Smith3229b742013-05-05 21:17:10 +00003121/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003122static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3123 AccessKinds AK, const LValue &LVal,
3124 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003125 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003126 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003127 return CompleteObject();
3128 }
3129
Craig Topper36250ad2014-05-12 05:36:57 +00003130 CallStackFrame *Frame = nullptr;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003131 if (LVal.getLValueCallIndex()) {
3132 Frame = Info.getCallFrame(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003133 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003134 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003135 << AK << LVal.Base.is<const ValueDecl*>();
3136 NoteLValueLocation(Info, LVal.Base);
3137 return CompleteObject();
3138 }
Richard Smith3229b742013-05-05 21:17:10 +00003139 }
3140
3141 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3142 // is not a constant expression (even if the object is non-volatile). We also
3143 // apply this rule to C++98, in order to conform to the expected 'volatile'
3144 // semantics.
3145 if (LValType.isVolatileQualified()) {
3146 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003147 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003148 << AK << LValType;
3149 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003150 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003151 return CompleteObject();
3152 }
3153
3154 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003155 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003156 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003157 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003158
3159 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3160 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3161 // In C++11, constexpr, non-volatile variables initialized with constant
3162 // expressions are constant expressions too. Inside constexpr functions,
3163 // parameters are constant expressions even if they're non-const.
3164 // In C++1y, objects local to a constant expression (those with a Frame) are
3165 // both readable and writable inside constant expressions.
3166 // In C, such things can also be folded, although they are not ICEs.
3167 const VarDecl *VD = dyn_cast<VarDecl>(D);
3168 if (VD) {
3169 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3170 VD = VDef;
3171 }
3172 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003173 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003174 return CompleteObject();
3175 }
3176
3177 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003178 if (BaseType.isVolatileQualified()) {
3179 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003180 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003181 << AK << 1 << VD;
3182 Info.Note(VD->getLocation(), diag::note_declared_at);
3183 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003184 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003185 }
3186 return CompleteObject();
3187 }
3188
3189 // Unless we're looking at a local variable or argument in a constexpr call,
3190 // the variable we're reading must be const.
3191 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003192 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003193 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3194 // OK, we can read and modify an object if we're in the process of
3195 // evaluating its initializer, because its lifetime began in this
3196 // evaluation.
3197 } else if (AK != AK_Read) {
3198 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003199 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003200 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003201 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003202 // OK, we can read this variable.
3203 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003204 // In OpenCL if a variable is in constant address space it is a const value.
3205 if (!(BaseType.isConstQualified() ||
3206 (Info.getLangOpts().OpenCL &&
3207 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003208 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003209 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003210 Info.Note(VD->getLocation(), diag::note_declared_at);
3211 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003212 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003213 }
3214 return CompleteObject();
3215 }
3216 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3217 // We support folding of const floating-point types, in order to make
3218 // static const data members of such types (supported as an extension)
3219 // more useful.
3220 if (Info.getLangOpts().CPlusPlus11) {
3221 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3222 Info.Note(VD->getLocation(), diag::note_declared_at);
3223 } else {
3224 Info.CCEDiag(E);
3225 }
George Burgess IVb5316982016-12-27 05:33:20 +00003226 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3227 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3228 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003229 } else {
3230 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003231 if (Info.checkingPotentialConstantExpression() &&
3232 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3233 // The definition of this variable could be constexpr. We can't
3234 // access it right now, but may be able to in future.
3235 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003236 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003237 Info.Note(VD->getLocation(), diag::note_declared_at);
3238 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003239 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003240 }
3241 return CompleteObject();
3242 }
3243 }
3244
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003245 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003246 return CompleteObject();
3247 } else {
3248 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3249
3250 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003251 if (const MaterializeTemporaryExpr *MTE =
3252 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3253 assert(MTE->getStorageDuration() == SD_Static &&
3254 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003255
Richard Smithe6c01442013-06-05 00:46:14 +00003256 // Per C++1y [expr.const]p2:
3257 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3258 // - a [...] glvalue of integral or enumeration type that refers to
3259 // a non-volatile const object [...]
3260 // [...]
3261 // - a [...] glvalue of literal type that refers to a non-volatile
3262 // object whose lifetime began within the evaluation of e.
3263 //
3264 // C++11 misses the 'began within the evaluation of e' check and
3265 // instead allows all temporaries, including things like:
3266 // int &&r = 1;
3267 // int x = ++r;
3268 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003269 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003270 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3271 const ValueDecl *ED = MTE->getExtendingDecl();
3272 if (!(BaseType.isConstQualified() &&
3273 BaseType->isIntegralOrEnumerationType()) &&
3274 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003275 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003276 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3277 return CompleteObject();
3278 }
3279
3280 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3281 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003282 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003283 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003284 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003285 return CompleteObject();
3286 }
3287 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003288 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003289 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003290 }
Richard Smith3229b742013-05-05 21:17:10 +00003291
3292 // Volatile temporary objects cannot be accessed in constant expressions.
3293 if (BaseType.isVolatileQualified()) {
3294 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003295 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003296 << AK << 0;
3297 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3298 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003299 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003300 }
3301 return CompleteObject();
3302 }
3303 }
3304
Richard Smith7525ff62013-05-09 07:14:00 +00003305 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003306 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003307 // object under construction.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003308 if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3309 LVal.getLValueCallIndex(),
3310 LVal.getLValueVersion())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003311 BaseType = Info.Ctx.getCanonicalType(BaseType);
3312 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003313 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003314 }
3315
Richard Smith9defb7d2018-02-21 03:38:30 +00003316 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003317 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003318 //
3319 // FIXME: Not all local state is mutable. Allow local constant subobjects
3320 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003321 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3322 Info.EvalStatus.HasSideEffects) ||
3323 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003324 return CompleteObject();
3325
Richard Smith9defb7d2018-02-21 03:38:30 +00003326 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003327}
3328
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003329/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003330/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3331/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003332///
3333/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003334/// \param Conv - The expression for which we are performing the conversion.
3335/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003336/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3337/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003338/// \param LVal - The glvalue on which we are attempting to perform this action.
3339/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003340static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003341 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003342 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003343 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003344 return false;
3345
Richard Smith3229b742013-05-05 21:17:10 +00003346 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003347 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003348 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003349 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3350 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3351 // initializer until now for such expressions. Such an expression can't be
3352 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003353 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003354 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003355 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003356 }
Richard Smith3229b742013-05-05 21:17:10 +00003357 APValue Lit;
3358 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3359 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003360 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003361 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003362 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003363 // We represent a string literal array as an lvalue pointing at the
3364 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003365 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003366 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smith9defb7d2018-02-21 03:38:30 +00003367 CompleteObject StrObj(&Str, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003368 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003369 }
Richard Smith11562c52011-10-28 17:51:58 +00003370 }
3371
Richard Smith3229b742013-05-05 21:17:10 +00003372 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3373 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003374}
3375
3376/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003377static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003378 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003379 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003380 return false;
3381
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003382 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003383 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003384 return false;
3385 }
3386
Richard Smith3229b742013-05-05 21:17:10 +00003387 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003388 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3389}
3390
3391namespace {
3392struct CompoundAssignSubobjectHandler {
3393 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003394 const Expr *E;
3395 QualType PromotedLHSType;
3396 BinaryOperatorKind Opcode;
3397 const APValue &RHS;
3398
3399 static const AccessKinds AccessKind = AK_Assign;
3400
3401 typedef bool result_type;
3402
3403 bool checkConst(QualType QT) {
3404 // Assigning to a const object has undefined behavior.
3405 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003406 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003407 return false;
3408 }
3409 return true;
3410 }
3411
3412 bool failed() { return false; }
3413 bool found(APValue &Subobj, QualType SubobjType) {
3414 switch (Subobj.getKind()) {
3415 case APValue::Int:
3416 return found(Subobj.getInt(), SubobjType);
3417 case APValue::Float:
3418 return found(Subobj.getFloat(), SubobjType);
3419 case APValue::ComplexInt:
3420 case APValue::ComplexFloat:
3421 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003422 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003423 return false;
3424 case APValue::LValue:
3425 return foundPointer(Subobj, SubobjType);
3426 default:
3427 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003428 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003429 return false;
3430 }
3431 }
3432 bool found(APSInt &Value, QualType SubobjType) {
3433 if (!checkConst(SubobjType))
3434 return false;
3435
3436 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3437 // We don't support compound assignment on integer-cast-to-pointer
3438 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003439 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003440 return false;
3441 }
3442
3443 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3444 SubobjType, Value);
3445 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3446 return false;
3447 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3448 return true;
3449 }
3450 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003451 return checkConst(SubobjType) &&
3452 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3453 Value) &&
3454 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3455 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003456 }
3457 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3458 if (!checkConst(SubobjType))
3459 return false;
3460
3461 QualType PointeeType;
3462 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3463 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003464
3465 if (PointeeType.isNull() || !RHS.isInt() ||
3466 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003467 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003468 return false;
3469 }
3470
Richard Smithd6cc1982017-01-31 02:23:02 +00003471 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003472 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003473 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003474
3475 LValue LVal;
3476 LVal.setFrom(Info.Ctx, Subobj);
3477 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3478 return false;
3479 LVal.moveInto(Subobj);
3480 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003481 }
3482 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3483 llvm_unreachable("shouldn't encounter string elements here");
3484 }
3485};
3486} // end anonymous namespace
3487
3488const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3489
3490/// Perform a compound assignment of LVal <op>= RVal.
3491static bool handleCompoundAssignment(
3492 EvalInfo &Info, const Expr *E,
3493 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3494 BinaryOperatorKind Opcode, const APValue &RVal) {
3495 if (LVal.Designator.Invalid)
3496 return false;
3497
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003498 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003499 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003500 return false;
3501 }
3502
3503 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3504 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3505 RVal };
3506 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3507}
3508
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003509namespace {
3510struct IncDecSubobjectHandler {
3511 EvalInfo &Info;
3512 const UnaryOperator *E;
3513 AccessKinds AccessKind;
3514 APValue *Old;
3515
Richard Smith243ef902013-05-05 23:31:59 +00003516 typedef bool result_type;
3517
3518 bool checkConst(QualType QT) {
3519 // Assigning to a const object has undefined behavior.
3520 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003521 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003522 return false;
3523 }
3524 return true;
3525 }
3526
3527 bool failed() { return false; }
3528 bool found(APValue &Subobj, QualType SubobjType) {
3529 // Stash the old value. Also clear Old, so we don't clobber it later
3530 // if we're post-incrementing a complex.
3531 if (Old) {
3532 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003533 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003534 }
3535
3536 switch (Subobj.getKind()) {
3537 case APValue::Int:
3538 return found(Subobj.getInt(), SubobjType);
3539 case APValue::Float:
3540 return found(Subobj.getFloat(), SubobjType);
3541 case APValue::ComplexInt:
3542 return found(Subobj.getComplexIntReal(),
3543 SubobjType->castAs<ComplexType>()->getElementType()
3544 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3545 case APValue::ComplexFloat:
3546 return found(Subobj.getComplexFloatReal(),
3547 SubobjType->castAs<ComplexType>()->getElementType()
3548 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3549 case APValue::LValue:
3550 return foundPointer(Subobj, SubobjType);
3551 default:
3552 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003553 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003554 return false;
3555 }
3556 }
3557 bool found(APSInt &Value, QualType SubobjType) {
3558 if (!checkConst(SubobjType))
3559 return false;
3560
3561 if (!SubobjType->isIntegerType()) {
3562 // We don't support increment / decrement on integer-cast-to-pointer
3563 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003564 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003565 return false;
3566 }
3567
3568 if (Old) *Old = APValue(Value);
3569
3570 // bool arithmetic promotes to int, and the conversion back to bool
3571 // doesn't reduce mod 2^n, so special-case it.
3572 if (SubobjType->isBooleanType()) {
3573 if (AccessKind == AK_Increment)
3574 Value = 1;
3575 else
3576 Value = !Value;
3577 return true;
3578 }
3579
3580 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003581 if (AccessKind == AK_Increment) {
3582 ++Value;
3583
3584 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3585 APSInt ActualValue(Value, /*IsUnsigned*/true);
3586 return HandleOverflow(Info, E, ActualValue, SubobjType);
3587 }
3588 } else {
3589 --Value;
3590
3591 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3592 unsigned BitWidth = Value.getBitWidth();
3593 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3594 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003595 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003596 }
3597 }
3598 return true;
3599 }
3600 bool found(APFloat &Value, QualType SubobjType) {
3601 if (!checkConst(SubobjType))
3602 return false;
3603
3604 if (Old) *Old = APValue(Value);
3605
3606 APFloat One(Value.getSemantics(), 1);
3607 if (AccessKind == AK_Increment)
3608 Value.add(One, APFloat::rmNearestTiesToEven);
3609 else
3610 Value.subtract(One, APFloat::rmNearestTiesToEven);
3611 return true;
3612 }
3613 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3614 if (!checkConst(SubobjType))
3615 return false;
3616
3617 QualType PointeeType;
3618 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3619 PointeeType = PT->getPointeeType();
3620 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003621 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003622 return false;
3623 }
3624
3625 LValue LVal;
3626 LVal.setFrom(Info.Ctx, Subobj);
3627 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3628 AccessKind == AK_Increment ? 1 : -1))
3629 return false;
3630 LVal.moveInto(Subobj);
3631 return true;
3632 }
3633 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3634 llvm_unreachable("shouldn't encounter string elements here");
3635 }
3636};
3637} // end anonymous namespace
3638
3639/// Perform an increment or decrement on LVal.
3640static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3641 QualType LValType, bool IsIncrement, APValue *Old) {
3642 if (LVal.Designator.Invalid)
3643 return false;
3644
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003645 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003646 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003647 return false;
3648 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003649
3650 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3651 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3652 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3653 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3654}
3655
Richard Smithe97cbd72011-11-11 04:05:33 +00003656/// Build an lvalue for the object argument of a member function call.
3657static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3658 LValue &This) {
3659 if (Object->getType()->isPointerType())
3660 return EvaluatePointer(Object, This, Info);
3661
3662 if (Object->isGLValue())
3663 return EvaluateLValue(Object, This, Info);
3664
Richard Smithd9f663b2013-04-22 15:31:51 +00003665 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003666 return EvaluateTemporary(Object, This, Info);
3667
Faisal Valie690b7a2016-07-02 22:34:24 +00003668 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003669 return false;
3670}
3671
3672/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3673/// lvalue referring to the result.
3674///
3675/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003676/// \param LV - An lvalue referring to the base of the member pointer.
3677/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003678/// \param IncludeMember - Specifies whether the member itself is included in
3679/// the resulting LValue subobject designator. This is not possible when
3680/// creating a bound member function.
3681/// \return The field or method declaration to which the member pointer refers,
3682/// or 0 if evaluation fails.
3683static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003684 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003685 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003686 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003687 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003688 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003689 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003690 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003691
3692 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3693 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003694 if (!MemPtr.getDecl()) {
3695 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003696 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003697 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003698 }
Richard Smith253c2a32012-01-27 01:14:48 +00003699
Richard Smith027bf112011-11-17 22:56:20 +00003700 if (MemPtr.isDerivedMember()) {
3701 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003702 // The end of the derived-to-base path for the base object must match the
3703 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003704 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003705 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003706 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003707 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003708 }
Richard Smith027bf112011-11-17 22:56:20 +00003709 unsigned PathLengthToMember =
3710 LV.Designator.Entries.size() - MemPtr.Path.size();
3711 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3712 const CXXRecordDecl *LVDecl = getAsBaseClass(
3713 LV.Designator.Entries[PathLengthToMember + I]);
3714 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003715 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003716 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003717 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003718 }
Richard Smith027bf112011-11-17 22:56:20 +00003719 }
3720
3721 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003722 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003723 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003724 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003725 } else if (!MemPtr.Path.empty()) {
3726 // Extend the LValue path with the member pointer's path.
3727 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3728 MemPtr.Path.size() + IncludeMember);
3729
3730 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003731 if (const PointerType *PT = LVType->getAs<PointerType>())
3732 LVType = PT->getPointeeType();
3733 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3734 assert(RD && "member pointer access on non-class-type expression");
3735 // The first class in the path is that of the lvalue.
3736 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3737 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003738 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003739 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003740 RD = Base;
3741 }
3742 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003743 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3744 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003745 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003746 }
3747
3748 // Add the member. Note that we cannot build bound member functions here.
3749 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003750 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003751 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003752 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003753 } else if (const IndirectFieldDecl *IFD =
3754 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003755 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003756 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003757 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003758 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003759 }
Richard Smith027bf112011-11-17 22:56:20 +00003760 }
3761
3762 return MemPtr.getDecl();
3763}
3764
Richard Smith84401042013-06-03 05:03:02 +00003765static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3766 const BinaryOperator *BO,
3767 LValue &LV,
3768 bool IncludeMember = true) {
3769 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3770
3771 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003772 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003773 MemberPtr MemPtr;
3774 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3775 }
Craig Topper36250ad2014-05-12 05:36:57 +00003776 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003777 }
3778
3779 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3780 BO->getRHS(), IncludeMember);
3781}
3782
Richard Smith027bf112011-11-17 22:56:20 +00003783/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3784/// the provided lvalue, which currently refers to the base object.
3785static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3786 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003787 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003788 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003789 return false;
3790
Richard Smitha8105bc2012-01-06 16:39:00 +00003791 QualType TargetQT = E->getType();
3792 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3793 TargetQT = PT->getPointeeType();
3794
3795 // Check this cast lands within the final derived-to-base subobject path.
3796 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003797 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003798 << D.MostDerivedType << TargetQT;
3799 return false;
3800 }
3801
Richard Smith027bf112011-11-17 22:56:20 +00003802 // Check the type of the final cast. We don't need to check the path,
3803 // since a cast can only be formed if the path is unique.
3804 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003805 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3806 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003807 if (NewEntriesSize == D.MostDerivedPathLength)
3808 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3809 else
Richard Smith027bf112011-11-17 22:56:20 +00003810 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003811 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003812 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003813 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003814 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003815 }
Richard Smith027bf112011-11-17 22:56:20 +00003816
3817 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003818 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003819}
3820
Mike Stump876387b2009-10-27 22:09:17 +00003821namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003822enum EvalStmtResult {
3823 /// Evaluation failed.
3824 ESR_Failed,
3825 /// Hit a 'return' statement.
3826 ESR_Returned,
3827 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003828 ESR_Succeeded,
3829 /// Hit a 'continue' statement.
3830 ESR_Continue,
3831 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003832 ESR_Break,
3833 /// Still scanning for 'case' or 'default' statement.
3834 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003835};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003836}
Richard Smith254a73d2011-10-28 22:34:42 +00003837
Richard Smith97fcf4b2016-08-14 23:15:52 +00003838static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3839 // We don't need to evaluate the initializer for a static local.
3840 if (!VD->hasLocalStorage())
3841 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003842
Richard Smith97fcf4b2016-08-14 23:15:52 +00003843 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003844 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00003845
Richard Smith97fcf4b2016-08-14 23:15:52 +00003846 const Expr *InitE = VD->getInit();
3847 if (!InitE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003848 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
3849 << false << VD->getType();
Richard Smith97fcf4b2016-08-14 23:15:52 +00003850 Val = APValue();
3851 return false;
3852 }
Richard Smith51f03172013-06-20 03:00:05 +00003853
Richard Smith97fcf4b2016-08-14 23:15:52 +00003854 if (InitE->isValueDependent())
3855 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003856
Richard Smith97fcf4b2016-08-14 23:15:52 +00003857 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3858 // Wipe out any partially-computed value, to allow tracking that this
3859 // evaluation failed.
3860 Val = APValue();
3861 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003862 }
3863
3864 return true;
3865}
3866
Richard Smith97fcf4b2016-08-14 23:15:52 +00003867static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3868 bool OK = true;
3869
3870 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3871 OK &= EvaluateVarDecl(Info, VD);
3872
3873 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3874 for (auto *BD : DD->bindings())
3875 if (auto *VD = BD->getHoldingVar())
3876 OK &= EvaluateDecl(Info, VD);
3877
3878 return OK;
3879}
3880
3881
Richard Smith4e18ca52013-05-06 05:56:11 +00003882/// Evaluate a condition (either a variable declaration or an expression).
3883static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3884 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003885 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003886 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3887 return false;
3888 return EvaluateAsBooleanCondition(Cond, Result, Info);
3889}
3890
Richard Smith89210072016-04-04 23:29:43 +00003891namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003892/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00003893/// statement should be stored.
3894struct StmtResult {
3895 /// The APValue that should be filled in with the returned value.
3896 APValue &Value;
3897 /// The location containing the result, if any (used to support RVO).
3898 const LValue *Slot;
3899};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003900
3901struct TempVersionRAII {
3902 CallStackFrame &Frame;
3903
3904 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3905 Frame.pushTempVersion();
3906 }
3907
3908 ~TempVersionRAII() {
3909 Frame.popTempVersion();
3910 }
3911};
3912
Richard Smith89210072016-04-04 23:29:43 +00003913}
Richard Smith52a980a2015-08-28 02:43:42 +00003914
3915static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003916 const Stmt *S,
3917 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003918
3919/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003920static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003921 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003922 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003923 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003924 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003925 case ESR_Break:
3926 return ESR_Succeeded;
3927 case ESR_Succeeded:
3928 case ESR_Continue:
3929 return ESR_Continue;
3930 case ESR_Failed:
3931 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003932 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003933 return ESR;
3934 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003935 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003936}
3937
Richard Smith496ddcf2013-05-12 17:32:42 +00003938/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003939static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003940 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003941 BlockScopeRAII Scope(Info);
3942
Richard Smith496ddcf2013-05-12 17:32:42 +00003943 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003944 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003945 {
3946 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003947 if (const Stmt *Init = SS->getInit()) {
3948 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3949 if (ESR != ESR_Succeeded)
3950 return ESR;
3951 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003952 if (SS->getConditionVariable() &&
3953 !EvaluateDecl(Info, SS->getConditionVariable()))
3954 return ESR_Failed;
3955 if (!EvaluateInteger(SS->getCond(), Value, Info))
3956 return ESR_Failed;
3957 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003958
3959 // Find the switch case corresponding to the value of the condition.
3960 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003961 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003962 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3963 SC = SC->getNextSwitchCase()) {
3964 if (isa<DefaultStmt>(SC)) {
3965 Found = SC;
3966 continue;
3967 }
3968
3969 const CaseStmt *CS = cast<CaseStmt>(SC);
3970 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3971 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3972 : LHS;
3973 if (LHS <= Value && Value <= RHS) {
3974 Found = SC;
3975 break;
3976 }
3977 }
3978
3979 if (!Found)
3980 return ESR_Succeeded;
3981
3982 // Search the switch body for the switch case and evaluate it from there.
3983 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3984 case ESR_Break:
3985 return ESR_Succeeded;
3986 case ESR_Succeeded:
3987 case ESR_Continue:
3988 case ESR_Failed:
3989 case ESR_Returned:
3990 return ESR;
3991 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003992 // This can only happen if the switch case is nested within a statement
3993 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003994 Info.FFDiag(Found->getBeginLoc(),
3995 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003996 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003997 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003998 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003999}
4000
Richard Smith254a73d2011-10-28 22:34:42 +00004001// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004002static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004003 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004004 if (!Info.nextStep(S))
4005 return ESR_Failed;
4006
Richard Smith496ddcf2013-05-12 17:32:42 +00004007 // If we're hunting down a 'case' or 'default' label, recurse through
4008 // substatements until we hit the label.
4009 if (Case) {
4010 // FIXME: We don't start the lifetime of objects whose initialization we
4011 // jump over. However, such objects must be of class type with a trivial
4012 // default constructor that initialize all subobjects, so must be empty,
4013 // so this almost never matters.
4014 switch (S->getStmtClass()) {
4015 case Stmt::CompoundStmtClass:
4016 // FIXME: Precompute which substatement of a compound statement we
4017 // would jump to, and go straight there rather than performing a
4018 // linear scan each time.
4019 case Stmt::LabelStmtClass:
4020 case Stmt::AttributedStmtClass:
4021 case Stmt::DoStmtClass:
4022 break;
4023
4024 case Stmt::CaseStmtClass:
4025 case Stmt::DefaultStmtClass:
4026 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004027 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004028 break;
4029
4030 case Stmt::IfStmtClass: {
4031 // FIXME: Precompute which side of an 'if' we would jump to, and go
4032 // straight there rather than scanning both sides.
4033 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004034
4035 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4036 // preceded by our switch label.
4037 BlockScopeRAII Scope(Info);
4038
Richard Smith496ddcf2013-05-12 17:32:42 +00004039 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4040 if (ESR != ESR_CaseNotFound || !IS->getElse())
4041 return ESR;
4042 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4043 }
4044
4045 case Stmt::WhileStmtClass: {
4046 EvalStmtResult ESR =
4047 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4048 if (ESR != ESR_Continue)
4049 return ESR;
4050 break;
4051 }
4052
4053 case Stmt::ForStmtClass: {
4054 const ForStmt *FS = cast<ForStmt>(S);
4055 EvalStmtResult ESR =
4056 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4057 if (ESR != ESR_Continue)
4058 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004059 if (FS->getInc()) {
4060 FullExpressionRAII IncScope(Info);
4061 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4062 return ESR_Failed;
4063 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004064 break;
4065 }
4066
4067 case Stmt::DeclStmtClass:
4068 // FIXME: If the variable has initialization that can't be jumped over,
4069 // bail out of any immediately-surrounding compound-statement too.
4070 default:
4071 return ESR_CaseNotFound;
4072 }
4073 }
4074
Richard Smith254a73d2011-10-28 22:34:42 +00004075 switch (S->getStmtClass()) {
4076 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004077 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004078 // Don't bother evaluating beyond an expression-statement which couldn't
4079 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004080 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004081 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004082 return ESR_Failed;
4083 return ESR_Succeeded;
4084 }
4085
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004086 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004087 return ESR_Failed;
4088
4089 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004090 return ESR_Succeeded;
4091
Richard Smithd9f663b2013-04-22 15:31:51 +00004092 case Stmt::DeclStmtClass: {
4093 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004094 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004095 // Each declaration initialization is its own full-expression.
4096 // FIXME: This isn't quite right; if we're performing aggregate
4097 // initialization, each braced subexpression is its own full-expression.
4098 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004099 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004100 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004101 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004102 return ESR_Succeeded;
4103 }
4104
Richard Smith357362d2011-12-13 06:39:58 +00004105 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004106 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004107 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004108 if (RetExpr &&
4109 !(Result.Slot
4110 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4111 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004112 return ESR_Failed;
4113 return ESR_Returned;
4114 }
Richard Smith254a73d2011-10-28 22:34:42 +00004115
4116 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004117 BlockScopeRAII Scope(Info);
4118
Richard Smith254a73d2011-10-28 22:34:42 +00004119 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004120 for (const auto *BI : CS->body()) {
4121 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004122 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004123 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004124 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004125 return ESR;
4126 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004127 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004128 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004129
4130 case Stmt::IfStmtClass: {
4131 const IfStmt *IS = cast<IfStmt>(S);
4132
4133 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004134 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004135 if (const Stmt *Init = IS->getInit()) {
4136 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4137 if (ESR != ESR_Succeeded)
4138 return ESR;
4139 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004140 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004141 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004142 return ESR_Failed;
4143
4144 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4145 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4146 if (ESR != ESR_Succeeded)
4147 return ESR;
4148 }
4149 return ESR_Succeeded;
4150 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004151
4152 case Stmt::WhileStmtClass: {
4153 const WhileStmt *WS = cast<WhileStmt>(S);
4154 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004155 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004156 bool Continue;
4157 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4158 Continue))
4159 return ESR_Failed;
4160 if (!Continue)
4161 break;
4162
4163 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4164 if (ESR != ESR_Continue)
4165 return ESR;
4166 }
4167 return ESR_Succeeded;
4168 }
4169
4170 case Stmt::DoStmtClass: {
4171 const DoStmt *DS = cast<DoStmt>(S);
4172 bool Continue;
4173 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004174 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004175 if (ESR != ESR_Continue)
4176 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004177 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004178
Richard Smith08d6a2c2013-07-24 07:11:57 +00004179 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004180 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4181 return ESR_Failed;
4182 } while (Continue);
4183 return ESR_Succeeded;
4184 }
4185
4186 case Stmt::ForStmtClass: {
4187 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004188 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004189 if (FS->getInit()) {
4190 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4191 if (ESR != ESR_Succeeded)
4192 return ESR;
4193 }
4194 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004195 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004196 bool Continue = true;
4197 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4198 FS->getCond(), Continue))
4199 return ESR_Failed;
4200 if (!Continue)
4201 break;
4202
4203 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4204 if (ESR != ESR_Continue)
4205 return ESR;
4206
Richard Smith08d6a2c2013-07-24 07:11:57 +00004207 if (FS->getInc()) {
4208 FullExpressionRAII IncScope(Info);
4209 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4210 return ESR_Failed;
4211 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004212 }
4213 return ESR_Succeeded;
4214 }
4215
Richard Smith896e0d72013-05-06 06:51:17 +00004216 case Stmt::CXXForRangeStmtClass: {
4217 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004218 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004219
Richard Smith8baa5002018-09-28 18:44:09 +00004220 // Evaluate the init-statement if present.
4221 if (FS->getInit()) {
4222 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4223 if (ESR != ESR_Succeeded)
4224 return ESR;
4225 }
4226
Richard Smith896e0d72013-05-06 06:51:17 +00004227 // Initialize the __range variable.
4228 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4229 if (ESR != ESR_Succeeded)
4230 return ESR;
4231
4232 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004233 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4234 if (ESR != ESR_Succeeded)
4235 return ESR;
4236 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004237 if (ESR != ESR_Succeeded)
4238 return ESR;
4239
4240 while (true) {
4241 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004242 {
4243 bool Continue = true;
4244 FullExpressionRAII CondExpr(Info);
4245 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4246 return ESR_Failed;
4247 if (!Continue)
4248 break;
4249 }
Richard Smith896e0d72013-05-06 06:51:17 +00004250
4251 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004252 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004253 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4254 if (ESR != ESR_Succeeded)
4255 return ESR;
4256
4257 // Loop body.
4258 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4259 if (ESR != ESR_Continue)
4260 return ESR;
4261
4262 // Increment: ++__begin
4263 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4264 return ESR_Failed;
4265 }
4266
4267 return ESR_Succeeded;
4268 }
4269
Richard Smith496ddcf2013-05-12 17:32:42 +00004270 case Stmt::SwitchStmtClass:
4271 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4272
Richard Smith4e18ca52013-05-06 05:56:11 +00004273 case Stmt::ContinueStmtClass:
4274 return ESR_Continue;
4275
4276 case Stmt::BreakStmtClass:
4277 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004278
4279 case Stmt::LabelStmtClass:
4280 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4281
4282 case Stmt::AttributedStmtClass:
4283 // As a general principle, C++11 attributes can be ignored without
4284 // any semantic impact.
4285 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4286 Case);
4287
4288 case Stmt::CaseStmtClass:
4289 case Stmt::DefaultStmtClass:
4290 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004291 }
4292}
4293
Richard Smithcc36f692011-12-22 02:22:31 +00004294/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4295/// default constructor. If so, we'll fold it whether or not it's marked as
4296/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4297/// so we need special handling.
4298static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004299 const CXXConstructorDecl *CD,
4300 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004301 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4302 return false;
4303
Richard Smith66e05fe2012-01-18 05:21:49 +00004304 // Value-initialization does not call a trivial default constructor, so such a
4305 // call is a core constant expression whether or not the constructor is
4306 // constexpr.
4307 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004308 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004309 // FIXME: If DiagDecl is an implicitly-declared special member function,
4310 // we should be much more explicit about why it's not constexpr.
4311 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4312 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4313 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004314 } else {
4315 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4316 }
4317 }
4318 return true;
4319}
4320
Richard Smith357362d2011-12-13 06:39:58 +00004321/// CheckConstexprFunction - Check that a function can be called in a constant
4322/// expression.
4323static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4324 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004325 const FunctionDecl *Definition,
4326 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004327 // Potential constant expressions can contain calls to declared, but not yet
4328 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004329 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004330 Declaration->isConstexpr())
4331 return false;
4332
James Y Knightc7d3e602018-10-05 17:49:48 +00004333 // Bail out if the function declaration itself is invalid. We will
4334 // have produced a relevant diagnostic while parsing it, so just
4335 // note the problematic sub-expression.
4336 if (Declaration->isInvalidDecl()) {
4337 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004338 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004339 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004340
Richard Smith357362d2011-12-13 06:39:58 +00004341 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004342 if (Definition && Definition->isConstexpr() &&
4343 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004344 return true;
4345
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004346 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004347 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004348
Richard Smith5179eb72016-06-28 19:03:57 +00004349 // If this function is not constexpr because it is an inherited
4350 // non-constexpr constructor, diagnose that directly.
4351 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4352 if (CD && CD->isInheritingConstructor()) {
4353 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004354 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004355 DiagDecl = CD = Inherited;
4356 }
4357
4358 // FIXME: If DiagDecl is an implicitly-declared special member function
4359 // or an inheriting constructor, we should be much more explicit about why
4360 // it's not constexpr.
4361 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004362 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004363 << CD->getInheritedConstructor().getConstructor()->getParent();
4364 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004365 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004366 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004367 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4368 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004369 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004370 }
4371 return false;
4372}
4373
Richard Smithbe6dd812014-11-19 21:27:17 +00004374/// Determine if a class has any fields that might need to be copied by a
4375/// trivial copy or move operation.
4376static bool hasFields(const CXXRecordDecl *RD) {
4377 if (!RD || RD->isEmpty())
4378 return false;
4379 for (auto *FD : RD->fields()) {
4380 if (FD->isUnnamedBitfield())
4381 continue;
4382 return true;
4383 }
4384 for (auto &Base : RD->bases())
4385 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4386 return true;
4387 return false;
4388}
4389
Richard Smithd62306a2011-11-10 06:34:14 +00004390namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004391typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004392}
4393
4394/// EvaluateArgs - Evaluate the arguments to a function call.
4395static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4396 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004397 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004398 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004399 I != E; ++I) {
4400 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4401 // If we're checking for a potential constant expression, evaluate all
4402 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004403 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004404 return false;
4405 Success = false;
4406 }
4407 }
4408 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004409}
4410
Richard Smith254a73d2011-10-28 22:34:42 +00004411/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004412static bool HandleFunctionCall(SourceLocation CallLoc,
4413 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004414 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004415 EvalInfo &Info, APValue &Result,
4416 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004417 ArgVector ArgValues(Args.size());
4418 if (!EvaluateArgs(Args, ArgValues, Info))
4419 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004420
Richard Smith253c2a32012-01-27 01:14:48 +00004421 if (!Info.CheckCallLimit(CallLoc))
4422 return false;
4423
4424 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004425
4426 // For a trivial copy or move assignment, perform an APValue copy. This is
4427 // essential for unions, where the operations performed by the assignment
4428 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004429 //
4430 // Skip this for non-union classes with no fields; in that case, the defaulted
4431 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004432 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004433 if (MD && MD->isDefaulted() &&
4434 (MD->getParent()->isUnion() ||
4435 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004436 assert(This &&
4437 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4438 LValue RHS;
4439 RHS.setFrom(Info.Ctx, ArgValues[0]);
4440 APValue RHSValue;
4441 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4442 RHS, RHSValue))
4443 return false;
4444 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4445 RHSValue))
4446 return false;
4447 This->moveInto(Result);
4448 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004449 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00004450 // We're in a lambda; determine the lambda capture field maps unless we're
4451 // just constexpr checking a lambda's call operator. constexpr checking is
4452 // done before the captures have been added to the closure object (unless
4453 // we're inferring constexpr-ness), so we don't have access to them in this
4454 // case. But since we don't need the captures to constexpr check, we can
4455 // just ignore them.
4456 if (!Info.checkingPotentialConstantExpression())
4457 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4458 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004459 }
4460
Richard Smith52a980a2015-08-28 02:43:42 +00004461 StmtResult Ret = {Result, ResultSlot};
4462 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004463 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004464 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004465 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004466 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004467 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004468 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004469}
4470
Richard Smithd62306a2011-11-10 06:34:14 +00004471/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004472static bool HandleConstructorCall(const Expr *E, const LValue &This,
4473 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004474 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004475 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004476 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004477 if (!Info.CheckCallLimit(CallLoc))
4478 return false;
4479
Richard Smith3607ffe2012-02-13 03:54:03 +00004480 const CXXRecordDecl *RD = Definition->getParent();
4481 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004482 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004483 return false;
4484 }
4485
Erik Pilkington42925492017-10-04 00:18:55 +00004486 EvalInfo::EvaluatingConstructorRAII EvalObj(
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004487 Info, {This.getLValueBase(),
4488 {This.getLValueCallIndex(), This.getLValueVersion()}});
Richard Smith5179eb72016-06-28 19:03:57 +00004489 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004490
Richard Smith52a980a2015-08-28 02:43:42 +00004491 // FIXME: Creating an APValue just to hold a nonexistent return value is
4492 // wasteful.
4493 APValue RetVal;
4494 StmtResult Ret = {RetVal, nullptr};
4495
Richard Smith5179eb72016-06-28 19:03:57 +00004496 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004497 if (Definition->isDelegatingConstructor()) {
4498 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004499 {
4500 FullExpressionRAII InitScope(Info);
4501 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4502 return false;
4503 }
Richard Smith52a980a2015-08-28 02:43:42 +00004504 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004505 }
4506
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004507 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004508 // essential for unions (or classes with anonymous union members), where the
4509 // operations performed by the constructor cannot be represented by
4510 // ctor-initializers.
4511 //
4512 // Skip this for empty non-union classes; we should not perform an
4513 // lvalue-to-rvalue conversion on them because their copy constructor does not
4514 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004515 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004516 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004517 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004518 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004519 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004520 return handleLValueToRValueConversion(
4521 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4522 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004523 }
4524
4525 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004526 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004527 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004528 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004529
John McCalld7bca762012-05-01 00:38:49 +00004530 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004531 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4532
Richard Smith08d6a2c2013-07-24 07:11:57 +00004533 // A scope for temporaries lifetime-extended by reference members.
4534 BlockScopeRAII LifetimeExtendedScope(Info);
4535
Richard Smith253c2a32012-01-27 01:14:48 +00004536 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004537 unsigned BasesSeen = 0;
4538#ifndef NDEBUG
4539 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4540#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004541 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004542 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004543 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004544 APValue *Value = &Result;
4545
4546 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004547 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004548 if (I->isBaseInitializer()) {
4549 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004550#ifndef NDEBUG
4551 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004552 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004553 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4554 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4555 "base class initializers not in expected order");
4556 ++BaseIt;
4557#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004558 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004559 BaseType->getAsCXXRecordDecl(), &Layout))
4560 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004561 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004562 } else if ((FD = I->getMember())) {
4563 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004564 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004565 if (RD->isUnion()) {
4566 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004567 Value = &Result.getUnionValue();
4568 } else {
4569 Value = &Result.getStructField(FD->getFieldIndex());
4570 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004571 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004572 // Walk the indirect field decl's chain to find the object to initialize,
4573 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004574 auto IndirectFieldChain = IFD->chain();
4575 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004576 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004577 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4578 // Switch the union field if it differs. This happens if we had
4579 // preceding zero-initialization, and we're now initializing a union
4580 // subobject other than the first.
4581 // FIXME: In this case, the values of the other subobjects are
4582 // specified, since zero-initialization sets all padding bits to zero.
4583 if (Value->isUninit() ||
4584 (Value->isUnion() && Value->getUnionField() != FD)) {
4585 if (CD->isUnion())
4586 *Value = APValue(FD);
4587 else
4588 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004589 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004590 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004591 // Store Subobject as its parent before updating it for the last element
4592 // in the chain.
4593 if (C == IndirectFieldChain.back())
4594 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004595 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004596 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004597 if (CD->isUnion())
4598 Value = &Value->getUnionValue();
4599 else
4600 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004601 }
Richard Smithd62306a2011-11-10 06:34:14 +00004602 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004603 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004604 }
Richard Smith253c2a32012-01-27 01:14:48 +00004605
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004606 // Need to override This for implicit field initializers as in this case
4607 // This refers to innermost anonymous struct/union containing initializer,
4608 // not to currently constructed class.
4609 const Expr *Init = I->getInit();
4610 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4611 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004612 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004613 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4614 (FD && FD->isBitField() &&
4615 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004616 // If we're checking for a potential constant expression, evaluate all
4617 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004618 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004619 return false;
4620 Success = false;
4621 }
Richard Smithd62306a2011-11-10 06:34:14 +00004622 }
4623
Richard Smithd9f663b2013-04-22 15:31:51 +00004624 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004625 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004626}
4627
Richard Smith5179eb72016-06-28 19:03:57 +00004628static bool HandleConstructorCall(const Expr *E, const LValue &This,
4629 ArrayRef<const Expr*> Args,
4630 const CXXConstructorDecl *Definition,
4631 EvalInfo &Info, APValue &Result) {
4632 ArgVector ArgValues(Args.size());
4633 if (!EvaluateArgs(Args, ArgValues, Info))
4634 return false;
4635
4636 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4637 Info, Result);
4638}
4639
Eli Friedman9a156e52008-11-12 09:44:48 +00004640//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004641// Generic Evaluation
4642//===----------------------------------------------------------------------===//
4643namespace {
4644
Aaron Ballman68af21c2014-01-03 19:26:43 +00004645template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004646class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004647 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004648private:
Richard Smith52a980a2015-08-28 02:43:42 +00004649 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004650 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004651 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004652 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004653 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004654 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004655 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004656
Richard Smith17100ba2012-02-16 02:46:34 +00004657 // Check whether a conditional operator with a non-constant condition is a
4658 // potential constant expression. If neither arm is a potential constant
4659 // expression, then the conditional operator is not either.
4660 template<typename ConditionalOperator>
4661 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004662 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004663
4664 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004665 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004666 {
Richard Smith17100ba2012-02-16 02:46:34 +00004667 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004668 StmtVisitorTy::Visit(E->getFalseExpr());
4669 if (Diag.empty())
4670 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004671 }
Richard Smith17100ba2012-02-16 02:46:34 +00004672
George Burgess IV8c892b52016-05-25 22:31:54 +00004673 {
4674 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004675 Diag.clear();
4676 StmtVisitorTy::Visit(E->getTrueExpr());
4677 if (Diag.empty())
4678 return;
4679 }
4680
4681 Error(E, diag::note_constexpr_conditional_never_const);
4682 }
4683
4684
4685 template<typename ConditionalOperator>
4686 bool HandleConditionalOperator(const ConditionalOperator *E) {
4687 bool BoolResult;
4688 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004689 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004690 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004691 return false;
4692 }
4693 if (Info.noteFailure()) {
4694 StmtVisitorTy::Visit(E->getTrueExpr());
4695 StmtVisitorTy::Visit(E->getFalseExpr());
4696 }
Richard Smith17100ba2012-02-16 02:46:34 +00004697 return false;
4698 }
4699
4700 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4701 return StmtVisitorTy::Visit(EvalExpr);
4702 }
4703
Peter Collingbournee9200682011-05-13 03:29:01 +00004704protected:
4705 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004706 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004707 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4708
Richard Smith92b1ce02011-12-12 09:28:41 +00004709 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004710 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004711 }
4712
Aaron Ballman68af21c2014-01-03 19:26:43 +00004713 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004714
4715public:
4716 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4717
4718 EvalInfo &getEvalInfo() { return Info; }
4719
Richard Smithf57d8cb2011-12-09 22:58:01 +00004720 /// Report an evaluation error. This should only be called when an error is
4721 /// first discovered. When propagating an error, just return false.
4722 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004723 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004724 return false;
4725 }
4726 bool Error(const Expr *E) {
4727 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4728 }
4729
Aaron Ballman68af21c2014-01-03 19:26:43 +00004730 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004731 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004732 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004733 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004734 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004735 }
4736
Aaron Ballman68af21c2014-01-03 19:26:43 +00004737 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004738 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004739 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004740 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004741 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004742 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004743 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004744 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004745 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004746 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004747 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004748 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004749 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4750 TempVersionRAII RAII(*Info.CurrentCall);
4751 return StmtVisitorTy::Visit(E->getExpr());
4752 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004753 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004754 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00004755 // The initializer may not have been parsed yet, or might be erroneous.
4756 if (!E->getExpr())
4757 return Error(E);
4758 return StmtVisitorTy::Visit(E->getExpr());
4759 }
Richard Smith5894a912011-12-19 22:12:41 +00004760 // We cannot create any objects for which cleanups are required, so there is
4761 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004762 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004763 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004764
Aaron Ballman68af21c2014-01-03 19:26:43 +00004765 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004766 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4767 return static_cast<Derived*>(this)->VisitCastExpr(E);
4768 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004769 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004770 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4771 return static_cast<Derived*>(this)->VisitCastExpr(E);
4772 }
4773
Aaron Ballman68af21c2014-01-03 19:26:43 +00004774 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004775 switch (E->getOpcode()) {
4776 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004777 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004778
4779 case BO_Comma:
4780 VisitIgnoredValue(E->getLHS());
4781 return StmtVisitorTy::Visit(E->getRHS());
4782
4783 case BO_PtrMemD:
4784 case BO_PtrMemI: {
4785 LValue Obj;
4786 if (!HandleMemberPointerAccess(Info, E, Obj))
4787 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004788 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004789 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004790 return false;
4791 return DerivedSuccess(Result, E);
4792 }
4793 }
4794 }
4795
Aaron Ballman68af21c2014-01-03 19:26:43 +00004796 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004797 // Evaluate and cache the common expression. We treat it as a temporary,
4798 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004799 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004800 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004801 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004802
Richard Smith17100ba2012-02-16 02:46:34 +00004803 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004804 }
4805
Aaron Ballman68af21c2014-01-03 19:26:43 +00004806 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004807 bool IsBcpCall = false;
4808 // If the condition (ignoring parens) is a __builtin_constant_p call,
4809 // the result is a constant expression if it can be folded without
4810 // side-effects. This is an important GNU extension. See GCC PR38377
4811 // for discussion.
4812 if (const CallExpr *CallCE =
4813 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004814 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004815 IsBcpCall = true;
4816
4817 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4818 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004819 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004820 return false;
4821
Richard Smith6d4c6582013-11-05 22:18:15 +00004822 FoldConstant Fold(Info, IsBcpCall);
4823 if (!HandleConditionalOperator(E)) {
4824 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004825 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004826 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004827
4828 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004829 }
4830
Aaron Ballman68af21c2014-01-03 19:26:43 +00004831 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004832 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00004833 return DerivedSuccess(*Value, E);
4834
4835 const Expr *Source = E->getSourceExpr();
4836 if (!Source)
4837 return Error(E);
4838 if (Source == E) { // sanity checking.
4839 assert(0 && "OpaqueValueExpr recursively refers to itself");
4840 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004841 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004842 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004843 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004844
Aaron Ballman68af21c2014-01-03 19:26:43 +00004845 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004846 APValue Result;
4847 if (!handleCallExpr(E, Result, nullptr))
4848 return false;
4849 return DerivedSuccess(Result, E);
4850 }
4851
4852 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004853 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004854 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004855 QualType CalleeType = Callee->getType();
4856
Craig Topper36250ad2014-05-12 05:36:57 +00004857 const FunctionDecl *FD = nullptr;
4858 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004859 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004860 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004861
Richard Smithe97cbd72011-11-11 04:05:33 +00004862 // Extract function decl and 'this' pointer from the callee.
4863 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004864 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004865 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4866 // Explicit bound member calls, such as x.f() or p->g();
4867 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004868 return false;
4869 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004870 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004871 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004872 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4873 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004874 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4875 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004876 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004877 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004878 return Error(Callee);
4879
4880 FD = dyn_cast<FunctionDecl>(Member);
4881 if (!FD)
4882 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004883 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004884 LValue Call;
4885 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004886 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004887
Richard Smitha8105bc2012-01-06 16:39:00 +00004888 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004889 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004890 FD = dyn_cast_or_null<FunctionDecl>(
4891 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004892 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004893 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004894 // Don't call function pointers which have been cast to some other type.
4895 // Per DR (no number yet), the caller and callee can differ in noexcept.
4896 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4897 CalleeType->getPointeeType(), FD->getType())) {
4898 return Error(E);
4899 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004900
4901 // Overloaded operator calls to member functions are represented as normal
4902 // calls with '*this' as the first argument.
4903 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4904 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004905 // FIXME: When selecting an implicit conversion for an overloaded
4906 // operator delete, we sometimes try to evaluate calls to conversion
4907 // operators without a 'this' parameter!
4908 if (Args.empty())
4909 return Error(E);
4910
Nick Lewycky13073a62017-06-12 21:15:44 +00004911 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004912 return false;
4913 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004914 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00004915 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004916 // Map the static invoker for the lambda back to the call operator.
4917 // Conveniently, we don't have to slice out the 'this' argument (as is
4918 // being done for the non-static case), since a static member function
4919 // doesn't have an implicit argument passed in.
4920 const CXXRecordDecl *ClosureClass = MD->getParent();
4921 assert(
4922 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4923 "Number of captures must be zero for conversion to function-ptr");
4924
4925 const CXXMethodDecl *LambdaCallOp =
4926 ClosureClass->getLambdaCallOperator();
4927
4928 // Set 'FD', the function that will be called below, to the call
4929 // operator. If the closure object represents a generic lambda, find
4930 // the corresponding specialization of the call operator.
4931
4932 if (ClosureClass->isGenericLambda()) {
4933 assert(MD->isFunctionTemplateSpecialization() &&
4934 "A generic lambda's static-invoker function must be a "
4935 "template specialization");
4936 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4937 FunctionTemplateDecl *CallOpTemplate =
4938 LambdaCallOp->getDescribedFunctionTemplate();
4939 void *InsertPos = nullptr;
4940 FunctionDecl *CorrespondingCallOpSpecialization =
4941 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4942 assert(CorrespondingCallOpSpecialization &&
4943 "We must always have a function call operator specialization "
4944 "that corresponds to our static invoker specialization");
4945 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4946 } else
4947 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004948 }
4949
Fangrui Song6907ce22018-07-30 19:24:48 +00004950
Richard Smithe97cbd72011-11-11 04:05:33 +00004951 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004952 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004953
Richard Smith47b34932012-02-01 02:39:43 +00004954 if (This && !This->checkSubobject(Info, E, CSK_This))
4955 return false;
4956
Richard Smith3607ffe2012-02-13 03:54:03 +00004957 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4958 // calls to such functions in constant expressions.
4959 if (This && !HasQualifier &&
4960 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4961 return Error(E, diag::note_constexpr_virtual_call);
4962
Craig Topper36250ad2014-05-12 05:36:57 +00004963 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004964 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004965
Nick Lewycky13073a62017-06-12 21:15:44 +00004966 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4967 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004968 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004969 return false;
4970
Richard Smith52a980a2015-08-28 02:43:42 +00004971 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004972 }
4973
Aaron Ballman68af21c2014-01-03 19:26:43 +00004974 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004975 return StmtVisitorTy::Visit(E->getInitializer());
4976 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004977 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004978 if (E->getNumInits() == 0)
4979 return DerivedZeroInitialization(E);
4980 if (E->getNumInits() == 1)
4981 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004982 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004983 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004984 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004985 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004986 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004987 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004988 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004989 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004990 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004991 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004992 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004993
Richard Smithd62306a2011-11-10 06:34:14 +00004994 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004995 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004996 assert(!E->isArrow() && "missing call to bound member function?");
4997
Richard Smith2e312c82012-03-03 22:46:17 +00004998 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004999 if (!Evaluate(Val, Info, E->getBase()))
5000 return false;
5001
5002 QualType BaseTy = E->getBase()->getType();
5003
5004 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00005005 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005006 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00005007 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00005008 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5009
Richard Smith9defb7d2018-02-21 03:38:30 +00005010 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00005011 SubobjectDesignator Designator(BaseTy);
5012 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00005013
Richard Smith3229b742013-05-05 21:17:10 +00005014 APValue Result;
5015 return extractSubobject(Info, E, Obj, Designator, Result) &&
5016 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00005017 }
5018
Aaron Ballman68af21c2014-01-03 19:26:43 +00005019 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005020 switch (E->getCastKind()) {
5021 default:
5022 break;
5023
Richard Smitha23ab512013-05-23 00:30:41 +00005024 case CK_AtomicToNonAtomic: {
5025 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00005026 // This does not need to be done in place even for class/array types:
5027 // atomic-to-non-atomic conversion implies copying the object
5028 // representation.
5029 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00005030 return false;
5031 return DerivedSuccess(AtomicVal, E);
5032 }
5033
Richard Smith11562c52011-10-28 17:51:58 +00005034 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00005035 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00005036 return StmtVisitorTy::Visit(E->getSubExpr());
5037
5038 case CK_LValueToRValue: {
5039 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005040 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5041 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005042 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00005043 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00005044 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00005045 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005046 return false;
5047 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00005048 }
5049 }
5050
Richard Smithf57d8cb2011-12-09 22:58:01 +00005051 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005052 }
5053
Aaron Ballman68af21c2014-01-03 19:26:43 +00005054 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005055 return VisitUnaryPostIncDec(UO);
5056 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005057 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005058 return VisitUnaryPostIncDec(UO);
5059 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005060 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005061 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005062 return Error(UO);
5063
5064 LValue LVal;
5065 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5066 return false;
5067 APValue RVal;
5068 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5069 UO->isIncrementOp(), &RVal))
5070 return false;
5071 return DerivedSuccess(RVal, UO);
5072 }
5073
Aaron Ballman68af21c2014-01-03 19:26:43 +00005074 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00005075 // We will have checked the full-expressions inside the statement expression
5076 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00005077 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00005078 return Error(E);
5079
Richard Smith08d6a2c2013-07-24 07:11:57 +00005080 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00005081 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005082 if (CS->body_empty())
5083 return true;
5084
Richard Smith51f03172013-06-20 03:00:05 +00005085 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5086 BE = CS->body_end();
5087 /**/; ++BI) {
5088 if (BI + 1 == BE) {
5089 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5090 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005091 Info.FFDiag((*BI)->getBeginLoc(),
5092 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005093 return false;
5094 }
5095 return this->Visit(FinalExpr);
5096 }
5097
5098 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00005099 StmtResult Result = { ReturnValue, nullptr };
5100 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00005101 if (ESR != ESR_Succeeded) {
5102 // FIXME: If the statement-expression terminated due to 'return',
5103 // 'break', or 'continue', it would be nice to propagate that to
5104 // the outer statement evaluation rather than bailing out.
5105 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005106 Info.FFDiag((*BI)->getBeginLoc(),
5107 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005108 return false;
5109 }
5110 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005111
5112 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00005113 }
5114
Richard Smith4a678122011-10-24 18:44:57 +00005115 /// Visit a value which is evaluated, but whose value is ignored.
5116 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00005117 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00005118 }
David Majnemere9807b22016-02-26 04:23:19 +00005119
5120 /// Potentially visit a MemberExpr's base expression.
5121 void VisitIgnoredBaseExpression(const Expr *E) {
5122 // While MSVC doesn't evaluate the base expression, it does diagnose the
5123 // presence of side-effecting behavior.
5124 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5125 return;
5126 VisitIgnoredValue(E);
5127 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005128};
5129
Eric Fiselier0683c0e2018-05-07 21:07:10 +00005130} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00005131
5132//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005133// Common base class for lvalue and temporary evaluation.
5134//===----------------------------------------------------------------------===//
5135namespace {
5136template<class Derived>
5137class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005138 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00005139protected:
5140 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005141 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005142 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005143 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005144
5145 bool Success(APValue::LValueBase B) {
5146 Result.set(B);
5147 return true;
5148 }
5149
George Burgess IVf9013bf2017-02-10 22:52:29 +00005150 bool evaluatePointer(const Expr *E, LValue &Result) {
5151 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5152 }
5153
Richard Smith027bf112011-11-17 22:56:20 +00005154public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005155 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5156 : ExprEvaluatorBaseTy(Info), Result(Result),
5157 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005158
Richard Smith2e312c82012-03-03 22:46:17 +00005159 bool Success(const APValue &V, const Expr *E) {
5160 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005161 return true;
5162 }
Richard Smith027bf112011-11-17 22:56:20 +00005163
Richard Smith027bf112011-11-17 22:56:20 +00005164 bool VisitMemberExpr(const MemberExpr *E) {
5165 // Handle non-static data members.
5166 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005167 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005168 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005169 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005170 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005171 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005172 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005173 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005174 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005175 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005176 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005177 BaseTy = E->getBase()->getType();
5178 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005179 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005180 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005181 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005182 Result.setInvalid(E);
5183 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005184 }
Richard Smith027bf112011-11-17 22:56:20 +00005185
Richard Smith1b78b3d2012-01-25 22:15:11 +00005186 const ValueDecl *MD = E->getMemberDecl();
5187 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5188 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5189 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5190 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005191 if (!HandleLValueMember(this->Info, E, Result, FD))
5192 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005193 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005194 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5195 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005196 } else
5197 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005198
Richard Smith1b78b3d2012-01-25 22:15:11 +00005199 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005200 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005201 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005202 RefValue))
5203 return false;
5204 return Success(RefValue, E);
5205 }
5206 return true;
5207 }
5208
5209 bool VisitBinaryOperator(const BinaryOperator *E) {
5210 switch (E->getOpcode()) {
5211 default:
5212 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5213
5214 case BO_PtrMemD:
5215 case BO_PtrMemI:
5216 return HandleMemberPointerAccess(this->Info, E, Result);
5217 }
5218 }
5219
5220 bool VisitCastExpr(const CastExpr *E) {
5221 switch (E->getCastKind()) {
5222 default:
5223 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5224
5225 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005226 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005227 if (!this->Visit(E->getSubExpr()))
5228 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005229
5230 // Now figure out the necessary offset to add to the base LV to get from
5231 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005232 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5233 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005234 }
5235 }
5236};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005237}
Richard Smith027bf112011-11-17 22:56:20 +00005238
5239//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005240// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005241//
5242// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5243// function designators (in C), decl references to void objects (in C), and
5244// temporaries (if building with -Wno-address-of-temporary).
5245//
5246// LValue evaluation produces values comprising a base expression of one of the
5247// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005248// - Declarations
5249// * VarDecl
5250// * FunctionDecl
5251// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005252// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005253// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005254// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005255// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005256// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005257// * ObjCEncodeExpr
5258// * AddrLabelExpr
5259// * BlockExpr
5260// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005261// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005262// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005263// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005264// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5265// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005266// * A MaterializeTemporaryExpr that has static storage duration, with no
5267// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005268// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005269//===----------------------------------------------------------------------===//
5270namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005271class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005272 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005273public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005274 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5275 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005276
Richard Smith11562c52011-10-28 17:51:58 +00005277 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005278 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005279
Peter Collingbournee9200682011-05-13 03:29:01 +00005280 bool VisitDeclRefExpr(const DeclRefExpr *E);
5281 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005282 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005283 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5284 bool VisitMemberExpr(const MemberExpr *E);
5285 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5286 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005287 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005288 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005289 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5290 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005291 bool VisitUnaryReal(const UnaryOperator *E);
5292 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005293 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5294 return VisitUnaryPreIncDec(UO);
5295 }
5296 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5297 return VisitUnaryPreIncDec(UO);
5298 }
Richard Smith3229b742013-05-05 21:17:10 +00005299 bool VisitBinAssign(const BinaryOperator *BO);
5300 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005301
Peter Collingbournee9200682011-05-13 03:29:01 +00005302 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005303 switch (E->getCastKind()) {
5304 default:
Richard Smith027bf112011-11-17 22:56:20 +00005305 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005306
Eli Friedmance3e02a2011-10-11 00:13:24 +00005307 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005308 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005309 if (!Visit(E->getSubExpr()))
5310 return false;
5311 Result.Designator.setInvalid();
5312 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005313
Richard Smith027bf112011-11-17 22:56:20 +00005314 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005315 if (!Visit(E->getSubExpr()))
5316 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005317 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005318 }
5319 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005320};
5321} // end anonymous namespace
5322
Richard Smith11562c52011-10-28 17:51:58 +00005323/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005324/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005325/// * function designators in C, and
5326/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005327/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005328static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5329 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005330 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005331 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005332 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005333}
5334
Peter Collingbournee9200682011-05-13 03:29:01 +00005335bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005336 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005337 return Success(FD);
5338 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005339 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005340 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005341 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005342 return Error(E);
5343}
Richard Smith733237d2011-10-24 23:14:33 +00005344
Faisal Vali0528a312016-11-13 06:09:16 +00005345
Richard Smith11562c52011-10-28 17:51:58 +00005346bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005347
5348 // If we are within a lambda's call operator, check whether the 'VD' referred
5349 // to within 'E' actually represents a lambda-capture that maps to a
5350 // data-member/field within the closure object, and if so, evaluate to the
5351 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00005352 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5353 isa<DeclRefExpr>(E) &&
5354 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5355 // We don't always have a complete capture-map when checking or inferring if
5356 // the function call operator meets the requirements of a constexpr function
5357 // - but we don't need to evaluate the captures to determine constexprness
5358 // (dcl.constexpr C++17).
5359 if (Info.checkingPotentialConstantExpression())
5360 return false;
5361
Faisal Vali051e3a22017-02-16 04:12:21 +00005362 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005363 // Start with 'Result' referring to the complete closure object...
5364 Result = *Info.CurrentCall->This;
5365 // ... then update it to refer to the field of the closure object
5366 // that represents the capture.
5367 if (!HandleLValueMember(Info, E, Result, FD))
5368 return false;
5369 // And if the field is of reference type, update 'Result' to refer to what
5370 // the field refers to.
5371 if (FD->getType()->isReferenceType()) {
5372 APValue RVal;
5373 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5374 RVal))
5375 return false;
5376 Result.setFrom(Info.Ctx, RVal);
5377 }
5378 return true;
5379 }
5380 }
Craig Topper36250ad2014-05-12 05:36:57 +00005381 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005382 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5383 // Only if a local variable was declared in the function currently being
5384 // evaluated, do we expect to be able to find its value in the current
5385 // frame. (Otherwise it was likely declared in an enclosing context and
5386 // could either have a valid evaluatable value (for e.g. a constexpr
5387 // variable) or be ill-formed (and trigger an appropriate evaluation
5388 // diagnostic)).
5389 if (Info.CurrentCall->Callee &&
5390 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5391 Frame = Info.CurrentCall;
5392 }
5393 }
Richard Smith3229b742013-05-05 21:17:10 +00005394
Richard Smithfec09922011-11-01 16:57:24 +00005395 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005396 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005397 Result.set({VD, Frame->Index,
5398 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00005399 return true;
5400 }
Richard Smithce40ad62011-11-12 22:28:03 +00005401 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005402 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005403
Richard Smith3229b742013-05-05 21:17:10 +00005404 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005405 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005406 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005407 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005408 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005409 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005410 return false;
5411 }
Richard Smith3229b742013-05-05 21:17:10 +00005412 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005413}
5414
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005415bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5416 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005417 // Walk through the expression to find the materialized temporary itself.
5418 SmallVector<const Expr *, 2> CommaLHSs;
5419 SmallVector<SubobjectAdjustment, 2> Adjustments;
5420 const Expr *Inner = E->GetTemporaryExpr()->
5421 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005422
Richard Smith84401042013-06-03 05:03:02 +00005423 // If we passed any comma operators, evaluate their LHSs.
5424 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5425 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5426 return false;
5427
Richard Smithe6c01442013-06-05 00:46:14 +00005428 // A materialized temporary with static storage duration can appear within the
5429 // result of a constant expression evaluation, so we need to preserve its
5430 // value for use outside this evaluation.
5431 APValue *Value;
5432 if (E->getStorageDuration() == SD_Static) {
5433 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005434 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005435 Result.set(E);
5436 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005437 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5438 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00005439 }
5440
Richard Smithea4ad5d2013-06-06 08:19:16 +00005441 QualType Type = Inner->getType();
5442
Richard Smith84401042013-06-03 05:03:02 +00005443 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005444 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5445 (E->getStorageDuration() == SD_Static &&
5446 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5447 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005448 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005449 }
Richard Smith84401042013-06-03 05:03:02 +00005450
5451 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005452 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5453 --I;
5454 switch (Adjustments[I].Kind) {
5455 case SubobjectAdjustment::DerivedToBaseAdjustment:
5456 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5457 Type, Result))
5458 return false;
5459 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5460 break;
5461
5462 case SubobjectAdjustment::FieldAdjustment:
5463 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5464 return false;
5465 Type = Adjustments[I].Field->getType();
5466 break;
5467
5468 case SubobjectAdjustment::MemberPointerAdjustment:
5469 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5470 Adjustments[I].Ptr.RHS))
5471 return false;
5472 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5473 break;
5474 }
5475 }
5476
5477 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005478}
5479
Peter Collingbournee9200682011-05-13 03:29:01 +00005480bool
5481LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005482 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5483 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005484 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5485 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005486 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005487}
5488
Richard Smith6e525142011-12-27 12:18:28 +00005489bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005490 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005491 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005492
Faisal Valie690b7a2016-07-02 22:34:24 +00005493 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005494 << E->getExprOperand()->getType()
5495 << E->getExprOperand()->getSourceRange();
5496 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005497}
5498
Francois Pichet0066db92012-04-16 04:08:35 +00005499bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5500 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005501}
Francois Pichet0066db92012-04-16 04:08:35 +00005502
Peter Collingbournee9200682011-05-13 03:29:01 +00005503bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005504 // Handle static data members.
5505 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005506 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005507 return VisitVarDecl(E, VD);
5508 }
5509
Richard Smith254a73d2011-10-28 22:34:42 +00005510 // Handle static member functions.
5511 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5512 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005513 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005514 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005515 }
5516 }
5517
Richard Smithd62306a2011-11-10 06:34:14 +00005518 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005519 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005520}
5521
Peter Collingbournee9200682011-05-13 03:29:01 +00005522bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005523 // FIXME: Deal with vectors as array subscript bases.
5524 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005525 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005526
Nick Lewyckyad888682017-04-27 07:27:36 +00005527 bool Success = true;
5528 if (!evaluatePointer(E->getBase(), Result)) {
5529 if (!Info.noteFailure())
5530 return false;
5531 Success = false;
5532 }
Mike Stump11289f42009-09-09 15:08:12 +00005533
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005534 APSInt Index;
5535 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005536 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005537
Nick Lewyckyad888682017-04-27 07:27:36 +00005538 return Success &&
5539 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005540}
Eli Friedman9a156e52008-11-12 09:44:48 +00005541
Peter Collingbournee9200682011-05-13 03:29:01 +00005542bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005543 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005544}
5545
Richard Smith66c96992012-02-18 22:04:06 +00005546bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5547 if (!Visit(E->getSubExpr()))
5548 return false;
5549 // __real is a no-op on scalar lvalues.
5550 if (E->getSubExpr()->getType()->isAnyComplexType())
5551 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5552 return true;
5553}
5554
5555bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5556 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5557 "lvalue __imag__ on scalar?");
5558 if (!Visit(E->getSubExpr()))
5559 return false;
5560 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5561 return true;
5562}
5563
Richard Smith243ef902013-05-05 23:31:59 +00005564bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005565 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005566 return Error(UO);
5567
5568 if (!this->Visit(UO->getSubExpr()))
5569 return false;
5570
Richard Smith243ef902013-05-05 23:31:59 +00005571 return handleIncDec(
5572 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005573 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005574}
5575
5576bool LValueExprEvaluator::VisitCompoundAssignOperator(
5577 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005578 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005579 return Error(CAO);
5580
Richard Smith3229b742013-05-05 21:17:10 +00005581 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005582
5583 // The overall lvalue result is the result of evaluating the LHS.
5584 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005585 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005586 Evaluate(RHS, this->Info, CAO->getRHS());
5587 return false;
5588 }
5589
Richard Smith3229b742013-05-05 21:17:10 +00005590 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5591 return false;
5592
Richard Smith43e77732013-05-07 04:50:00 +00005593 return handleCompoundAssignment(
5594 this->Info, CAO,
5595 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5596 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005597}
5598
5599bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005600 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005601 return Error(E);
5602
Richard Smith3229b742013-05-05 21:17:10 +00005603 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005604
5605 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005606 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005607 Evaluate(NewVal, this->Info, E->getRHS());
5608 return false;
5609 }
5610
Richard Smith3229b742013-05-05 21:17:10 +00005611 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5612 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005613
5614 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005615 NewVal);
5616}
5617
Eli Friedman9a156e52008-11-12 09:44:48 +00005618//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005619// Pointer Evaluation
5620//===----------------------------------------------------------------------===//
5621
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005622/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00005623/// returned by a function with the alloc_size attribute. Returns true if we
5624/// were successful. Places an unsigned number into `Result`.
5625///
5626/// This expects the given CallExpr to be a call to a function with an
5627/// alloc_size attribute.
5628static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5629 const CallExpr *Call,
5630 llvm::APInt &Result) {
5631 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5632
Joel E. Denny81508102018-03-13 14:51:22 +00005633 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5634 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005635 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5636 if (Call->getNumArgs() <= SizeArgNo)
5637 return false;
5638
5639 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5640 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5641 return false;
5642 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5643 return false;
5644 Into = Into.zextOrSelf(BitsInSizeT);
5645 return true;
5646 };
5647
5648 APSInt SizeOfElem;
5649 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5650 return false;
5651
Joel E. Denny81508102018-03-13 14:51:22 +00005652 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005653 Result = std::move(SizeOfElem);
5654 return true;
5655 }
5656
5657 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00005658 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005659 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5660 return false;
5661
5662 bool Overflow;
5663 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5664 if (Overflow)
5665 return false;
5666
5667 Result = std::move(BytesAvailable);
5668 return true;
5669}
5670
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005671/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00005672/// function.
5673static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5674 const LValue &LVal,
5675 llvm::APInt &Result) {
5676 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5677 "Can't get the size of a non alloc_size function");
5678 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5679 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5680 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5681}
5682
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005683/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00005684/// a function with the alloc_size attribute. If it was possible to do so, this
5685/// function will return true, make Result's Base point to said function call,
5686/// and mark Result's Base as invalid.
5687static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5688 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005689 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005690 return false;
5691
5692 // Because we do no form of static analysis, we only support const variables.
5693 //
5694 // Additionally, we can't support parameters, nor can we support static
5695 // variables (in the latter case, use-before-assign isn't UB; in the former,
5696 // we have no clue what they'll be assigned to).
5697 const auto *VD =
5698 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5699 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5700 return false;
5701
5702 const Expr *Init = VD->getAnyInitializer();
5703 if (!Init)
5704 return false;
5705
5706 const Expr *E = Init->IgnoreParens();
5707 if (!tryUnwrapAllocSizeCall(E))
5708 return false;
5709
5710 // Store E instead of E unwrapped so that the type of the LValue's base is
5711 // what the user wanted.
5712 Result.setInvalid(E);
5713
5714 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005715 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005716 return true;
5717}
5718
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005719namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005720class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005721 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005722 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005723 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005724
Peter Collingbournee9200682011-05-13 03:29:01 +00005725 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005726 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005727 return true;
5728 }
George Burgess IVe3763372016-12-22 02:50:20 +00005729
George Burgess IVf9013bf2017-02-10 22:52:29 +00005730 bool evaluateLValue(const Expr *E, LValue &Result) {
5731 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5732 }
5733
5734 bool evaluatePointer(const Expr *E, LValue &Result) {
5735 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5736 }
5737
George Burgess IVe3763372016-12-22 02:50:20 +00005738 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005739public:
Mike Stump11289f42009-09-09 15:08:12 +00005740
George Burgess IVf9013bf2017-02-10 22:52:29 +00005741 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5742 : ExprEvaluatorBaseTy(info), Result(Result),
5743 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005744
Richard Smith2e312c82012-03-03 22:46:17 +00005745 bool Success(const APValue &V, const Expr *E) {
5746 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005747 return true;
5748 }
Richard Smithfddd3842011-12-30 21:15:51 +00005749 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005750 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5751 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005752 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005753 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005754
John McCall45d55e42010-05-07 21:00:08 +00005755 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005756 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005757 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005758 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005759 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005760 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5761 if (Info.noteFailure())
5762 EvaluateIgnoredValue(Info, E->getSubExpr());
5763 return Error(E);
5764 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005765 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005766 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005767 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005768 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005769 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005770 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005771 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005772 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005773 }
Richard Smithd62306a2011-11-10 06:34:14 +00005774 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005775 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005776 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005777 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005778 if (!Info.CurrentCall->This) {
5779 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005780 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005781 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005782 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005783 return false;
5784 }
Richard Smithd62306a2011-11-10 06:34:14 +00005785 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005786 // If we are inside a lambda's call operator, the 'this' expression refers
5787 // to the enclosing '*this' object (either by value or reference) which is
5788 // either copied into the closure object's field that represents the '*this'
5789 // or refers to '*this'.
5790 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5791 // Update 'Result' to refer to the data member/field of the closure object
5792 // that represents the '*this' capture.
5793 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00005794 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005795 return false;
5796 // If we captured '*this' by reference, replace the field with its referent.
5797 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5798 ->isPointerType()) {
5799 APValue RVal;
5800 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5801 RVal))
5802 return false;
5803
5804 Result.setFrom(Info.Ctx, RVal);
5805 }
5806 }
Richard Smithd62306a2011-11-10 06:34:14 +00005807 return true;
5808 }
John McCallc07a0c72011-02-17 10:25:35 +00005809
Eli Friedman449fe542009-03-23 04:56:01 +00005810 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005811};
Chris Lattner05706e882008-07-11 18:11:29 +00005812} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005813
George Burgess IVf9013bf2017-02-10 22:52:29 +00005814static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5815 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005816 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005817 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005818}
5819
John McCall45d55e42010-05-07 21:00:08 +00005820bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005821 if (E->getOpcode() != BO_Add &&
5822 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005823 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005824
Chris Lattner05706e882008-07-11 18:11:29 +00005825 const Expr *PExp = E->getLHS();
5826 const Expr *IExp = E->getRHS();
5827 if (IExp->getType()->isPointerType())
5828 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005829
George Burgess IVf9013bf2017-02-10 22:52:29 +00005830 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005831 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005832 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005833
John McCall45d55e42010-05-07 21:00:08 +00005834 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005835 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005836 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005837
Richard Smith96e0c102011-11-04 02:25:55 +00005838 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005839 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005840
Ted Kremenek28831752012-08-23 20:46:57 +00005841 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005842 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005843}
Eli Friedman9a156e52008-11-12 09:44:48 +00005844
John McCall45d55e42010-05-07 21:00:08 +00005845bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005846 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005847}
Mike Stump11289f42009-09-09 15:08:12 +00005848
Richard Smith81dfef92018-07-11 00:29:05 +00005849bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5850 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005851
Eli Friedman847a2bc2009-12-27 05:43:15 +00005852 switch (E->getCastKind()) {
5853 default:
5854 break;
5855
John McCalle3027922010-08-25 11:45:40 +00005856 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005857 case CK_CPointerToObjCPointerCast:
5858 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005859 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005860 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005861 if (!Visit(SubExpr))
5862 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005863 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5864 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5865 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005866 if (!E->getType()->isVoidPointerType()) {
Richard Smith81dfef92018-07-11 00:29:05 +00005867 // If we changed anything other than cvr-qualifiers, we can't use this
5868 // value for constant folding. FIXME: Qualification conversions should
5869 // always be CK_NoOp, but we get this wrong in C.
5870 if (!Info.Ctx.hasCvrSimilarType(E->getType(), E->getSubExpr()->getType()))
5871 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005872 if (SubExpr->getType()->isVoidPointerType())
5873 CCEDiag(E, diag::note_constexpr_invalid_cast)
5874 << 3 << SubExpr->getType();
5875 else
5876 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5877 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005878 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5879 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005880 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005881
Anders Carlsson18275092010-10-31 20:41:46 +00005882 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005883 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005884 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005885 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005886 if (!Result.Base && Result.Offset.isZero())
5887 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005888
Richard Smithd62306a2011-11-10 06:34:14 +00005889 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005890 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005891 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5892 castAs<PointerType>()->getPointeeType(),
5893 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005894
Richard Smith027bf112011-11-17 22:56:20 +00005895 case CK_BaseToDerived:
5896 if (!Visit(E->getSubExpr()))
5897 return false;
5898 if (!Result.Base && Result.Offset.isZero())
5899 return true;
5900 return HandleBaseToDerivedCast(Info, E, Result);
5901
Richard Smith0b0a0b62011-10-29 20:57:55 +00005902 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005903 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005904 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005905
John McCalle3027922010-08-25 11:45:40 +00005906 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005907 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5908
Richard Smith2e312c82012-03-03 22:46:17 +00005909 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005910 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005911 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005912
John McCall45d55e42010-05-07 21:00:08 +00005913 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005914 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5915 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005916 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005917 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005918 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00005919 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005920 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005921 return true;
5922 } else {
5923 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005924 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005925 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005926 }
5927 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005928
5929 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005930 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005931 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005932 return false;
5933 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005934 APValue &Value = createTemporary(SubExpr, false, Result,
5935 *Info.CurrentCall);
5936 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005937 return false;
5938 }
Richard Smith96e0c102011-11-04 02:25:55 +00005939 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005940 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5941 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005942 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005943 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005944 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005945 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005946 }
Richard Smithdd785442011-10-31 20:57:44 +00005947
John McCalle3027922010-08-25 11:45:40 +00005948 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005949 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005950
5951 case CK_LValueToRValue: {
5952 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005953 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005954 return false;
5955
5956 APValue RVal;
5957 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5958 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5959 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005960 return InvalidBaseOK &&
5961 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005962 return Success(RVal, E);
5963 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005964 }
5965
Richard Smith11562c52011-10-28 17:51:58 +00005966 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005967}
Chris Lattner05706e882008-07-11 18:11:29 +00005968
Hal Finkel0dd05d42014-10-03 17:18:37 +00005969static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5970 // C++ [expr.alignof]p3:
5971 // When alignof is applied to a reference type, the result is the
5972 // alignment of the referenced type.
5973 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5974 T = Ref->getPointeeType();
5975
5976 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005977 if (T.getQualifiers().hasUnaligned())
5978 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005979 return Info.Ctx.toCharUnitsFromBits(
5980 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5981}
5982
5983static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5984 E = E->IgnoreParens();
5985
5986 // The kinds of expressions that we have special-case logic here for
5987 // should be kept up to date with the special checks for those
5988 // expressions in Sema.
5989
5990 // alignof decl is always accepted, even if it doesn't make sense: we default
5991 // to 1 in those cases.
5992 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5993 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5994 /*RefAsPointee*/true);
5995
5996 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5997 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5998 /*RefAsPointee*/true);
5999
6000 return GetAlignOfType(Info, E->getType());
6001}
6002
George Burgess IVe3763372016-12-22 02:50:20 +00006003// To be clear: this happily visits unsupported builtins. Better name welcomed.
6004bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6005 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6006 return true;
6007
George Burgess IVf9013bf2017-02-10 22:52:29 +00006008 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00006009 return false;
6010
6011 Result.setInvalid(E);
6012 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006013 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00006014 return true;
6015}
6016
Peter Collingbournee9200682011-05-13 03:29:01 +00006017bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006018 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00006019 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00006020
Richard Smith6328cbd2016-11-16 00:57:23 +00006021 if (unsigned BuiltinOp = E->getBuiltinCallee())
6022 return VisitBuiltinCallExpr(E, BuiltinOp);
6023
George Burgess IVe3763372016-12-22 02:50:20 +00006024 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006025}
6026
6027bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6028 unsigned BuiltinOp) {
6029 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00006030 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006031 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006032 case Builtin::BI__builtin_assume_aligned: {
6033 // We need to be very careful here because: if the pointer does not have the
6034 // asserted alignment, then the behavior is undefined, and undefined
6035 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00006036 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00006037 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00006038
Hal Finkel0dd05d42014-10-03 17:18:37 +00006039 LValue OffsetResult(Result);
6040 APSInt Alignment;
6041 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6042 return false;
Richard Smith642a2362017-01-30 23:30:26 +00006043 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00006044
6045 if (E->getNumArgs() > 2) {
6046 APSInt Offset;
6047 if (!EvaluateInteger(E->getArg(2), Offset, Info))
6048 return false;
6049
Richard Smith642a2362017-01-30 23:30:26 +00006050 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006051 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6052 }
6053
6054 // If there is a base object, then it must have the correct alignment.
6055 if (OffsetResult.Base) {
6056 CharUnits BaseAlignment;
6057 if (const ValueDecl *VD =
6058 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6059 BaseAlignment = Info.Ctx.getDeclAlign(VD);
6060 } else {
6061 BaseAlignment =
6062 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
6063 }
6064
6065 if (BaseAlignment < Align) {
6066 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00006067 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00006068 CCEDiag(E->getArg(0),
6069 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00006070 << (unsigned)BaseAlignment.getQuantity()
6071 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006072 return false;
6073 }
6074 }
6075
6076 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006077 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006078 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006079
Richard Smith642a2362017-01-30 23:30:26 +00006080 (OffsetResult.Base
6081 ? CCEDiag(E->getArg(0),
6082 diag::note_constexpr_baa_insufficient_alignment) << 1
6083 : CCEDiag(E->getArg(0),
6084 diag::note_constexpr_baa_value_insufficient_alignment))
6085 << (int)OffsetResult.Offset.getQuantity()
6086 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006087 return false;
6088 }
6089
6090 return true;
6091 }
Richard Smithe9507952016-11-12 01:39:56 +00006092
6093 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006094 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00006095 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006096 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00006097 if (Info.getLangOpts().CPlusPlus11)
6098 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6099 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00006100 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00006101 else
6102 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006103 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00006104 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006105 case Builtin::BI__builtin_wcschr:
6106 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006107 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006108 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00006109 if (!Visit(E->getArg(0)))
6110 return false;
6111 APSInt Desired;
6112 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6113 return false;
6114 uint64_t MaxLength = uint64_t(-1);
6115 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00006116 BuiltinOp != Builtin::BIwcschr &&
6117 BuiltinOp != Builtin::BI__builtin_strchr &&
6118 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00006119 APSInt N;
6120 if (!EvaluateInteger(E->getArg(2), N, Info))
6121 return false;
6122 MaxLength = N.getExtValue();
6123 }
6124
Richard Smith8110c9d2016-11-29 19:45:17 +00006125 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00006126
Richard Smith8110c9d2016-11-29 19:45:17 +00006127 // Figure out what value we're actually looking for (after converting to
6128 // the corresponding unsigned type if necessary).
6129 uint64_t DesiredVal;
6130 bool StopAtNull = false;
6131 switch (BuiltinOp) {
6132 case Builtin::BIstrchr:
6133 case Builtin::BI__builtin_strchr:
6134 // strchr compares directly to the passed integer, and therefore
6135 // always fails if given an int that is not a char.
6136 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6137 E->getArg(1)->getType(),
6138 Desired),
6139 Desired))
6140 return ZeroInitialization(E);
6141 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006142 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006143 case Builtin::BImemchr:
6144 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006145 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006146 // memchr compares by converting both sides to unsigned char. That's also
6147 // correct for strchr if we get this far (to cope with plain char being
6148 // unsigned in the strchr case).
6149 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6150 break;
Richard Smithe9507952016-11-12 01:39:56 +00006151
Richard Smith8110c9d2016-11-29 19:45:17 +00006152 case Builtin::BIwcschr:
6153 case Builtin::BI__builtin_wcschr:
6154 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006155 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006156 case Builtin::BIwmemchr:
6157 case Builtin::BI__builtin_wmemchr:
6158 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6159 DesiredVal = Desired.getZExtValue();
6160 break;
6161 }
Richard Smithe9507952016-11-12 01:39:56 +00006162
6163 for (; MaxLength; --MaxLength) {
6164 APValue Char;
6165 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6166 !Char.isInt())
6167 return false;
6168 if (Char.getInt().getZExtValue() == DesiredVal)
6169 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006170 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006171 break;
6172 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6173 return false;
6174 }
6175 // Not found: return nullptr.
6176 return ZeroInitialization(E);
6177 }
6178
Richard Smith06f71b52018-08-04 00:57:17 +00006179 case Builtin::BImemcpy:
6180 case Builtin::BImemmove:
6181 case Builtin::BIwmemcpy:
6182 case Builtin::BIwmemmove:
6183 if (Info.getLangOpts().CPlusPlus11)
6184 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6185 << /*isConstexpr*/0 << /*isConstructor*/0
6186 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6187 else
6188 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6189 LLVM_FALLTHROUGH;
6190 case Builtin::BI__builtin_memcpy:
6191 case Builtin::BI__builtin_memmove:
6192 case Builtin::BI__builtin_wmemcpy:
6193 case Builtin::BI__builtin_wmemmove: {
6194 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6195 BuiltinOp == Builtin::BIwmemmove ||
6196 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6197 BuiltinOp == Builtin::BI__builtin_wmemmove;
6198 bool Move = BuiltinOp == Builtin::BImemmove ||
6199 BuiltinOp == Builtin::BIwmemmove ||
6200 BuiltinOp == Builtin::BI__builtin_memmove ||
6201 BuiltinOp == Builtin::BI__builtin_wmemmove;
6202
6203 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00006204 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00006205 return false;
6206 LValue Dest = Result;
6207
6208 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00006209 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00006210 return false;
6211
6212 APSInt N;
6213 if (!EvaluateInteger(E->getArg(2), N, Info))
6214 return false;
6215 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6216
6217 // If the size is zero, we treat this as always being a valid no-op.
6218 // (Even if one of the src and dest pointers is null.)
6219 if (!N)
6220 return true;
6221
Richard Smith128719c2018-09-13 22:47:33 +00006222 // Otherwise, if either of the operands is null, we can't proceed. Don't
6223 // try to determine the type of the copied objects, because there aren't
6224 // any.
6225 if (!Src.Base || !Dest.Base) {
6226 APValue Val;
6227 (!Src.Base ? Src : Dest).moveInto(Val);
6228 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6229 << Move << WChar << !!Src.Base
6230 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6231 return false;
6232 }
6233 if (Src.Designator.Invalid || Dest.Designator.Invalid)
6234 return false;
6235
Richard Smith06f71b52018-08-04 00:57:17 +00006236 // We require that Src and Dest are both pointers to arrays of
6237 // trivially-copyable type. (For the wide version, the designator will be
6238 // invalid if the designated object is not a wchar_t.)
6239 QualType T = Dest.Designator.getType(Info.Ctx);
6240 QualType SrcT = Src.Designator.getType(Info.Ctx);
6241 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6242 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6243 return false;
6244 }
Petr Pavlued083f22018-10-04 09:25:44 +00006245 if (T->isIncompleteType()) {
6246 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6247 return false;
6248 }
Richard Smith06f71b52018-08-04 00:57:17 +00006249 if (!T.isTriviallyCopyableType(Info.Ctx)) {
6250 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6251 return false;
6252 }
6253
6254 // Figure out how many T's we're copying.
6255 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6256 if (!WChar) {
6257 uint64_t Remainder;
6258 llvm::APInt OrigN = N;
6259 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6260 if (Remainder) {
6261 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6262 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6263 << (unsigned)TSize;
6264 return false;
6265 }
6266 }
6267
6268 // Check that the copying will remain within the arrays, just so that we
6269 // can give a more meaningful diagnostic. This implicitly also checks that
6270 // N fits into 64 bits.
6271 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6272 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6273 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6274 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6275 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6276 << N.toString(10, /*Signed*/false);
6277 return false;
6278 }
6279 uint64_t NElems = N.getZExtValue();
6280 uint64_t NBytes = NElems * TSize;
6281
6282 // Check for overlap.
6283 int Direction = 1;
6284 if (HasSameBase(Src, Dest)) {
6285 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6286 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6287 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6288 // Dest is inside the source region.
6289 if (!Move) {
6290 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6291 return false;
6292 }
6293 // For memmove and friends, copy backwards.
6294 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6295 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6296 return false;
6297 Direction = -1;
6298 } else if (!Move && SrcOffset >= DestOffset &&
6299 SrcOffset - DestOffset < NBytes) {
6300 // Src is inside the destination region for memcpy: invalid.
6301 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6302 return false;
6303 }
6304 }
6305
6306 while (true) {
6307 APValue Val;
6308 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6309 !handleAssignment(Info, E, Dest, T, Val))
6310 return false;
6311 // Do not iterate past the last element; if we're copying backwards, that
6312 // might take us off the start of the array.
6313 if (--NElems == 0)
6314 return true;
6315 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6316 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6317 return false;
6318 }
6319 }
6320
Richard Smith6cbd65d2013-07-11 02:27:57 +00006321 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006322 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006323 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006324}
Chris Lattner05706e882008-07-11 18:11:29 +00006325
6326//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006327// Member Pointer Evaluation
6328//===----------------------------------------------------------------------===//
6329
6330namespace {
6331class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006332 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006333 MemberPtr &Result;
6334
6335 bool Success(const ValueDecl *D) {
6336 Result = MemberPtr(D);
6337 return true;
6338 }
6339public:
6340
6341 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6342 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6343
Richard Smith2e312c82012-03-03 22:46:17 +00006344 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006345 Result.setFrom(V);
6346 return true;
6347 }
Richard Smithfddd3842011-12-30 21:15:51 +00006348 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006349 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006350 }
6351
6352 bool VisitCastExpr(const CastExpr *E);
6353 bool VisitUnaryAddrOf(const UnaryOperator *E);
6354};
6355} // end anonymous namespace
6356
6357static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6358 EvalInfo &Info) {
6359 assert(E->isRValue() && E->getType()->isMemberPointerType());
6360 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6361}
6362
6363bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6364 switch (E->getCastKind()) {
6365 default:
6366 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6367
6368 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006369 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006370 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006371
6372 case CK_BaseToDerivedMemberPointer: {
6373 if (!Visit(E->getSubExpr()))
6374 return false;
6375 if (E->path_empty())
6376 return true;
6377 // Base-to-derived member pointer casts store the path in derived-to-base
6378 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6379 // the wrong end of the derived->base arc, so stagger the path by one class.
6380 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6381 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6382 PathI != PathE; ++PathI) {
6383 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6384 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6385 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006386 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006387 }
6388 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6389 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006390 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006391 return true;
6392 }
6393
6394 case CK_DerivedToBaseMemberPointer:
6395 if (!Visit(E->getSubExpr()))
6396 return false;
6397 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6398 PathE = E->path_end(); PathI != PathE; ++PathI) {
6399 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6400 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6401 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006402 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006403 }
6404 return true;
6405 }
6406}
6407
6408bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6409 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6410 // member can be formed.
6411 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6412}
6413
6414//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006415// Record Evaluation
6416//===----------------------------------------------------------------------===//
6417
6418namespace {
6419 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006420 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006421 const LValue &This;
6422 APValue &Result;
6423 public:
6424
6425 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6426 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6427
Richard Smith2e312c82012-03-03 22:46:17 +00006428 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006429 Result = V;
6430 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006431 }
Richard Smithb8348f52016-05-12 22:16:28 +00006432 bool ZeroInitialization(const Expr *E) {
6433 return ZeroInitialization(E, E->getType());
6434 }
6435 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006436
Richard Smith52a980a2015-08-28 02:43:42 +00006437 bool VisitCallExpr(const CallExpr *E) {
6438 return handleCallExpr(E, Result, &This);
6439 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006440 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006441 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006442 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6443 return VisitCXXConstructExpr(E, E->getType());
6444 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006445 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006446 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006447 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006448 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006449
6450 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006451 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006452}
Richard Smithd62306a2011-11-10 06:34:14 +00006453
Richard Smithfddd3842011-12-30 21:15:51 +00006454/// Perform zero-initialization on an object of non-union class type.
6455/// C++11 [dcl.init]p5:
6456/// To zero-initialize an object or reference of type T means:
6457/// [...]
6458/// -- if T is a (possibly cv-qualified) non-union class type,
6459/// each non-static data member and each base-class subobject is
6460/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006461static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6462 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006463 const LValue &This, APValue &Result) {
6464 assert(!RD->isUnion() && "Expected non-union class type");
6465 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6466 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006467 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006468
John McCalld7bca762012-05-01 00:38:49 +00006469 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006470 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6471
6472 if (CD) {
6473 unsigned Index = 0;
6474 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006475 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006476 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6477 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006478 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6479 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006480 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006481 Result.getStructBase(Index)))
6482 return false;
6483 }
6484 }
6485
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006486 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006487 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006488 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006489 continue;
6490
6491 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006492 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006493 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006494
David Blaikie2d7c57e2012-04-30 02:36:29 +00006495 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006496 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006497 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006498 return false;
6499 }
6500
6501 return true;
6502}
6503
Richard Smithb8348f52016-05-12 22:16:28 +00006504bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6505 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006506 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006507 if (RD->isUnion()) {
6508 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6509 // object's first non-static named data member is zero-initialized
6510 RecordDecl::field_iterator I = RD->field_begin();
6511 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006512 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006513 return true;
6514 }
6515
6516 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006517 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006518 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006519 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006520 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006521 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006522 }
6523
Richard Smith5d108602012-02-17 00:44:16 +00006524 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006525 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006526 return false;
6527 }
6528
Richard Smitha8105bc2012-01-06 16:39:00 +00006529 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006530}
6531
Richard Smithe97cbd72011-11-11 04:05:33 +00006532bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6533 switch (E->getCastKind()) {
6534 default:
6535 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6536
6537 case CK_ConstructorConversion:
6538 return Visit(E->getSubExpr());
6539
6540 case CK_DerivedToBase:
6541 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006542 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006543 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006544 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006545 if (!DerivedObject.isStruct())
6546 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006547
6548 // Derived-to-base rvalue conversion: just slice off the derived part.
6549 APValue *Value = &DerivedObject;
6550 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6551 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6552 PathE = E->path_end(); PathI != PathE; ++PathI) {
6553 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6554 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6555 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6556 RD = Base;
6557 }
6558 Result = *Value;
6559 return true;
6560 }
6561 }
6562}
6563
Richard Smithd62306a2011-11-10 06:34:14 +00006564bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006565 if (E->isTransparent())
6566 return Visit(E->getInit(0));
6567
Richard Smithd62306a2011-11-10 06:34:14 +00006568 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006569 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006570 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6571
6572 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006573 const FieldDecl *Field = E->getInitializedFieldInUnion();
6574 Result = APValue(Field);
6575 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006576 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006577
6578 // If the initializer list for a union does not contain any elements, the
6579 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006580 // FIXME: The element should be initialized from an initializer list.
6581 // Is this difference ever observable for initializer lists which
6582 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006583 ImplicitValueInitExpr VIE(Field->getType());
6584 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6585
Richard Smithd62306a2011-11-10 06:34:14 +00006586 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006587 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6588 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006589
6590 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6591 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6592 isa<CXXDefaultInitExpr>(InitExpr));
6593
Richard Smithb228a862012-02-15 02:18:13 +00006594 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006595 }
6596
Richard Smith872307e2016-03-08 22:17:41 +00006597 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006598 if (Result.isUninit())
6599 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6600 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006601 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006602 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006603
6604 // Initialize base classes.
6605 if (CXXRD) {
6606 for (const auto &Base : CXXRD->bases()) {
6607 assert(ElementNo < E->getNumInits() && "missing init for base class");
6608 const Expr *Init = E->getInit(ElementNo);
6609
6610 LValue Subobject = This;
6611 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6612 return false;
6613
6614 APValue &FieldVal = Result.getStructBase(ElementNo);
6615 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006616 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006617 return false;
6618 Success = false;
6619 }
6620 ++ElementNo;
6621 }
6622 }
6623
6624 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006625 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006626 // Anonymous bit-fields are not considered members of the class for
6627 // purposes of aggregate initialization.
6628 if (Field->isUnnamedBitfield())
6629 continue;
6630
6631 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006632
Richard Smith253c2a32012-01-27 01:14:48 +00006633 bool HaveInit = ElementNo < E->getNumInits();
6634
6635 // FIXME: Diagnostics here should point to the end of the initializer
6636 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006637 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006638 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006639 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006640
6641 // Perform an implicit value-initialization for members beyond the end of
6642 // the initializer list.
6643 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006644 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006645
Richard Smith852c9db2013-04-20 22:23:05 +00006646 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6647 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6648 isa<CXXDefaultInitExpr>(Init));
6649
Richard Smith49ca8aa2013-08-06 07:09:20 +00006650 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6651 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6652 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006653 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006654 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006655 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006656 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006657 }
6658 }
6659
Richard Smith253c2a32012-01-27 01:14:48 +00006660 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006661}
6662
Richard Smithb8348f52016-05-12 22:16:28 +00006663bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6664 QualType T) {
6665 // Note that E's type is not necessarily the type of our class here; we might
6666 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006667 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006668 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6669
Richard Smithfddd3842011-12-30 21:15:51 +00006670 bool ZeroInit = E->requiresZeroInitialization();
6671 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006672 // If we've already performed zero-initialization, we're already done.
6673 if (!Result.isUninit())
6674 return true;
6675
Richard Smithda3f4fd2014-03-05 23:32:50 +00006676 // We can get here in two different ways:
6677 // 1) We're performing value-initialization, and should zero-initialize
6678 // the object, or
6679 // 2) We're performing default-initialization of an object with a trivial
6680 // constexpr default constructor, in which case we should start the
6681 // lifetimes of all the base subobjects (there can be no data member
6682 // subobjects in this case) per [basic.life]p1.
6683 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006684 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006685 }
6686
Craig Topper36250ad2014-05-12 05:36:57 +00006687 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006688 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006689
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006690 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006691 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006692
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006693 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006694 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006695 if (const MaterializeTemporaryExpr *ME
6696 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6697 return Visit(ME->GetTemporaryExpr());
6698
Richard Smithb8348f52016-05-12 22:16:28 +00006699 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006700 return false;
6701
Craig Topper5fc8fc22014-08-27 06:28:36 +00006702 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006703 return HandleConstructorCall(E, This, Args,
6704 cast<CXXConstructorDecl>(Definition), Info,
6705 Result);
6706}
6707
6708bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6709 const CXXInheritedCtorInitExpr *E) {
6710 if (!Info.CurrentCall) {
6711 assert(Info.checkingPotentialConstantExpression());
6712 return false;
6713 }
6714
6715 const CXXConstructorDecl *FD = E->getConstructor();
6716 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6717 return false;
6718
6719 const FunctionDecl *Definition = nullptr;
6720 auto Body = FD->getBody(Definition);
6721
6722 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6723 return false;
6724
6725 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006726 cast<CXXConstructorDecl>(Definition), Info,
6727 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006728}
6729
Richard Smithcc1b96d2013-06-12 22:31:48 +00006730bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6731 const CXXStdInitializerListExpr *E) {
6732 const ConstantArrayType *ArrayType =
6733 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6734
6735 LValue Array;
6736 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6737 return false;
6738
6739 // Get a pointer to the first element of the array.
6740 Array.addArray(Info, E, ArrayType);
6741
6742 // FIXME: Perform the checks on the field types in SemaInit.
6743 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6744 RecordDecl::field_iterator Field = Record->field_begin();
6745 if (Field == Record->field_end())
6746 return Error(E);
6747
6748 // Start pointer.
6749 if (!Field->getType()->isPointerType() ||
6750 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6751 ArrayType->getElementType()))
6752 return Error(E);
6753
6754 // FIXME: What if the initializer_list type has base classes, etc?
6755 Result = APValue(APValue::UninitStruct(), 0, 2);
6756 Array.moveInto(Result.getStructField(0));
6757
6758 if (++Field == Record->field_end())
6759 return Error(E);
6760
6761 if (Field->getType()->isPointerType() &&
6762 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6763 ArrayType->getElementType())) {
6764 // End pointer.
6765 if (!HandleLValueArrayAdjustment(Info, E, Array,
6766 ArrayType->getElementType(),
6767 ArrayType->getSize().getZExtValue()))
6768 return false;
6769 Array.moveInto(Result.getStructField(1));
6770 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6771 // Length.
6772 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6773 else
6774 return Error(E);
6775
6776 if (++Field != Record->field_end())
6777 return Error(E);
6778
6779 return true;
6780}
6781
Faisal Valic72a08c2017-01-09 03:02:53 +00006782bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6783 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6784 if (ClosureClass->isInvalidDecl()) return false;
6785
6786 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00006787
Faisal Vali051e3a22017-02-16 04:12:21 +00006788 const size_t NumFields =
6789 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006790
6791 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6792 E->capture_init_end()) &&
6793 "The number of lambda capture initializers should equal the number of "
6794 "fields within the closure type");
6795
Faisal Vali051e3a22017-02-16 04:12:21 +00006796 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6797 // Iterate through all the lambda's closure object's fields and initialize
6798 // them.
6799 auto *CaptureInitIt = E->capture_init_begin();
6800 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6801 bool Success = true;
6802 for (const auto *Field : ClosureClass->fields()) {
6803 assert(CaptureInitIt != E->capture_init_end());
6804 // Get the initializer for this field
6805 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00006806
Faisal Vali051e3a22017-02-16 04:12:21 +00006807 // If there is no initializer, either this is a VLA or an error has
6808 // occurred.
6809 if (!CurFieldInit)
6810 return Error(E);
6811
6812 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6813 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6814 if (!Info.keepEvaluatingAfterFailure())
6815 return false;
6816 Success = false;
6817 }
6818 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006819 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006820 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006821}
6822
Richard Smithd62306a2011-11-10 06:34:14 +00006823static bool EvaluateRecord(const Expr *E, const LValue &This,
6824 APValue &Result, EvalInfo &Info) {
6825 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006826 "can't evaluate expression as a record rvalue");
6827 return RecordExprEvaluator(Info, This, Result).Visit(E);
6828}
6829
6830//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006831// Temporary Evaluation
6832//
6833// Temporaries are represented in the AST as rvalues, but generally behave like
6834// lvalues. The full-object of which the temporary is a subobject is implicitly
6835// materialized so that a reference can bind to it.
6836//===----------------------------------------------------------------------===//
6837namespace {
6838class TemporaryExprEvaluator
6839 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6840public:
6841 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006842 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006843
6844 /// Visit an expression which constructs the value of this temporary.
6845 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006846 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6847 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006848 }
6849
6850 bool VisitCastExpr(const CastExpr *E) {
6851 switch (E->getCastKind()) {
6852 default:
6853 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6854
6855 case CK_ConstructorConversion:
6856 return VisitConstructExpr(E->getSubExpr());
6857 }
6858 }
6859 bool VisitInitListExpr(const InitListExpr *E) {
6860 return VisitConstructExpr(E);
6861 }
6862 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6863 return VisitConstructExpr(E);
6864 }
6865 bool VisitCallExpr(const CallExpr *E) {
6866 return VisitConstructExpr(E);
6867 }
Richard Smith513955c2014-12-17 19:24:30 +00006868 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6869 return VisitConstructExpr(E);
6870 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006871 bool VisitLambdaExpr(const LambdaExpr *E) {
6872 return VisitConstructExpr(E);
6873 }
Richard Smith027bf112011-11-17 22:56:20 +00006874};
6875} // end anonymous namespace
6876
6877/// Evaluate an expression of record type as a temporary.
6878static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006879 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006880 return TemporaryExprEvaluator(Info, Result).Visit(E);
6881}
6882
6883//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006884// Vector Evaluation
6885//===----------------------------------------------------------------------===//
6886
6887namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006888 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006889 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006890 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006891 public:
Mike Stump11289f42009-09-09 15:08:12 +00006892
Richard Smith2d406342011-10-22 21:10:00 +00006893 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6894 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006895
Craig Topper9798b932015-09-29 04:30:05 +00006896 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006897 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6898 // FIXME: remove this APValue copy.
6899 Result = APValue(V.data(), V.size());
6900 return true;
6901 }
Richard Smith2e312c82012-03-03 22:46:17 +00006902 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006903 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006904 Result = V;
6905 return true;
6906 }
Richard Smithfddd3842011-12-30 21:15:51 +00006907 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006908
Richard Smith2d406342011-10-22 21:10:00 +00006909 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006910 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006911 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006912 bool VisitInitListExpr(const InitListExpr *E);
6913 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006914 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006915 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006916 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006917 };
6918} // end anonymous namespace
6919
6920static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006921 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006922 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006923}
6924
George Burgess IV533ff002015-12-11 00:23:35 +00006925bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006926 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006927 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006928
Richard Smith161f09a2011-12-06 22:44:34 +00006929 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006930 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006931
Eli Friedmanc757de22011-03-25 00:43:55 +00006932 switch (E->getCastKind()) {
6933 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006934 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006935 if (SETy->isIntegerType()) {
6936 APSInt IntResult;
6937 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006938 return false;
6939 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006940 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006941 APFloat FloatResult(0.0);
6942 if (!EvaluateFloat(SE, FloatResult, Info))
6943 return false;
6944 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006945 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006946 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006947 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006948
6949 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006950 SmallVector<APValue, 4> Elts(NElts, Val);
6951 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006952 }
Eli Friedman803acb32011-12-22 03:51:45 +00006953 case CK_BitCast: {
6954 // Evaluate the operand into an APInt we can extract from.
6955 llvm::APInt SValInt;
6956 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6957 return false;
6958 // Extract the elements
6959 QualType EltTy = VTy->getElementType();
6960 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6961 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6962 SmallVector<APValue, 4> Elts;
6963 if (EltTy->isRealFloatingType()) {
6964 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006965 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006966 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006967 FloatEltSize = 80;
6968 for (unsigned i = 0; i < NElts; i++) {
6969 llvm::APInt Elt;
6970 if (BigEndian)
6971 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6972 else
6973 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006974 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006975 }
6976 } else if (EltTy->isIntegerType()) {
6977 for (unsigned i = 0; i < NElts; i++) {
6978 llvm::APInt Elt;
6979 if (BigEndian)
6980 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6981 else
6982 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6983 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6984 }
6985 } else {
6986 return Error(E);
6987 }
6988 return Success(Elts, E);
6989 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006990 default:
Richard Smith11562c52011-10-28 17:51:58 +00006991 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006992 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006993}
6994
Richard Smith2d406342011-10-22 21:10:00 +00006995bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006996VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006997 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006998 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006999 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007000
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007001 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007002 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007003
Eli Friedmanb9c71292012-01-03 23:24:20 +00007004 // The number of initializers can be less than the number of
7005 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00007006 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00007007 // should be initialized with zeroes.
7008 unsigned CountInits = 0, CountElts = 0;
7009 while (CountElts < NumElements) {
7010 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00007011 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00007012 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00007013 APValue v;
7014 if (!EvaluateVector(E->getInit(CountInits), v, Info))
7015 return Error(E);
7016 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00007017 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00007018 Elements.push_back(v.getVectorElt(j));
7019 CountElts += vlen;
7020 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007021 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007022 if (CountInits < NumInits) {
7023 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007024 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007025 } else // trailing integer zero.
7026 sInt = Info.Ctx.MakeIntValue(0, EltTy);
7027 Elements.push_back(APValue(sInt));
7028 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007029 } else {
7030 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007031 if (CountInits < NumInits) {
7032 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007033 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007034 } else // trailing float zero.
7035 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7036 Elements.push_back(APValue(f));
7037 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00007038 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00007039 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007040 }
Richard Smith2d406342011-10-22 21:10:00 +00007041 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007042}
7043
Richard Smith2d406342011-10-22 21:10:00 +00007044bool
Richard Smithfddd3842011-12-30 21:15:51 +00007045VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007046 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00007047 QualType EltTy = VT->getElementType();
7048 APValue ZeroElement;
7049 if (EltTy->isIntegerType())
7050 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7051 else
7052 ZeroElement =
7053 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7054
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007055 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00007056 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007057}
7058
Richard Smith2d406342011-10-22 21:10:00 +00007059bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00007060 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007061 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007062}
7063
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007064//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00007065// Array Evaluation
7066//===----------------------------------------------------------------------===//
7067
7068namespace {
7069 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007070 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007071 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00007072 APValue &Result;
7073 public:
7074
Richard Smithd62306a2011-11-10 06:34:14 +00007075 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7076 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00007077
7078 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00007079 assert((V.isArray() || V.isLValue()) &&
7080 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00007081 Result = V;
7082 return true;
7083 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007084
Richard Smithfddd3842011-12-30 21:15:51 +00007085 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007086 const ConstantArrayType *CAT =
7087 Info.Ctx.getAsConstantArrayType(E->getType());
7088 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007089 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007090
7091 Result = APValue(APValue::UninitArray(), 0,
7092 CAT->getSize().getZExtValue());
7093 if (!Result.hasArrayFiller()) return true;
7094
Richard Smithfddd3842011-12-30 21:15:51 +00007095 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00007096 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007097 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00007098 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00007099 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00007100 }
7101
Richard Smith52a980a2015-08-28 02:43:42 +00007102 bool VisitCallExpr(const CallExpr *E) {
7103 return handleCallExpr(E, Result, &This);
7104 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007105 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00007106 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00007107 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00007108 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7109 const LValue &Subobject,
7110 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00007111 };
7112} // end anonymous namespace
7113
Richard Smithd62306a2011-11-10 06:34:14 +00007114static bool EvaluateArray(const Expr *E, const LValue &This,
7115 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00007116 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00007117 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007118}
7119
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007120// Return true iff the given array filler may depend on the element index.
7121static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7122 // For now, just whitelist non-class value-initialization and initialization
7123 // lists comprised of them.
7124 if (isa<ImplicitValueInitExpr>(FillerExpr))
7125 return false;
7126 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7127 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7128 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7129 return true;
7130 }
7131 return false;
7132 }
7133 return true;
7134}
7135
Richard Smithf3e9e432011-11-07 09:22:26 +00007136bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7137 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7138 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007139 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007140
Richard Smithca2cfbf2011-12-22 01:07:19 +00007141 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7142 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00007143 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00007144 LValue LV;
7145 if (!EvaluateLValue(E->getInit(0), LV, Info))
7146 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007147 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00007148 LV.moveInto(Val);
7149 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00007150 }
7151
Richard Smith253c2a32012-01-27 01:14:48 +00007152 bool Success = true;
7153
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007154 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7155 "zero-initialized array shouldn't have any initialized elts");
7156 APValue Filler;
7157 if (Result.isArray() && Result.hasArrayFiller())
7158 Filler = Result.getArrayFiller();
7159
Richard Smith9543c5e2013-04-22 14:44:29 +00007160 unsigned NumEltsToInit = E->getNumInits();
7161 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007162 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00007163
7164 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007165 // array element.
7166 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00007167 NumEltsToInit = NumElts;
7168
Nicola Zaghen3538b392018-05-15 13:30:56 +00007169 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7170 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007171
Richard Smith9543c5e2013-04-22 14:44:29 +00007172 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007173
7174 // If the array was previously zero-initialized, preserve the
7175 // zero-initialized values.
7176 if (!Filler.isUninit()) {
7177 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7178 Result.getArrayInitializedElt(I) = Filler;
7179 if (Result.hasArrayFiller())
7180 Result.getArrayFiller() = Filler;
7181 }
7182
Richard Smithd62306a2011-11-10 06:34:14 +00007183 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007184 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00007185 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7186 const Expr *Init =
7187 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00007188 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00007189 Info, Subobject, Init) ||
7190 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00007191 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007192 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00007193 return false;
7194 Success = false;
7195 }
Richard Smithd62306a2011-11-10 06:34:14 +00007196 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007197
Richard Smith9543c5e2013-04-22 14:44:29 +00007198 if (!Result.hasArrayFiller())
7199 return Success;
7200
7201 // If we get here, we have a trivial filler, which we can just evaluate
7202 // once and splat over the rest of the array elements.
7203 assert(FillerExpr && "no array filler for incomplete init list");
7204 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7205 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00007206}
7207
Richard Smith410306b2016-12-12 02:53:20 +00007208bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7209 if (E->getCommonExpr() &&
7210 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7211 Info, E->getCommonExpr()->getSourceExpr()))
7212 return false;
7213
7214 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7215
7216 uint64_t Elements = CAT->getSize().getZExtValue();
7217 Result = APValue(APValue::UninitArray(), Elements, Elements);
7218
7219 LValue Subobject = This;
7220 Subobject.addArray(Info, E, CAT);
7221
7222 bool Success = true;
7223 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7224 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7225 Info, Subobject, E->getSubExpr()) ||
7226 !HandleLValueArrayAdjustment(Info, E, Subobject,
7227 CAT->getElementType(), 1)) {
7228 if (!Info.noteFailure())
7229 return false;
7230 Success = false;
7231 }
7232 }
7233
7234 return Success;
7235}
7236
Richard Smith027bf112011-11-17 22:56:20 +00007237bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00007238 return VisitCXXConstructExpr(E, This, &Result, E->getType());
7239}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007240
Richard Smith9543c5e2013-04-22 14:44:29 +00007241bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7242 const LValue &Subobject,
7243 APValue *Value,
7244 QualType Type) {
7245 bool HadZeroInit = !Value->isUninit();
7246
7247 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7248 unsigned N = CAT->getSize().getZExtValue();
7249
7250 // Preserve the array filler if we had prior zero-initialization.
7251 APValue Filler =
7252 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7253 : APValue();
7254
7255 *Value = APValue(APValue::UninitArray(), N, N);
7256
7257 if (HadZeroInit)
7258 for (unsigned I = 0; I != N; ++I)
7259 Value->getArrayInitializedElt(I) = Filler;
7260
7261 // Initialize the elements.
7262 LValue ArrayElt = Subobject;
7263 ArrayElt.addArray(Info, E, CAT);
7264 for (unsigned I = 0; I != N; ++I)
7265 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7266 CAT->getElementType()) ||
7267 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7268 CAT->getElementType(), 1))
7269 return false;
7270
7271 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007272 }
Richard Smith027bf112011-11-17 22:56:20 +00007273
Richard Smith9543c5e2013-04-22 14:44:29 +00007274 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00007275 return Error(E);
7276
Richard Smithb8348f52016-05-12 22:16:28 +00007277 return RecordExprEvaluator(Info, Subobject, *Value)
7278 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00007279}
7280
Richard Smithf3e9e432011-11-07 09:22:26 +00007281//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007282// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007283//
7284// As a GNU extension, we support casting pointers to sufficiently-wide integer
7285// types and back in constant folding. Integer values are thus represented
7286// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00007287//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007288
7289namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007290class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007291 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00007292 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007293public:
Richard Smith2e312c82012-03-03 22:46:17 +00007294 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007295 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007296
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007297 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007298 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007299 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007300 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007301 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007302 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007303 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007304 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007305 return true;
7306 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007307 bool Success(const llvm::APSInt &SI, const Expr *E) {
7308 return Success(SI, E, Result);
7309 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007310
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007311 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007312 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007313 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007314 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007315 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007316 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007317 Result.getInt().setIsUnsigned(
7318 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007319 return true;
7320 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007321 bool Success(const llvm::APInt &I, const Expr *E) {
7322 return Success(I, E, Result);
7323 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007324
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007325 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007326 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007327 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007328 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007329 return true;
7330 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007331 bool Success(uint64_t Value, const Expr *E) {
7332 return Success(Value, E, Result);
7333 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007334
Ken Dyckdbc01912011-03-11 02:13:43 +00007335 bool Success(CharUnits Size, const Expr *E) {
7336 return Success(Size.getQuantity(), E);
7337 }
7338
Richard Smith2e312c82012-03-03 22:46:17 +00007339 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007340 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007341 Result = V;
7342 return true;
7343 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007344 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007345 }
Mike Stump11289f42009-09-09 15:08:12 +00007346
Richard Smithfddd3842011-12-30 21:15:51 +00007347 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007348
Peter Collingbournee9200682011-05-13 03:29:01 +00007349 //===--------------------------------------------------------------------===//
7350 // Visitor Methods
7351 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007352
Chris Lattner7174bf32008-07-12 00:38:25 +00007353 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007354 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007355 }
7356 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007357 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007358 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007359
7360 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7361 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007362 if (CheckReferencedDecl(E, E->getDecl()))
7363 return true;
7364
7365 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007366 }
7367 bool VisitMemberExpr(const MemberExpr *E) {
7368 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007369 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007370 return true;
7371 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007372
7373 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007374 }
7375
Peter Collingbournee9200682011-05-13 03:29:01 +00007376 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007377 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007378 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007379 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007380 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007381
Peter Collingbournee9200682011-05-13 03:29:01 +00007382 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007383 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007384
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007385 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007386 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007387 }
Mike Stump11289f42009-09-09 15:08:12 +00007388
Ted Kremeneke65b0862012-03-06 20:05:56 +00007389 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7390 return Success(E->getValue(), E);
7391 }
Richard Smith410306b2016-12-12 02:53:20 +00007392
7393 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7394 if (Info.ArrayInitIndex == uint64_t(-1)) {
7395 // We were asked to evaluate this subexpression independent of the
7396 // enclosing ArrayInitLoopExpr. We can't do that.
7397 Info.FFDiag(E);
7398 return false;
7399 }
7400 return Success(Info.ArrayInitIndex, E);
7401 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007402
Richard Smith4ce706a2011-10-11 21:43:33 +00007403 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007404 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007405 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007406 }
7407
Douglas Gregor29c42f22012-02-24 07:38:34 +00007408 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7409 return Success(E->getValue(), E);
7410 }
7411
John Wiegley6242b6a2011-04-28 00:16:57 +00007412 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7413 return Success(E->getValue(), E);
7414 }
7415
John Wiegleyf9f65842011-04-25 06:54:41 +00007416 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7417 return Success(E->getValue(), E);
7418 }
7419
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007420 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007421 bool VisitUnaryImag(const UnaryOperator *E);
7422
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007423 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007424 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007425
Eli Friedman4e7a2412009-02-27 04:45:43 +00007426 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007427};
Leonard Chandb01c3a2018-06-20 17:19:40 +00007428
7429class FixedPointExprEvaluator
7430 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
7431 APValue &Result;
7432
7433 public:
7434 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
7435 : ExprEvaluatorBaseTy(info), Result(result) {}
7436
7437 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7438 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7439 assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
7440 "Invalid evaluation result.");
7441 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7442 "Invalid evaluation result.");
7443 Result = APValue(SI);
7444 return true;
7445 }
7446 bool Success(const llvm::APSInt &SI, const Expr *E) {
7447 return Success(SI, E, Result);
7448 }
7449
7450 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7451 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7452 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7453 "Invalid evaluation result.");
7454 Result = APValue(APSInt(I));
7455 Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
7456 return true;
7457 }
7458 bool Success(const llvm::APInt &I, const Expr *E) {
7459 return Success(I, E, Result);
7460 }
7461
7462 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7463 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7464 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7465 return true;
7466 }
7467 bool Success(uint64_t Value, const Expr *E) {
7468 return Success(Value, E, Result);
7469 }
7470
7471 bool Success(CharUnits Size, const Expr *E) {
7472 return Success(Size.getQuantity(), E);
7473 }
7474
7475 bool Success(const APValue &V, const Expr *E) {
7476 if (V.isLValue() || V.isAddrLabelDiff()) {
7477 Result = V;
7478 return true;
7479 }
7480 return Success(V.getInt(), E);
7481 }
7482
7483 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7484
7485 //===--------------------------------------------------------------------===//
7486 // Visitor Methods
7487 //===--------------------------------------------------------------------===//
7488
7489 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
7490 return Success(E->getValue(), E);
7491 }
7492
7493 bool VisitUnaryOperator(const UnaryOperator *E);
7494};
Chris Lattner05706e882008-07-11 18:11:29 +00007495} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007496
Richard Smith11562c52011-10-28 17:51:58 +00007497/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7498/// produce either the integer value or a pointer.
7499///
7500/// GCC has a heinous extension which folds casts between pointer types and
7501/// pointer-sized integral types. We support this by allowing the evaluation of
7502/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7503/// Some simple arithmetic on such values is supported (they are treated much
7504/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007505static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007506 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007507 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007508 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007509}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007510
Richard Smithf57d8cb2011-12-09 22:58:01 +00007511static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007512 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007513 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007514 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007515 if (!Val.isInt()) {
7516 // FIXME: It would be better to produce the diagnostic for casting
7517 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007518 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007519 return false;
7520 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007521 Result = Val.getInt();
7522 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007523}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007524
Richard Smithf57d8cb2011-12-09 22:58:01 +00007525/// Check whether the given declaration can be directly converted to an integral
7526/// rvalue. If not, no diagnostic is produced; there are other things we can
7527/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007528bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007529 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007530 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007531 // Check for signedness/width mismatches between E type and ECD value.
7532 bool SameSign = (ECD->getInitVal().isSigned()
7533 == E->getType()->isSignedIntegerOrEnumerationType());
7534 bool SameWidth = (ECD->getInitVal().getBitWidth()
7535 == Info.Ctx.getIntWidth(E->getType()));
7536 if (SameSign && SameWidth)
7537 return Success(ECD->getInitVal(), E);
7538 else {
7539 // Get rid of mismatch (otherwise Success assertions will fail)
7540 // by computing a new value matching the type of E.
7541 llvm::APSInt Val = ECD->getInitVal();
7542 if (!SameSign)
7543 Val.setIsSigned(!ECD->getInitVal().isSigned());
7544 if (!SameWidth)
7545 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7546 return Success(Val, E);
7547 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007548 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007549 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007550}
7551
Richard Smith08b682b2018-05-23 21:18:00 +00007552/// Values returned by __builtin_classify_type, chosen to match the values
7553/// produced by GCC's builtin.
7554enum class GCCTypeClass {
7555 None = -1,
7556 Void = 0,
7557 Integer = 1,
7558 // GCC reserves 2 for character types, but instead classifies them as
7559 // integers.
7560 Enum = 3,
7561 Bool = 4,
7562 Pointer = 5,
7563 // GCC reserves 6 for references, but appears to never use it (because
7564 // expressions never have reference type, presumably).
7565 PointerToDataMember = 7,
7566 RealFloat = 8,
7567 Complex = 9,
7568 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7569 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7570 // GCC claims to reserve 11 for pointers to member functions, but *actually*
7571 // uses 12 for that purpose, same as for a class or struct. Maybe it
7572 // internally implements a pointer to member as a struct? Who knows.
7573 PointerToMemberFunction = 12, // Not a bug, see above.
7574 ClassOrStruct = 12,
7575 Union = 13,
7576 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7577 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7578 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7579 // literals.
7580};
7581
Chris Lattner86ee2862008-10-06 06:40:35 +00007582/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7583/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00007584static GCCTypeClass
7585EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7586 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00007587
Richard Smith08b682b2018-05-23 21:18:00 +00007588 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007589 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7590
7591 switch (CanTy->getTypeClass()) {
7592#define TYPE(ID, BASE)
7593#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7594#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7595#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7596#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00007597 case Type::Auto:
7598 case Type::DeducedTemplateSpecialization:
7599 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007600
7601 case Type::Builtin:
7602 switch (BT->getKind()) {
7603#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00007604#define SIGNED_TYPE(ID, SINGLETON_ID) \
7605 case BuiltinType::ID: return GCCTypeClass::Integer;
7606#define FLOATING_TYPE(ID, SINGLETON_ID) \
7607 case BuiltinType::ID: return GCCTypeClass::RealFloat;
7608#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7609 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007610#include "clang/AST/BuiltinTypes.def"
7611 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00007612 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007613
7614 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00007615 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007616
Richard Smith08b682b2018-05-23 21:18:00 +00007617 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007618 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00007619 case BuiltinType::WChar_U:
7620 case BuiltinType::Char8:
7621 case BuiltinType::Char16:
7622 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007623 case BuiltinType::UShort:
7624 case BuiltinType::UInt:
7625 case BuiltinType::ULong:
7626 case BuiltinType::ULongLong:
7627 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00007628 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007629
Leonard Chanf921d852018-06-04 16:07:52 +00007630 case BuiltinType::UShortAccum:
7631 case BuiltinType::UAccum:
7632 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00007633 case BuiltinType::UShortFract:
7634 case BuiltinType::UFract:
7635 case BuiltinType::ULongFract:
7636 case BuiltinType::SatUShortAccum:
7637 case BuiltinType::SatUAccum:
7638 case BuiltinType::SatULongAccum:
7639 case BuiltinType::SatUShortFract:
7640 case BuiltinType::SatUFract:
7641 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00007642 return GCCTypeClass::None;
7643
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007644 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007645
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007646 case BuiltinType::ObjCId:
7647 case BuiltinType::ObjCClass:
7648 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007649#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7650 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007651#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007652 case BuiltinType::OCLSampler:
7653 case BuiltinType::OCLEvent:
7654 case BuiltinType::OCLClkEvent:
7655 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007656 case BuiltinType::OCLReserveID:
Richard Smith08b682b2018-05-23 21:18:00 +00007657 return GCCTypeClass::None;
7658
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007659 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00007660 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007661 };
Richard Smith08b682b2018-05-23 21:18:00 +00007662 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007663
7664 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00007665 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007666
7667 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007668 case Type::ConstantArray:
7669 case Type::VariableArray:
7670 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00007671 case Type::FunctionNoProto:
7672 case Type::FunctionProto:
7673 return GCCTypeClass::Pointer;
7674
7675 case Type::MemberPointer:
7676 return CanTy->isMemberDataPointerType()
7677 ? GCCTypeClass::PointerToDataMember
7678 : GCCTypeClass::PointerToMemberFunction;
7679
7680 case Type::Complex:
7681 return GCCTypeClass::Complex;
7682
7683 case Type::Record:
7684 return CanTy->isUnionType() ? GCCTypeClass::Union
7685 : GCCTypeClass::ClassOrStruct;
7686
7687 case Type::Atomic:
7688 // GCC classifies _Atomic T the same as T.
7689 return EvaluateBuiltinClassifyType(
7690 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007691
7692 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007693 case Type::Vector:
7694 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007695 case Type::ObjCObject:
7696 case Type::ObjCInterface:
7697 case Type::ObjCObjectPointer:
7698 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00007699 // GCC classifies vectors as None. We follow its lead and classify all
7700 // other types that don't fit into the regular classification the same way.
7701 return GCCTypeClass::None;
7702
7703 case Type::LValueReference:
7704 case Type::RValueReference:
7705 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007706 }
7707
Richard Smith08b682b2018-05-23 21:18:00 +00007708 llvm_unreachable("unexpected type class");
7709}
7710
7711/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7712/// as GCC.
7713static GCCTypeClass
7714EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7715 // If no argument was supplied, default to None. This isn't
7716 // ideal, however it is what gcc does.
7717 if (E->getNumArgs() == 0)
7718 return GCCTypeClass::None;
7719
7720 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7721 // being an ICE, but still folds it to a constant using the type of the first
7722 // argument.
7723 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00007724}
7725
Richard Smith5fab0c92011-12-28 19:48:30 +00007726/// EvaluateBuiltinConstantPForLValue - Determine the result of
7727/// __builtin_constant_p when applied to the given lvalue.
7728///
7729/// An lvalue is only "constant" if it is a pointer or reference to the first
7730/// character of a string literal.
7731template<typename LValue>
7732static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007733 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007734 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7735}
7736
7737/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7738/// GCC as we can manage.
7739static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7740 QualType ArgType = Arg->getType();
7741
7742 // __builtin_constant_p always has one operand. The rules which gcc follows
7743 // are not precisely documented, but are as follows:
7744 //
7745 // - If the operand is of integral, floating, complex or enumeration type,
7746 // and can be folded to a known value of that type, it returns 1.
7747 // - If the operand and can be folded to a pointer to the first character
7748 // of a string literal (or such a pointer cast to an integral type), it
7749 // returns 1.
7750 //
7751 // Otherwise, it returns 0.
7752 //
7753 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7754 // its support for this does not currently work.
7755 if (ArgType->isIntegralOrEnumerationType()) {
7756 Expr::EvalResult Result;
7757 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7758 return false;
7759
7760 APValue &V = Result.Val;
7761 if (V.getKind() == APValue::Int)
7762 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007763 if (V.getKind() == APValue::LValue)
7764 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007765 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7766 return Arg->isEvaluatable(Ctx);
7767 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7768 LValue LV;
7769 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007770 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007771 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7772 : EvaluatePointer(Arg, LV, Info)) &&
7773 !Status.HasSideEffects)
7774 return EvaluateBuiltinConstantPForLValue(LV);
7775 }
7776
7777 // Anything else isn't considered to be sufficiently constant.
7778 return false;
7779}
7780
John McCall95007602010-05-10 23:27:23 +00007781/// Retrieves the "underlying object type" of the given expression,
7782/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007783static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007784 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7785 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007786 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007787 } else if (const Expr *E = B.get<const Expr*>()) {
7788 if (isa<CompoundLiteralExpr>(E))
7789 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007790 }
7791
7792 return QualType();
7793}
7794
George Burgess IV3a03fab2015-09-04 21:28:13 +00007795/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007796/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007797/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007798/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7799///
7800/// Always returns an RValue with a pointer representation.
7801static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7802 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7803
7804 auto *NoParens = E->IgnoreParens();
7805 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007806 if (Cast == nullptr)
7807 return NoParens;
7808
7809 // We only conservatively allow a few kinds of casts, because this code is
7810 // inherently a simple solution that seeks to support the common case.
7811 auto CastKind = Cast->getCastKind();
7812 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7813 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007814 return NoParens;
7815
7816 auto *SubExpr = Cast->getSubExpr();
7817 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7818 return NoParens;
7819 return ignorePointerCastsAndParens(SubExpr);
7820}
7821
George Burgess IVa51c4072015-10-16 01:49:01 +00007822/// Checks to see if the given LValue's Designator is at the end of the LValue's
7823/// record layout. e.g.
7824/// struct { struct { int a, b; } fst, snd; } obj;
7825/// obj.fst // no
7826/// obj.snd // yes
7827/// obj.fst.a // no
7828/// obj.fst.b // no
7829/// obj.snd.a // no
7830/// obj.snd.b // yes
7831///
7832/// Please note: this function is specialized for how __builtin_object_size
7833/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007834///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007835/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7836/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007837static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7838 assert(!LVal.Designator.Invalid);
7839
George Burgess IV4168d752016-06-27 19:40:41 +00007840 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7841 const RecordDecl *Parent = FD->getParent();
7842 Invalid = Parent->isInvalidDecl();
7843 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007844 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007845 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007846 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7847 };
7848
7849 auto &Base = LVal.getLValueBase();
7850 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7851 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007852 bool Invalid;
7853 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7854 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007855 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007856 for (auto *FD : IFD->chain()) {
7857 bool Invalid;
7858 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7859 return Invalid;
7860 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007861 }
7862 }
7863
George Burgess IVe3763372016-12-22 02:50:20 +00007864 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007865 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007866 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007867 // If we don't know the array bound, conservatively assume we're looking at
7868 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007869 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007870 if (BaseType->isIncompleteArrayType())
7871 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7872 else
7873 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007874 }
7875
7876 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7877 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007878 if (BaseType->isArrayType()) {
7879 // Because __builtin_object_size treats arrays as objects, we can ignore
7880 // the index iff this is the last array in the Designator.
7881 if (I + 1 == E)
7882 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007883 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7884 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007885 if (Index + 1 != CAT->getSize())
7886 return false;
7887 BaseType = CAT->getElementType();
7888 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007889 const auto *CT = BaseType->castAs<ComplexType>();
7890 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007891 if (Index != 1)
7892 return false;
7893 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007894 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007895 bool Invalid;
7896 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7897 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007898 BaseType = FD->getType();
7899 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007900 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007901 return false;
7902 }
7903 }
7904 return true;
7905}
7906
George Burgess IVe3763372016-12-22 02:50:20 +00007907/// Tests to see if the LValue has a user-specified designator (that isn't
7908/// necessarily valid). Note that this always returns 'true' if the LValue has
7909/// an unsized array as its first designator entry, because there's currently no
7910/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007911static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007912 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007913 return false;
7914
George Burgess IVe3763372016-12-22 02:50:20 +00007915 if (!LVal.Designator.Entries.empty())
7916 return LVal.Designator.isMostDerivedAnUnsizedArray();
7917
George Burgess IVa51c4072015-10-16 01:49:01 +00007918 if (!LVal.InvalidBase)
7919 return true;
7920
George Burgess IVe3763372016-12-22 02:50:20 +00007921 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7922 // the LValueBase.
7923 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7924 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007925}
7926
George Burgess IVe3763372016-12-22 02:50:20 +00007927/// Attempts to detect a user writing into a piece of memory that's impossible
7928/// to figure out the size of by just using types.
7929static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7930 const SubobjectDesignator &Designator = LVal.Designator;
7931 // Notes:
7932 // - Users can only write off of the end when we have an invalid base. Invalid
7933 // bases imply we don't know where the memory came from.
7934 // - We used to be a bit more aggressive here; we'd only be conservative if
7935 // the array at the end was flexible, or if it had 0 or 1 elements. This
7936 // broke some common standard library extensions (PR30346), but was
7937 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7938 // with some sort of whitelist. OTOH, it seems that GCC is always
7939 // conservative with the last element in structs (if it's an array), so our
7940 // current behavior is more compatible than a whitelisting approach would
7941 // be.
7942 return LVal.InvalidBase &&
7943 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7944 Designator.MostDerivedIsArrayElement &&
7945 isDesignatorAtObjectEnd(Ctx, LVal);
7946}
7947
7948/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7949/// Fails if the conversion would cause loss of precision.
7950static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7951 CharUnits &Result) {
7952 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7953 if (Int.ugt(CharUnitsMax))
7954 return false;
7955 Result = CharUnits::fromQuantity(Int.getZExtValue());
7956 return true;
7957}
7958
7959/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7960/// determine how many bytes exist from the beginning of the object to either
7961/// the end of the current subobject, or the end of the object itself, depending
7962/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007963///
George Burgess IVe3763372016-12-22 02:50:20 +00007964/// If this returns false, the value of Result is undefined.
7965static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7966 unsigned Type, const LValue &LVal,
7967 CharUnits &EndOffset) {
7968 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007969
George Burgess IV7fb7e362017-01-03 23:35:19 +00007970 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7971 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7972 return false;
7973 return HandleSizeof(Info, ExprLoc, Ty, Result);
7974 };
7975
George Burgess IVe3763372016-12-22 02:50:20 +00007976 // We want to evaluate the size of the entire object. This is a valid fallback
7977 // for when Type=1 and the designator is invalid, because we're asked for an
7978 // upper-bound.
7979 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7980 // Type=3 wants a lower bound, so we can't fall back to this.
7981 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007982 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007983
7984 llvm::APInt APEndOffset;
7985 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7986 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7987 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7988
7989 if (LVal.InvalidBase)
7990 return false;
7991
7992 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007993 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007994 }
7995
George Burgess IVe3763372016-12-22 02:50:20 +00007996 // We want to evaluate the size of a subobject.
7997 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007998
7999 // The following is a moderately common idiom in C:
8000 //
8001 // struct Foo { int a; char c[1]; };
8002 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8003 // strcpy(&F->c[0], Bar);
8004 //
George Burgess IVe3763372016-12-22 02:50:20 +00008005 // In order to not break too much legacy code, we need to support it.
8006 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8007 // If we can resolve this to an alloc_size call, we can hand that back,
8008 // because we know for certain how many bytes there are to write to.
8009 llvm::APInt APEndOffset;
8010 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8011 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8012 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8013
8014 // If we cannot determine the size of the initial allocation, then we can't
8015 // given an accurate upper-bound. However, we are still able to give
8016 // conservative lower-bounds for Type=3.
8017 if (Type == 1)
8018 return false;
8019 }
8020
8021 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00008022 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008023 return false;
8024
George Burgess IVe3763372016-12-22 02:50:20 +00008025 // According to the GCC documentation, we want the size of the subobject
8026 // denoted by the pointer. But that's not quite right -- what we actually
8027 // want is the size of the immediately-enclosing array, if there is one.
8028 int64_t ElemsRemaining;
8029 if (Designator.MostDerivedIsArrayElement &&
8030 Designator.Entries.size() == Designator.MostDerivedPathLength) {
8031 uint64_t ArraySize = Designator.getMostDerivedArraySize();
8032 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
8033 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8034 } else {
8035 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8036 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008037
George Burgess IVe3763372016-12-22 02:50:20 +00008038 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8039 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008040}
8041
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008042/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00008043/// returns true and stores the result in @p Size.
8044///
8045/// If @p WasError is non-null, this will report whether the failure to evaluate
8046/// is to be treated as an Error in IntExprEvaluator.
8047static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8048 EvalInfo &Info, uint64_t &Size) {
8049 // Determine the denoted object.
8050 LValue LVal;
8051 {
8052 // The operand of __builtin_object_size is never evaluated for side-effects.
8053 // If there are any, but we can determine the pointed-to object anyway, then
8054 // ignore the side-effects.
8055 SpeculativeEvaluationRAII SpeculativeEval(Info);
8056 FoldOffsetRAII Fold(Info);
8057
8058 if (E->isGLValue()) {
8059 // It's possible for us to be given GLValues if we're called via
8060 // Expr::tryEvaluateObjectSize.
8061 APValue RVal;
8062 if (!EvaluateAsRValue(Info, E, RVal))
8063 return false;
8064 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00008065 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8066 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00008067 return false;
8068 }
8069
8070 // If we point to before the start of the object, there are no accessible
8071 // bytes.
8072 if (LVal.getLValueOffset().isNegative()) {
8073 Size = 0;
8074 return true;
8075 }
8076
8077 CharUnits EndOffset;
8078 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8079 return false;
8080
8081 // If we've fallen outside of the end offset, just pretend there's nothing to
8082 // write to/read from.
8083 if (EndOffset <= LVal.getLValueOffset())
8084 Size = 0;
8085 else
8086 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8087 return true;
John McCall95007602010-05-10 23:27:23 +00008088}
8089
Peter Collingbournee9200682011-05-13 03:29:01 +00008090bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00008091 if (unsigned BuiltinOp = E->getBuiltinCallee())
8092 return VisitBuiltinCallExpr(E, BuiltinOp);
8093
8094 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8095}
8096
8097bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8098 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00008099 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008100 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00008101 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00008102
8103 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00008104 // The type was checked when we built the expression.
8105 unsigned Type =
8106 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8107 assert(Type <= 3 && "unexpected type");
8108
George Burgess IVe3763372016-12-22 02:50:20 +00008109 uint64_t Size;
8110 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8111 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00008112
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008113 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00008114 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00008115
Richard Smith01ade172012-05-23 04:13:20 +00008116 // Expression had no side effects, but we couldn't statically determine the
8117 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008118 switch (Info.EvalMode) {
8119 case EvalInfo::EM_ConstantExpression:
8120 case EvalInfo::EM_PotentialConstantExpression:
8121 case EvalInfo::EM_ConstantFold:
8122 case EvalInfo::EM_EvaluateForOverflow:
8123 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00008124 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008125 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008126 return Error(E);
8127 case EvalInfo::EM_ConstantExpressionUnevaluated:
8128 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008129 // Reduce it to a constant now.
8130 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008131 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00008132
8133 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00008134 }
8135
Benjamin Kramera801f4a2012-10-06 14:42:22 +00008136 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00008137 case Builtin::BI__builtin_bswap32:
8138 case Builtin::BI__builtin_bswap64: {
8139 APSInt Val;
8140 if (!EvaluateInteger(E->getArg(0), Val, Info))
8141 return false;
8142
8143 return Success(Val.byteSwap(), E);
8144 }
8145
Richard Smith8889a3d2013-06-13 06:26:32 +00008146 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00008147 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00008148
Craig Topperf95a6d92018-08-08 22:31:12 +00008149 case Builtin::BI__builtin_clrsb:
8150 case Builtin::BI__builtin_clrsbl:
8151 case Builtin::BI__builtin_clrsbll: {
8152 APSInt Val;
8153 if (!EvaluateInteger(E->getArg(0), Val, Info))
8154 return false;
8155
8156 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8157 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008158
Richard Smith80b3c8e2013-06-13 05:04:16 +00008159 case Builtin::BI__builtin_clz:
8160 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008161 case Builtin::BI__builtin_clzll:
8162 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008163 APSInt Val;
8164 if (!EvaluateInteger(E->getArg(0), Val, Info))
8165 return false;
8166 if (!Val)
8167 return Error(E);
8168
8169 return Success(Val.countLeadingZeros(), E);
8170 }
8171
Richard Smith8889a3d2013-06-13 06:26:32 +00008172 case Builtin::BI__builtin_constant_p:
8173 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
8174
Richard Smith80b3c8e2013-06-13 05:04:16 +00008175 case Builtin::BI__builtin_ctz:
8176 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008177 case Builtin::BI__builtin_ctzll:
8178 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008179 APSInt Val;
8180 if (!EvaluateInteger(E->getArg(0), Val, Info))
8181 return false;
8182 if (!Val)
8183 return Error(E);
8184
8185 return Success(Val.countTrailingZeros(), E);
8186 }
8187
Richard Smith8889a3d2013-06-13 06:26:32 +00008188 case Builtin::BI__builtin_eh_return_data_regno: {
8189 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8190 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8191 return Success(Operand, E);
8192 }
8193
8194 case Builtin::BI__builtin_expect:
8195 return Visit(E->getArg(0));
8196
8197 case Builtin::BI__builtin_ffs:
8198 case Builtin::BI__builtin_ffsl:
8199 case Builtin::BI__builtin_ffsll: {
8200 APSInt Val;
8201 if (!EvaluateInteger(E->getArg(0), Val, Info))
8202 return false;
8203
8204 unsigned N = Val.countTrailingZeros();
8205 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8206 }
8207
8208 case Builtin::BI__builtin_fpclassify: {
8209 APFloat Val(0.0);
8210 if (!EvaluateFloat(E->getArg(5), Val, Info))
8211 return false;
8212 unsigned Arg;
8213 switch (Val.getCategory()) {
8214 case APFloat::fcNaN: Arg = 0; break;
8215 case APFloat::fcInfinity: Arg = 1; break;
8216 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8217 case APFloat::fcZero: Arg = 4; break;
8218 }
8219 return Visit(E->getArg(Arg));
8220 }
8221
8222 case Builtin::BI__builtin_isinf_sign: {
8223 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00008224 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00008225 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8226 }
8227
Richard Smithea3019d2013-10-15 19:07:14 +00008228 case Builtin::BI__builtin_isinf: {
8229 APFloat Val(0.0);
8230 return EvaluateFloat(E->getArg(0), Val, Info) &&
8231 Success(Val.isInfinity() ? 1 : 0, E);
8232 }
8233
8234 case Builtin::BI__builtin_isfinite: {
8235 APFloat Val(0.0);
8236 return EvaluateFloat(E->getArg(0), Val, Info) &&
8237 Success(Val.isFinite() ? 1 : 0, E);
8238 }
8239
8240 case Builtin::BI__builtin_isnan: {
8241 APFloat Val(0.0);
8242 return EvaluateFloat(E->getArg(0), Val, Info) &&
8243 Success(Val.isNaN() ? 1 : 0, E);
8244 }
8245
8246 case Builtin::BI__builtin_isnormal: {
8247 APFloat Val(0.0);
8248 return EvaluateFloat(E->getArg(0), Val, Info) &&
8249 Success(Val.isNormal() ? 1 : 0, E);
8250 }
8251
Richard Smith8889a3d2013-06-13 06:26:32 +00008252 case Builtin::BI__builtin_parity:
8253 case Builtin::BI__builtin_parityl:
8254 case Builtin::BI__builtin_parityll: {
8255 APSInt Val;
8256 if (!EvaluateInteger(E->getArg(0), Val, Info))
8257 return false;
8258
8259 return Success(Val.countPopulation() % 2, E);
8260 }
8261
Richard Smith80b3c8e2013-06-13 05:04:16 +00008262 case Builtin::BI__builtin_popcount:
8263 case Builtin::BI__builtin_popcountl:
8264 case Builtin::BI__builtin_popcountll: {
8265 APSInt Val;
8266 if (!EvaluateInteger(E->getArg(0), Val, Info))
8267 return false;
8268
8269 return Success(Val.countPopulation(), E);
8270 }
8271
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008272 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00008273 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00008274 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008275 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008276 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00008277 << /*isConstexpr*/0 << /*isConstructor*/0
8278 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00008279 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00008280 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008281 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008282 case Builtin::BI__builtin_strlen:
8283 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00008284 // As an extension, we support __builtin_strlen() as a constant expression,
8285 // and support folding strlen() to a constant.
8286 LValue String;
8287 if (!EvaluatePointer(E->getArg(0), String, Info))
8288 return false;
8289
Richard Smith8110c9d2016-11-29 19:45:17 +00008290 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8291
Richard Smithe6c19f22013-11-15 02:10:04 +00008292 // Fast path: if it's a string literal, search the string value.
8293 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8294 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008295 // The string literal may have embedded null characters. Find the first
8296 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00008297 StringRef Str = S->getBytes();
8298 int64_t Off = String.Offset.getQuantity();
8299 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008300 S->getCharByteWidth() == 1 &&
8301 // FIXME: Add fast-path for wchar_t too.
8302 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00008303 Str = Str.substr(Off);
8304
8305 StringRef::size_type Pos = Str.find(0);
8306 if (Pos != StringRef::npos)
8307 Str = Str.substr(0, Pos);
8308
8309 return Success(Str.size(), E);
8310 }
8311
8312 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008313 }
Richard Smithe6c19f22013-11-15 02:10:04 +00008314
8315 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00008316 for (uint64_t Strlen = 0; /**/; ++Strlen) {
8317 APValue Char;
8318 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8319 !Char.isInt())
8320 return false;
8321 if (!Char.getInt())
8322 return Success(Strlen, E);
8323 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8324 return false;
8325 }
8326 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008327
Richard Smithe151bab2016-11-11 23:43:35 +00008328 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008329 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008330 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008331 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008332 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008333 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008334 // A call to strlen is not a constant expression.
8335 if (Info.getLangOpts().CPlusPlus11)
8336 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8337 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00008338 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00008339 else
8340 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008341 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00008342 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008343 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008344 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008345 case Builtin::BI__builtin_wcsncmp:
8346 case Builtin::BI__builtin_memcmp:
8347 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00008348 LValue String1, String2;
8349 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8350 !EvaluatePointer(E->getArg(1), String2, Info))
8351 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00008352
8353 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8354
Richard Smithe151bab2016-11-11 23:43:35 +00008355 uint64_t MaxLength = uint64_t(-1);
8356 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008357 BuiltinOp != Builtin::BIwcscmp &&
8358 BuiltinOp != Builtin::BI__builtin_strcmp &&
8359 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00008360 APSInt N;
8361 if (!EvaluateInteger(E->getArg(2), N, Info))
8362 return false;
8363 MaxLength = N.getExtValue();
8364 }
8365 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008366 BuiltinOp != Builtin::BIwmemcmp &&
8367 BuiltinOp != Builtin::BI__builtin_memcmp &&
8368 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00008369 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8370 BuiltinOp == Builtin::BIwcsncmp ||
8371 BuiltinOp == Builtin::BIwmemcmp ||
8372 BuiltinOp == Builtin::BI__builtin_wcscmp ||
8373 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8374 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Richard Smithe151bab2016-11-11 23:43:35 +00008375 for (; MaxLength; --MaxLength) {
8376 APValue Char1, Char2;
8377 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
8378 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
8379 !Char1.isInt() || !Char2.isInt())
8380 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00008381 if (Char1.getInt() != Char2.getInt()) {
8382 if (IsWide) // wmemcmp compares with wchar_t signedness.
8383 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8384 // memcmp always compares unsigned chars.
8385 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8386 }
Richard Smithe151bab2016-11-11 23:43:35 +00008387 if (StopAtNull && !Char1.getInt())
8388 return Success(0, E);
8389 assert(!(StopAtNull && !Char2.getInt()));
8390 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
8391 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
8392 return false;
8393 }
8394 // We hit the strncmp / memcmp limit.
8395 return Success(0, E);
8396 }
8397
Richard Smith01ba47d2012-04-13 00:45:38 +00008398 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00008399 case Builtin::BI__atomic_is_lock_free:
8400 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00008401 APSInt SizeVal;
8402 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8403 return false;
8404
8405 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8406 // of two less than the maximum inline atomic width, we know it is
8407 // lock-free. If the size isn't a power of two, or greater than the
8408 // maximum alignment where we promote atomics, we know it is not lock-free
8409 // (at least not in the sense of atomic_is_lock_free). Otherwise,
8410 // the answer can only be determined at runtime; for example, 16-byte
8411 // atomics have lock-free implementations on some, but not all,
8412 // x86-64 processors.
8413
8414 // Check power-of-two.
8415 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00008416 if (Size.isPowerOfTwo()) {
8417 // Check against inlining width.
8418 unsigned InlineWidthBits =
8419 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8420 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8421 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8422 Size == CharUnits::One() ||
8423 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8424 Expr::NPC_NeverValueDependent))
8425 // OK, we will inline appropriately-aligned operations of this size,
8426 // and _Atomic(T) is appropriately-aligned.
8427 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008428
Richard Smith01ba47d2012-04-13 00:45:38 +00008429 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8430 castAs<PointerType>()->getPointeeType();
8431 if (!PointeeType->isIncompleteType() &&
8432 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8433 // OK, we will inline operations on this object.
8434 return Success(1, E);
8435 }
8436 }
8437 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008438
Richard Smith01ba47d2012-04-13 00:45:38 +00008439 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8440 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008441 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008442 case Builtin::BIomp_is_initial_device:
8443 // We can decide statically which value the runtime would return if called.
8444 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00008445 case Builtin::BI__builtin_add_overflow:
8446 case Builtin::BI__builtin_sub_overflow:
8447 case Builtin::BI__builtin_mul_overflow:
8448 case Builtin::BI__builtin_sadd_overflow:
8449 case Builtin::BI__builtin_uadd_overflow:
8450 case Builtin::BI__builtin_uaddl_overflow:
8451 case Builtin::BI__builtin_uaddll_overflow:
8452 case Builtin::BI__builtin_usub_overflow:
8453 case Builtin::BI__builtin_usubl_overflow:
8454 case Builtin::BI__builtin_usubll_overflow:
8455 case Builtin::BI__builtin_umul_overflow:
8456 case Builtin::BI__builtin_umull_overflow:
8457 case Builtin::BI__builtin_umulll_overflow:
8458 case Builtin::BI__builtin_saddl_overflow:
8459 case Builtin::BI__builtin_saddll_overflow:
8460 case Builtin::BI__builtin_ssub_overflow:
8461 case Builtin::BI__builtin_ssubl_overflow:
8462 case Builtin::BI__builtin_ssubll_overflow:
8463 case Builtin::BI__builtin_smul_overflow:
8464 case Builtin::BI__builtin_smull_overflow:
8465 case Builtin::BI__builtin_smulll_overflow: {
8466 LValue ResultLValue;
8467 APSInt LHS, RHS;
8468
8469 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
8470 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
8471 !EvaluateInteger(E->getArg(1), RHS, Info) ||
8472 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
8473 return false;
8474
8475 APSInt Result;
8476 bool DidOverflow = false;
8477
8478 // If the types don't have to match, enlarge all 3 to the largest of them.
8479 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8480 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8481 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8482 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
8483 ResultType->isSignedIntegerOrEnumerationType();
8484 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
8485 ResultType->isSignedIntegerOrEnumerationType();
8486 uint64_t LHSSize = LHS.getBitWidth();
8487 uint64_t RHSSize = RHS.getBitWidth();
8488 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
8489 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
8490
8491 // Add an additional bit if the signedness isn't uniformly agreed to. We
8492 // could do this ONLY if there is a signed and an unsigned that both have
8493 // MaxBits, but the code to check that is pretty nasty. The issue will be
8494 // caught in the shrink-to-result later anyway.
8495 if (IsSigned && !AllSigned)
8496 ++MaxBits;
8497
8498 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
8499 !IsSigned);
8500 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
8501 !IsSigned);
8502 Result = APSInt(MaxBits, !IsSigned);
8503 }
8504
8505 // Find largest int.
8506 switch (BuiltinOp) {
8507 default:
8508 llvm_unreachable("Invalid value for BuiltinOp");
8509 case Builtin::BI__builtin_add_overflow:
8510 case Builtin::BI__builtin_sadd_overflow:
8511 case Builtin::BI__builtin_saddl_overflow:
8512 case Builtin::BI__builtin_saddll_overflow:
8513 case Builtin::BI__builtin_uadd_overflow:
8514 case Builtin::BI__builtin_uaddl_overflow:
8515 case Builtin::BI__builtin_uaddll_overflow:
8516 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
8517 : LHS.uadd_ov(RHS, DidOverflow);
8518 break;
8519 case Builtin::BI__builtin_sub_overflow:
8520 case Builtin::BI__builtin_ssub_overflow:
8521 case Builtin::BI__builtin_ssubl_overflow:
8522 case Builtin::BI__builtin_ssubll_overflow:
8523 case Builtin::BI__builtin_usub_overflow:
8524 case Builtin::BI__builtin_usubl_overflow:
8525 case Builtin::BI__builtin_usubll_overflow:
8526 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
8527 : LHS.usub_ov(RHS, DidOverflow);
8528 break;
8529 case Builtin::BI__builtin_mul_overflow:
8530 case Builtin::BI__builtin_smul_overflow:
8531 case Builtin::BI__builtin_smull_overflow:
8532 case Builtin::BI__builtin_smulll_overflow:
8533 case Builtin::BI__builtin_umul_overflow:
8534 case Builtin::BI__builtin_umull_overflow:
8535 case Builtin::BI__builtin_umulll_overflow:
8536 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
8537 : LHS.umul_ov(RHS, DidOverflow);
8538 break;
8539 }
8540
8541 // In the case where multiple sizes are allowed, truncate and see if
8542 // the values are the same.
8543 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8544 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8545 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8546 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
8547 // since it will give us the behavior of a TruncOrSelf in the case where
8548 // its parameter <= its size. We previously set Result to be at least the
8549 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
8550 // will work exactly like TruncOrSelf.
8551 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
8552 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
8553
8554 if (!APSInt::isSameValue(Temp, Result))
8555 DidOverflow = true;
8556 Result = Temp;
8557 }
8558
8559 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +00008560 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
8561 return false;
Erich Keane00958272018-06-13 20:43:27 +00008562 return Success(DidOverflow, E);
8563 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008564 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008565}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008566
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008567/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +00008568/// object referred to by the lvalue.
8569static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8570 const LValue &LV) {
8571 // A null pointer can be viewed as being "past the end" but we don't
8572 // choose to look at it that way here.
8573 if (!LV.getLValueBase())
8574 return false;
8575
8576 // If the designator is valid and refers to a subobject, we're not pointing
8577 // past the end.
8578 if (!LV.getLValueDesignator().Invalid &&
8579 !LV.getLValueDesignator().isOnePastTheEnd())
8580 return false;
8581
David Majnemerc378ca52015-08-29 08:32:55 +00008582 // A pointer to an incomplete type might be past-the-end if the type's size is
8583 // zero. We cannot tell because the type is incomplete.
8584 QualType Ty = getType(LV.getLValueBase());
8585 if (Ty->isIncompleteType())
8586 return true;
8587
Richard Smithd20f1e62014-10-21 23:01:04 +00008588 // We're a past-the-end pointer if we point to the byte after the object,
8589 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008590 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008591 return LV.getLValueOffset() == Size;
8592}
8593
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008594namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008595
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008596/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008597///
8598/// We use a data recursive algorithm for binary operators so that we are able
8599/// to handle extreme cases of chained binary operators without causing stack
8600/// overflow.
8601class DataRecursiveIntBinOpEvaluator {
8602 struct EvalResult {
8603 APValue Val;
8604 bool Failed;
8605
8606 EvalResult() : Failed(false) { }
8607
8608 void swap(EvalResult &RHS) {
8609 Val.swap(RHS.Val);
8610 Failed = RHS.Failed;
8611 RHS.Failed = false;
8612 }
8613 };
8614
8615 struct Job {
8616 const Expr *E;
8617 EvalResult LHSResult; // meaningful only for binary operator expression.
8618 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008619
David Blaikie73726062015-08-12 23:09:24 +00008620 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008621 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008622
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008623 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008624 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008625 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008626
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008627 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008628 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008629 };
8630
8631 SmallVector<Job, 16> Queue;
8632
8633 IntExprEvaluator &IntEval;
8634 EvalInfo &Info;
8635 APValue &FinalResult;
8636
8637public:
8638 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8639 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8640
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008641 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008642 /// data recursively.
8643 /// We handle binary operators that are comma, logical, or that have operands
8644 /// with integral or enumeration type.
8645 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008646 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8647 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +00008648 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008649 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008650 }
8651
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008652 bool Traverse(const BinaryOperator *E) {
8653 enqueue(E);
8654 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008655 while (!Queue.empty())
8656 process(PrevResult);
8657
8658 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008659
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008660 FinalResult.swap(PrevResult.Val);
8661 return true;
8662 }
8663
8664private:
8665 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8666 return IntEval.Success(Value, E, Result);
8667 }
8668 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8669 return IntEval.Success(Value, E, Result);
8670 }
8671 bool Error(const Expr *E) {
8672 return IntEval.Error(E);
8673 }
8674 bool Error(const Expr *E, diag::kind D) {
8675 return IntEval.Error(E, D);
8676 }
8677
8678 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8679 return Info.CCEDiag(E, D);
8680 }
8681
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008682 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008683 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008684 bool &SuppressRHSDiags);
8685
8686 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8687 const BinaryOperator *E, APValue &Result);
8688
8689 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8690 Result.Failed = !Evaluate(Result.Val, Info, E);
8691 if (Result.Failed)
8692 Result.Val = APValue();
8693 }
8694
Richard Trieuba4d0872012-03-21 23:30:30 +00008695 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008696
8697 void enqueue(const Expr *E) {
8698 E = E->IgnoreParens();
8699 Queue.resize(Queue.size()+1);
8700 Queue.back().E = E;
8701 Queue.back().Kind = Job::AnyExprKind;
8702 }
8703};
8704
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008705}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008706
8707bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008708 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008709 bool &SuppressRHSDiags) {
8710 if (E->getOpcode() == BO_Comma) {
8711 // Ignore LHS but note if we could not evaluate it.
8712 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008713 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008714 return true;
8715 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008716
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008717 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008718 bool LHSAsBool;
8719 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008720 // We were able to evaluate the LHS, see if we can get away with not
8721 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008722 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8723 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008724 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008725 }
8726 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008727 LHSResult.Failed = true;
8728
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008729 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008730 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008731 if (!Info.noteSideEffect())
8732 return false;
8733
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008734 // We can't evaluate the LHS; however, sometimes the result
8735 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8736 // Don't ignore RHS and suppress diagnostics from this arm.
8737 SuppressRHSDiags = true;
8738 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008739
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008740 return true;
8741 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008742
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008743 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8744 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008745
George Burgess IVa145e252016-05-25 22:38:36 +00008746 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008747 return false; // Ignore RHS;
8748
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008749 return true;
8750}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008751
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008752static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8753 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008754 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8755 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8756 // offsets.
8757 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8758 CharUnits &Offset = LVal.getLValueOffset();
8759 uint64_t Offset64 = Offset.getQuantity();
8760 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8761 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8762 : Offset64 + Index64);
8763}
8764
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008765bool DataRecursiveIntBinOpEvaluator::
8766 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8767 const BinaryOperator *E, APValue &Result) {
8768 if (E->getOpcode() == BO_Comma) {
8769 if (RHSResult.Failed)
8770 return false;
8771 Result = RHSResult.Val;
8772 return true;
8773 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008774
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008775 if (E->isLogicalOp()) {
8776 bool lhsResult, rhsResult;
8777 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8778 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +00008779
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008780 if (LHSIsOK) {
8781 if (RHSIsOK) {
8782 if (E->getOpcode() == BO_LOr)
8783 return Success(lhsResult || rhsResult, E, Result);
8784 else
8785 return Success(lhsResult && rhsResult, E, Result);
8786 }
8787 } else {
8788 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008789 // We can't evaluate the LHS; however, sometimes the result
8790 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8791 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008792 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008793 }
8794 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008795
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008796 return false;
8797 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008798
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008799 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8800 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +00008801
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008802 if (LHSResult.Failed || RHSResult.Failed)
8803 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008804
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008805 const APValue &LHSVal = LHSResult.Val;
8806 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +00008807
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008808 // Handle cases like (unsigned long)&a + 4.
8809 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8810 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008811 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008812 return true;
8813 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008814
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008815 // Handle cases like 4 + (unsigned long)&a
8816 if (E->getOpcode() == BO_Add &&
8817 RHSVal.isLValue() && LHSVal.isInt()) {
8818 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008819 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008820 return true;
8821 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008822
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008823 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8824 // Handle (intptr_t)&&A - (intptr_t)&&B.
8825 if (!LHSVal.getLValueOffset().isZero() ||
8826 !RHSVal.getLValueOffset().isZero())
8827 return false;
8828 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8829 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8830 if (!LHSExpr || !RHSExpr)
8831 return false;
8832 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8833 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8834 if (!LHSAddrExpr || !RHSAddrExpr)
8835 return false;
8836 // Make sure both labels come from the same function.
8837 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8838 RHSAddrExpr->getLabel()->getDeclContext())
8839 return false;
8840 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8841 return true;
8842 }
Richard Smith43e77732013-05-07 04:50:00 +00008843
8844 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008845 if (!LHSVal.isInt() || !RHSVal.isInt())
8846 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008847
8848 // Set up the width and signedness manually, in case it can't be deduced
8849 // from the operation we're performing.
8850 // FIXME: Don't do this in the cases where we can deduce it.
8851 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8852 E->getType()->isUnsignedIntegerOrEnumerationType());
8853 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8854 RHSVal.getInt(), Value))
8855 return false;
8856 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008857}
8858
Richard Trieuba4d0872012-03-21 23:30:30 +00008859void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008860 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +00008861
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008862 switch (job.Kind) {
8863 case Job::AnyExprKind: {
8864 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8865 if (shouldEnqueue(Bop)) {
8866 job.Kind = Job::BinOpKind;
8867 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008868 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008869 }
8870 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008871
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008872 EvaluateExpr(job.E, Result);
8873 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008874 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008875 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008876
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008877 case Job::BinOpKind: {
8878 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008879 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008880 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008881 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008882 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008883 }
8884 if (SuppressRHSDiags)
8885 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008886 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008887 job.Kind = Job::BinOpVisitedLHSKind;
8888 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008889 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008890 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008891
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008892 case Job::BinOpVisitedLHSKind: {
8893 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8894 EvalResult RHS;
8895 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008896 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008897 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008898 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008899 }
8900 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008901
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008902 llvm_unreachable("Invalid Job::Kind!");
8903}
8904
George Burgess IV8c892b52016-05-25 22:31:54 +00008905namespace {
8906/// Used when we determine that we should fail, but can keep evaluating prior to
8907/// noting that we had a failure.
8908class DelayedNoteFailureRAII {
8909 EvalInfo &Info;
8910 bool NoteFailure;
8911
8912public:
8913 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8914 : Info(Info), NoteFailure(NoteFailure) {}
8915 ~DelayedNoteFailureRAII() {
8916 if (NoteFailure) {
8917 bool ContinueAfterFailure = Info.noteFailure();
8918 (void)ContinueAfterFailure;
8919 assert(ContinueAfterFailure &&
8920 "Shouldn't have kept evaluating on failure.");
8921 }
8922 }
8923};
8924}
8925
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008926template <class SuccessCB, class AfterCB>
8927static bool
8928EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
8929 SuccessCB &&Success, AfterCB &&DoAfter) {
8930 assert(E->isComparisonOp() && "expected comparison operator");
8931 assert((E->getOpcode() == BO_Cmp ||
8932 E->getType()->isIntegralOrEnumerationType()) &&
8933 "unsupported binary expression evaluation");
8934 auto Error = [&](const Expr *E) {
8935 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8936 return false;
8937 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008938
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008939 using CCR = ComparisonCategoryResult;
8940 bool IsRelational = E->isRelationalOp();
8941 bool IsEquality = E->isEqualityOp();
8942 if (E->getOpcode() == BO_Cmp) {
8943 const ComparisonCategoryInfo &CmpInfo =
8944 Info.Ctx.CompCategories.getInfoForType(E->getType());
8945 IsRelational = CmpInfo.isOrdered();
8946 IsEquality = CmpInfo.isEquality();
8947 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00008948
Anders Carlssonacc79812008-11-16 07:17:21 +00008949 QualType LHSTy = E->getLHS()->getType();
8950 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008951
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008952 if (LHSTy->isIntegralOrEnumerationType() &&
8953 RHSTy->isIntegralOrEnumerationType()) {
8954 APSInt LHS, RHS;
8955 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
8956 if (!LHSOK && !Info.noteFailure())
8957 return false;
8958 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
8959 return false;
8960 if (LHS < RHS)
8961 return Success(CCR::Less, E);
8962 if (LHS > RHS)
8963 return Success(CCR::Greater, E);
8964 return Success(CCR::Equal, E);
8965 }
8966
Chandler Carruthb29a7432014-10-11 11:03:30 +00008967 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008968 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008969 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008970 if (E->isAssignmentOp()) {
8971 LValue LV;
8972 EvaluateLValue(E->getLHS(), LV, Info);
8973 LHSOK = false;
8974 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008975 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8976 if (LHSOK) {
8977 LHS.makeComplexFloat();
8978 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8979 }
8980 } else {
8981 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8982 }
George Burgess IVa145e252016-05-25 22:38:36 +00008983 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008984 return false;
8985
Chandler Carruthb29a7432014-10-11 11:03:30 +00008986 if (E->getRHS()->getType()->isRealFloatingType()) {
8987 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8988 return false;
8989 RHS.makeComplexFloat();
8990 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8991 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008992 return false;
8993
8994 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008995 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008996 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008997 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008998 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008999 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9000 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009001 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009002 assert(IsEquality && "invalid complex comparison");
9003 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
9004 LHS.getComplexIntImag() == RHS.getComplexIntImag();
9005 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009006 }
9007 }
Mike Stump11289f42009-09-09 15:08:12 +00009008
Anders Carlssonacc79812008-11-16 07:17:21 +00009009 if (LHSTy->isRealFloatingType() &&
9010 RHSTy->isRealFloatingType()) {
9011 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00009012
Richard Smith253c2a32012-01-27 01:14:48 +00009013 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009014 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00009015 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009016
Richard Smith253c2a32012-01-27 01:14:48 +00009017 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00009018 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009019
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009020 assert(E->isComparisonOp() && "Invalid binary operator!");
9021 auto GetCmpRes = [&]() {
9022 switch (LHS.compare(RHS)) {
9023 case APFloat::cmpEqual:
9024 return CCR::Equal;
9025 case APFloat::cmpLessThan:
9026 return CCR::Less;
9027 case APFloat::cmpGreaterThan:
9028 return CCR::Greater;
9029 case APFloat::cmpUnordered:
9030 return CCR::Unordered;
9031 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +00009032 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009033 };
9034 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +00009035 }
Mike Stump11289f42009-09-09 15:08:12 +00009036
Eli Friedmana38da572009-04-28 19:17:36 +00009037 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009038 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +00009039
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009040 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9041 if (!LHSOK && !Info.noteFailure())
9042 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009043
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009044 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9045 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009046
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009047 // Reject differing bases from the normal codepath; we special-case
9048 // comparisons to null.
9049 if (!HasSameBase(LHSValue, RHSValue)) {
9050 // Inequalities and subtractions between unrelated pointers have
9051 // unspecified or undefined behavior.
9052 if (!IsEquality)
9053 return Error(E);
9054 // A constant address may compare equal to the address of a symbol.
9055 // The one exception is that address of an object cannot compare equal
9056 // to a null pointer constant.
9057 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9058 (!RHSValue.Base && !RHSValue.Offset.isZero()))
9059 return Error(E);
9060 // It's implementation-defined whether distinct literals will have
9061 // distinct addresses. In clang, the result of such a comparison is
9062 // unspecified, so it is not a constant expression. However, we do know
9063 // that the address of a literal will be non-null.
9064 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9065 LHSValue.Base && RHSValue.Base)
9066 return Error(E);
9067 // We can't tell whether weak symbols will end up pointing to the same
9068 // object.
9069 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9070 return Error(E);
9071 // We can't compare the address of the start of one object with the
9072 // past-the-end address of another object, per C++ DR1652.
9073 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9074 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9075 (RHSValue.Base && RHSValue.Offset.isZero() &&
9076 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9077 return Error(E);
9078 // We can't tell whether an object is at the same address as another
9079 // zero sized object.
9080 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9081 (LHSValue.Base && isZeroSized(RHSValue)))
9082 return Error(E);
9083 return Success(CCR::Nonequal, E);
9084 }
Eli Friedman64004332009-03-23 04:38:34 +00009085
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009086 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9087 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +00009088
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009089 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9090 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +00009091
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009092 // C++11 [expr.rel]p3:
9093 // Pointers to void (after pointer conversions) can be compared, with a
9094 // result defined as follows: If both pointers represent the same
9095 // address or are both the null pointer value, the result is true if the
9096 // operator is <= or >= and false otherwise; otherwise the result is
9097 // unspecified.
9098 // We interpret this as applying to pointers to *cv* void.
9099 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9100 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +00009101
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009102 // C++11 [expr.rel]p2:
9103 // - If two pointers point to non-static data members of the same object,
9104 // or to subobjects or array elements fo such members, recursively, the
9105 // pointer to the later declared member compares greater provided the
9106 // two members have the same access control and provided their class is
9107 // not a union.
9108 // [...]
9109 // - Otherwise pointer comparisons are unspecified.
9110 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9111 bool WasArrayIndex;
9112 unsigned Mismatch = FindDesignatorMismatch(
9113 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9114 // At the point where the designators diverge, the comparison has a
9115 // specified value if:
9116 // - we are comparing array indices
9117 // - we are comparing fields of a union, or fields with the same access
9118 // Otherwise, the result is unspecified and thus the comparison is not a
9119 // constant expression.
9120 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9121 Mismatch < RHSDesignator.Entries.size()) {
9122 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9123 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9124 if (!LF && !RF)
9125 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9126 else if (!LF)
9127 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009128 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9129 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009130 else if (!RF)
9131 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009132 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9133 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009134 else if (!LF->getParent()->isUnion() &&
9135 LF->getAccess() != RF->getAccess())
9136 Info.CCEDiag(E,
9137 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009138 << LF << LF->getAccess() << RF << RF->getAccess()
9139 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +00009140 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009141 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009142
9143 // The comparison here must be unsigned, and performed with the same
9144 // width as the pointer.
9145 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9146 uint64_t CompareLHS = LHSOffset.getQuantity();
9147 uint64_t CompareRHS = RHSOffset.getQuantity();
9148 assert(PtrSize <= 64 && "Unexpected pointer width");
9149 uint64_t Mask = ~0ULL >> (64 - PtrSize);
9150 CompareLHS &= Mask;
9151 CompareRHS &= Mask;
9152
9153 // If there is a base and this is a relational operator, we can only
9154 // compare pointers within the object in question; otherwise, the result
9155 // depends on where the object is located in memory.
9156 if (!LHSValue.Base.isNull() && IsRelational) {
9157 QualType BaseTy = getType(LHSValue.Base);
9158 if (BaseTy->isIncompleteType())
9159 return Error(E);
9160 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9161 uint64_t OffsetLimit = Size.getQuantity();
9162 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9163 return Error(E);
9164 }
9165
9166 if (CompareLHS < CompareRHS)
9167 return Success(CCR::Less, E);
9168 if (CompareLHS > CompareRHS)
9169 return Success(CCR::Greater, E);
9170 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009171 }
Richard Smith7bb00672012-02-01 01:42:44 +00009172
9173 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009174 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +00009175 assert(RHSTy->isMemberPointerType() && "invalid comparison");
9176
9177 MemberPtr LHSValue, RHSValue;
9178
9179 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009180 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00009181 return false;
9182
9183 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9184 return false;
9185
9186 // C++11 [expr.eq]p2:
9187 // If both operands are null, they compare equal. Otherwise if only one is
9188 // null, they compare unequal.
9189 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9190 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009191 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009192 }
9193
9194 // Otherwise if either is a pointer to a virtual member function, the
9195 // result is unspecified.
9196 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9197 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009198 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009199 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9200 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009201 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009202
9203 // Otherwise they compare equal if and only if they would refer to the
9204 // same member of the same most derived object or the same subobject if
9205 // they were dereferenced with a hypothetical object of the associated
9206 // class type.
9207 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009208 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009209 }
9210
Richard Smithab44d9b2012-02-14 22:35:28 +00009211 if (LHSTy->isNullPtrType()) {
9212 assert(E->isComparisonOp() && "unexpected nullptr operation");
9213 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9214 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9215 // are compared, the result is true of the operator is <=, >= or ==, and
9216 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009217 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +00009218 }
9219
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009220 return DoAfter();
9221}
9222
9223bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
9224 if (!CheckLiteralType(Info, E))
9225 return false;
9226
9227 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9228 const BinaryOperator *E) {
9229 // Evaluation succeeded. Lookup the information for the comparison category
9230 // type and fetch the VarDecl for the result.
9231 const ComparisonCategoryInfo &CmpInfo =
9232 Info.Ctx.CompCategories.getInfoForType(E->getType());
9233 const VarDecl *VD =
9234 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
9235 // Check and evaluate the result as a constant expression.
9236 LValue LV;
9237 LV.set(VD);
9238 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9239 return false;
9240 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9241 };
9242 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9243 return ExprEvaluatorBaseTy::VisitBinCmp(E);
9244 });
9245}
9246
9247bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9248 // We don't call noteFailure immediately because the assignment happens after
9249 // we evaluate LHS and RHS.
9250 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
9251 return Error(E);
9252
9253 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
9254 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
9255 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
9256
9257 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
9258 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009259 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009260
9261 if (E->isComparisonOp()) {
9262 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
9263 // comparisons and then translating the result.
9264 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9265 const BinaryOperator *E) {
9266 using CCR = ComparisonCategoryResult;
9267 bool IsEqual = ResKind == CCR::Equal,
9268 IsLess = ResKind == CCR::Less,
9269 IsGreater = ResKind == CCR::Greater;
9270 auto Op = E->getOpcode();
9271 switch (Op) {
9272 default:
9273 llvm_unreachable("unsupported binary operator");
9274 case BO_EQ:
9275 case BO_NE:
9276 return Success(IsEqual == (Op == BO_EQ), E);
9277 case BO_LT: return Success(IsLess, E);
9278 case BO_GT: return Success(IsGreater, E);
9279 case BO_LE: return Success(IsEqual || IsLess, E);
9280 case BO_GE: return Success(IsEqual || IsGreater, E);
9281 }
9282 };
9283 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9284 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9285 });
9286 }
9287
9288 QualType LHSTy = E->getLHS()->getType();
9289 QualType RHSTy = E->getRHS()->getType();
9290
9291 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
9292 E->getOpcode() == BO_Sub) {
9293 LValue LHSValue, RHSValue;
9294
9295 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9296 if (!LHSOK && !Info.noteFailure())
9297 return false;
9298
9299 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9300 return false;
9301
9302 // Reject differing bases from the normal codepath; we special-case
9303 // comparisons to null.
9304 if (!HasSameBase(LHSValue, RHSValue)) {
9305 // Handle &&A - &&B.
9306 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
9307 return Error(E);
9308 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
9309 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
9310 if (!LHSExpr || !RHSExpr)
9311 return Error(E);
9312 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9313 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9314 if (!LHSAddrExpr || !RHSAddrExpr)
9315 return Error(E);
9316 // Make sure both labels come from the same function.
9317 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9318 RHSAddrExpr->getLabel()->getDeclContext())
9319 return Error(E);
9320 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
9321 }
9322 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9323 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9324
9325 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9326 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9327
9328 // C++11 [expr.add]p6:
9329 // Unless both pointers point to elements of the same array object, or
9330 // one past the last element of the array object, the behavior is
9331 // undefined.
9332 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
9333 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
9334 RHSDesignator))
9335 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
9336
9337 QualType Type = E->getLHS()->getType();
9338 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
9339
9340 CharUnits ElementSize;
9341 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
9342 return false;
9343
9344 // As an extension, a type may have zero size (empty struct or union in
9345 // C, array of zero length). Pointer subtraction in such cases has
9346 // undefined behavior, so is not constant.
9347 if (ElementSize.isZero()) {
9348 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
9349 << ElementType;
9350 return false;
9351 }
9352
9353 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
9354 // and produce incorrect results when it overflows. Such behavior
9355 // appears to be non-conforming, but is common, so perhaps we should
9356 // assume the standard intended for such cases to be undefined behavior
9357 // and check for them.
9358
9359 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
9360 // overflow in the final conversion to ptrdiff_t.
9361 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
9362 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
9363 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
9364 false);
9365 APSInt TrueResult = (LHS - RHS) / ElemSize;
9366 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
9367
9368 if (Result.extend(65) != TrueResult &&
9369 !HandleOverflow(Info, E, TrueResult, E->getType()))
9370 return false;
9371 return Success(Result, E);
9372 }
9373
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009374 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00009375}
9376
Peter Collingbournee190dee2011-03-11 19:24:49 +00009377/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
9378/// a result as the expression's type.
9379bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
9380 const UnaryExprOrTypeTraitExpr *E) {
9381 switch(E->getKind()) {
9382 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00009383 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00009384 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009385 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00009386 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009387 }
Eli Friedman64004332009-03-23 04:38:34 +00009388
Peter Collingbournee190dee2011-03-11 19:24:49 +00009389 case UETT_VecStep: {
9390 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00009391
Peter Collingbournee190dee2011-03-11 19:24:49 +00009392 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00009393 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00009394
Peter Collingbournee190dee2011-03-11 19:24:49 +00009395 // The vec_step built-in functions that take a 3-component
9396 // vector return 4. (OpenCL 1.1 spec 6.11.12)
9397 if (n == 3)
9398 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00009399
Peter Collingbournee190dee2011-03-11 19:24:49 +00009400 return Success(n, E);
9401 } else
9402 return Success(1, E);
9403 }
9404
9405 case UETT_SizeOf: {
9406 QualType SrcTy = E->getTypeOfArgument();
9407 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9408 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00009409 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9410 SrcTy = Ref->getPointeeType();
9411
Richard Smithd62306a2011-11-10 06:34:14 +00009412 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00009413 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00009414 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00009415 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009416 }
Alexey Bataev00396512015-07-02 03:40:19 +00009417 case UETT_OpenMPRequiredSimdAlign:
9418 assert(E->isArgumentType());
9419 return Success(
9420 Info.Ctx.toCharUnitsFromBits(
9421 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9422 .getQuantity(),
9423 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009424 }
9425
9426 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00009427}
9428
Peter Collingbournee9200682011-05-13 03:29:01 +00009429bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009430 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00009431 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00009432 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009433 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00009434 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00009435 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00009436 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00009437 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00009438 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00009439 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00009440 APSInt IdxResult;
9441 if (!EvaluateInteger(Idx, IdxResult, Info))
9442 return false;
9443 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9444 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009445 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009446 CurrentType = AT->getElementType();
9447 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9448 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00009449 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00009450 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009451
James Y Knight7281c352015-12-29 22:31:18 +00009452 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00009453 FieldDecl *MemberDecl = ON.getField();
9454 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009455 if (!RT)
9456 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009457 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009458 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00009459 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00009460 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00009461 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00009462 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00009463 CurrentType = MemberDecl->getType().getNonReferenceType();
9464 break;
9465 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009466
James Y Knight7281c352015-12-29 22:31:18 +00009467 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00009468 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00009469
James Y Knight7281c352015-12-29 22:31:18 +00009470 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00009471 CXXBaseSpecifier *BaseSpec = ON.getBase();
9472 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00009473 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009474
9475 // Find the layout of the class whose base we are looking into.
9476 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009477 if (!RT)
9478 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009479 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009480 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00009481 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9482
9483 // Find the base class itself.
9484 CurrentType = BaseSpec->getType();
9485 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9486 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009487 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +00009488
Douglas Gregord1702062010-04-29 00:18:15 +00009489 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00009490 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00009491 break;
9492 }
Douglas Gregor882211c2010-04-28 22:16:22 +00009493 }
9494 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009495 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009496}
9497
Chris Lattnere13042c2008-07-11 19:10:17 +00009498bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009499 switch (E->getOpcode()) {
9500 default:
9501 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9502 // See C99 6.6p3.
9503 return Error(E);
9504 case UO_Extension:
9505 // FIXME: Should extension allow i-c-e extension expressions in its scope?
9506 // If so, we could clear the diagnostic ID.
9507 return Visit(E->getSubExpr());
9508 case UO_Plus:
9509 // The result is just the value.
9510 return Visit(E->getSubExpr());
9511 case UO_Minus: {
9512 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00009513 return false;
9514 if (!Result.isInt()) return Error(E);
9515 const APSInt &Value = Result.getInt();
9516 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9517 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9518 E->getType()))
9519 return false;
Richard Smithfe800032012-01-31 04:08:20 +00009520 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009521 }
9522 case UO_Not: {
9523 if (!Visit(E->getSubExpr()))
9524 return false;
9525 if (!Result.isInt()) return Error(E);
9526 return Success(~Result.getInt(), E);
9527 }
9528 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00009529 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00009530 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00009531 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009532 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00009533 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009534 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009535}
Mike Stump11289f42009-09-09 15:08:12 +00009536
Chris Lattner477c4be2008-07-12 01:15:53 +00009537/// HandleCast - This is used to evaluate implicit or explicit casts where the
9538/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00009539bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9540 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009541 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00009542 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009543
Eli Friedmanc757de22011-03-25 00:43:55 +00009544 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00009545 case CK_BaseToDerived:
9546 case CK_DerivedToBase:
9547 case CK_UncheckedDerivedToBase:
9548 case CK_Dynamic:
9549 case CK_ToUnion:
9550 case CK_ArrayToPointerDecay:
9551 case CK_FunctionToPointerDecay:
9552 case CK_NullToPointer:
9553 case CK_NullToMemberPointer:
9554 case CK_BaseToDerivedMemberPointer:
9555 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00009556 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00009557 case CK_ConstructorConversion:
9558 case CK_IntegralToPointer:
9559 case CK_ToVoid:
9560 case CK_VectorSplat:
9561 case CK_IntegralToFloating:
9562 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009563 case CK_CPointerToObjCPointerCast:
9564 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009565 case CK_AnyPointerToBlockPointerCast:
9566 case CK_ObjCObjectLValueCast:
9567 case CK_FloatingRealToComplex:
9568 case CK_FloatingComplexToReal:
9569 case CK_FloatingComplexCast:
9570 case CK_FloatingComplexToIntegralComplex:
9571 case CK_IntegralRealToComplex:
9572 case CK_IntegralComplexCast:
9573 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00009574 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009575 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009576 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009577 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009578 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009579 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00009580 llvm_unreachable("invalid cast kind for integral value");
9581
Eli Friedman9faf2f92011-03-25 19:07:11 +00009582 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009583 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009584 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00009585 case CK_ARCProduceObject:
9586 case CK_ARCConsumeObject:
9587 case CK_ARCReclaimReturnedObject:
9588 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009589 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009590 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009591
Richard Smith4ef685b2012-01-17 21:17:26 +00009592 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00009593 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009594 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009595 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009596 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009597
9598 case CK_MemberPointerToBoolean:
9599 case CK_PointerToBoolean:
9600 case CK_IntegralToBoolean:
9601 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009602 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009603 case CK_FloatingComplexToBoolean:
9604 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009605 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009606 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009607 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009608 uint64_t IntResult = BoolResult;
9609 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9610 IntResult = (uint64_t)-1;
9611 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009612 }
9613
Eli Friedmanc757de22011-03-25 00:43:55 +00009614 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009615 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009616 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009617
Eli Friedman742421e2009-02-20 01:15:07 +00009618 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009619 // Allow casts of address-of-label differences if they are no-ops
9620 // or narrowing. (The narrowing case isn't actually guaranteed to
9621 // be constant-evaluatable except in some narrow cases which are hard
9622 // to detect here. We let it through on the assumption the user knows
9623 // what they are doing.)
9624 if (Result.isAddrLabelDiff())
9625 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009626 // Only allow casts of lvalues if they are lossless.
9627 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9628 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009629
Richard Smith911e1422012-01-30 22:27:01 +00009630 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9631 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009632 }
Mike Stump11289f42009-09-09 15:08:12 +00009633
Eli Friedmanc757de22011-03-25 00:43:55 +00009634 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009635 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9636
John McCall45d55e42010-05-07 21:00:08 +00009637 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009638 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009639 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009640
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009641 if (LV.getLValueBase()) {
9642 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009643 // FIXME: Allow a larger integer size than the pointer size, and allow
9644 // narrowing back down to pointer width in subsequent integral casts.
9645 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009646 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009647 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009648
Richard Smithcf74da72011-11-16 07:18:12 +00009649 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009650 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009651 return true;
9652 }
9653
Yaxun Liu402804b2016-12-15 08:09:08 +00009654 uint64_t V;
9655 if (LV.isNullPointer())
9656 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9657 else
9658 V = LV.getLValueOffset().getQuantity();
9659
9660 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009661 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009662 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009663
Eli Friedmanc757de22011-03-25 00:43:55 +00009664 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009665 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009666 if (!EvaluateComplex(SubExpr, C, Info))
9667 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009668 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009669 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009670
Eli Friedmanc757de22011-03-25 00:43:55 +00009671 case CK_FloatingToIntegral: {
9672 APFloat F(0.0);
9673 if (!EvaluateFloat(SubExpr, F, Info))
9674 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009675
Richard Smith357362d2011-12-13 06:39:58 +00009676 APSInt Value;
9677 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9678 return false;
9679 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009680 }
9681 }
Mike Stump11289f42009-09-09 15:08:12 +00009682
Eli Friedmanc757de22011-03-25 00:43:55 +00009683 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009684}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009685
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009686bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9687 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009688 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009689 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9690 return false;
9691 if (!LV.isComplexInt())
9692 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009693 return Success(LV.getComplexIntReal(), E);
9694 }
9695
9696 return Visit(E->getSubExpr());
9697}
9698
Eli Friedman4e7a2412009-02-27 04:45:43 +00009699bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009700 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009701 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009702 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9703 return false;
9704 if (!LV.isComplexInt())
9705 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009706 return Success(LV.getComplexIntImag(), E);
9707 }
9708
Richard Smith4a678122011-10-24 18:44:57 +00009709 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009710 return Success(0, E);
9711}
9712
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009713bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9714 return Success(E->getPackLength(), E);
9715}
9716
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009717bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9718 return Success(E->getValue(), E);
9719}
9720
Leonard Chandb01c3a2018-06-20 17:19:40 +00009721bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9722 switch (E->getOpcode()) {
9723 default:
9724 // Invalid unary operators
9725 return Error(E);
9726 case UO_Plus:
9727 // The result is just the value.
9728 return Visit(E->getSubExpr());
9729 case UO_Minus: {
9730 if (!Visit(E->getSubExpr())) return false;
9731 if (!Result.isInt()) return Error(E);
9732 const APSInt &Value = Result.getInt();
9733 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
9734 SmallString<64> S;
9735 FixedPointValueToString(S, Value,
Leonard Chanc03642e2018-08-06 16:05:08 +00009736 Info.Ctx.getTypeInfo(E->getType()).Width);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009737 Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
9738 if (Info.noteUndefinedBehavior()) return false;
9739 }
9740 return Success(-Value, E);
9741 }
9742 case UO_LNot: {
9743 bool bres;
9744 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9745 return false;
9746 return Success(!bres, E);
9747 }
9748 }
9749}
9750
Chris Lattner05706e882008-07-11 18:11:29 +00009751//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009752// Float Evaluation
9753//===----------------------------------------------------------------------===//
9754
9755namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009756class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009757 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009758 APFloat &Result;
9759public:
9760 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009761 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009762
Richard Smith2e312c82012-03-03 22:46:17 +00009763 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009764 Result = V.getFloat();
9765 return true;
9766 }
Eli Friedman24c01542008-08-22 00:06:13 +00009767
Richard Smithfddd3842011-12-30 21:15:51 +00009768 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009769 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9770 return true;
9771 }
9772
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009773 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009774
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009775 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009776 bool VisitBinaryOperator(const BinaryOperator *E);
9777 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009778 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009779
John McCallb1fb0d32010-05-07 22:08:54 +00009780 bool VisitUnaryReal(const UnaryOperator *E);
9781 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009782
Richard Smithfddd3842011-12-30 21:15:51 +00009783 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009784};
9785} // end anonymous namespace
9786
9787static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009788 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009789 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009790}
9791
Jay Foad39c79802011-01-12 09:06:06 +00009792static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009793 QualType ResultTy,
9794 const Expr *Arg,
9795 bool SNaN,
9796 llvm::APFloat &Result) {
9797 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9798 if (!S) return false;
9799
9800 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9801
9802 llvm::APInt fill;
9803
9804 // Treat empty strings as if they were zero.
9805 if (S->getString().empty())
9806 fill = llvm::APInt(32, 0);
9807 else if (S->getString().getAsInteger(0, fill))
9808 return false;
9809
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009810 if (Context.getTargetInfo().isNan2008()) {
9811 if (SNaN)
9812 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9813 else
9814 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9815 } else {
9816 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9817 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9818 // a different encoding to what became a standard in 2008, and for pre-
9819 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9820 // sNaN. This is now known as "legacy NaN" encoding.
9821 if (SNaN)
9822 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9823 else
9824 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9825 }
9826
John McCall16291492010-02-28 13:00:19 +00009827 return true;
9828}
9829
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009830bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009831 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009832 default:
9833 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9834
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009835 case Builtin::BI__builtin_huge_val:
9836 case Builtin::BI__builtin_huge_valf:
9837 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009838 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009839 case Builtin::BI__builtin_inf:
9840 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009841 case Builtin::BI__builtin_infl:
9842 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009843 const llvm::fltSemantics &Sem =
9844 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009845 Result = llvm::APFloat::getInf(Sem);
9846 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009847 }
Mike Stump11289f42009-09-09 15:08:12 +00009848
John McCall16291492010-02-28 13:00:19 +00009849 case Builtin::BI__builtin_nans:
9850 case Builtin::BI__builtin_nansf:
9851 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009852 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009853 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9854 true, Result))
9855 return Error(E);
9856 return true;
John McCall16291492010-02-28 13:00:19 +00009857
Chris Lattner0b7282e2008-10-06 06:31:58 +00009858 case Builtin::BI__builtin_nan:
9859 case Builtin::BI__builtin_nanf:
9860 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009861 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +00009862 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009863 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009864 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9865 false, Result))
9866 return Error(E);
9867 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009868
9869 case Builtin::BI__builtin_fabs:
9870 case Builtin::BI__builtin_fabsf:
9871 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009872 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009873 if (!EvaluateFloat(E->getArg(0), Result, Info))
9874 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009875
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009876 if (Result.isNegative())
9877 Result.changeSign();
9878 return true;
9879
Richard Smith8889a3d2013-06-13 06:26:32 +00009880 // FIXME: Builtin::BI__builtin_powi
9881 // FIXME: Builtin::BI__builtin_powif
9882 // FIXME: Builtin::BI__builtin_powil
9883
Mike Stump11289f42009-09-09 15:08:12 +00009884 case Builtin::BI__builtin_copysign:
9885 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009886 case Builtin::BI__builtin_copysignl:
9887 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009888 APFloat RHS(0.);
9889 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9890 !EvaluateFloat(E->getArg(1), RHS, Info))
9891 return false;
9892 Result.copySign(RHS);
9893 return true;
9894 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009895 }
9896}
9897
John McCallb1fb0d32010-05-07 22:08:54 +00009898bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009899 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9900 ComplexValue CV;
9901 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9902 return false;
9903 Result = CV.FloatReal;
9904 return true;
9905 }
9906
9907 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009908}
9909
9910bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009911 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9912 ComplexValue CV;
9913 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9914 return false;
9915 Result = CV.FloatImag;
9916 return true;
9917 }
9918
Richard Smith4a678122011-10-24 18:44:57 +00009919 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009920 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9921 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009922 return true;
9923}
9924
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009925bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009926 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009927 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009928 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009929 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009930 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009931 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9932 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009933 Result.changeSign();
9934 return true;
9935 }
9936}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009937
Eli Friedman24c01542008-08-22 00:06:13 +00009938bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009939 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9940 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009941
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009942 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009943 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009944 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009945 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009946 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9947 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009948}
9949
9950bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9951 Result = E->getValue();
9952 return true;
9953}
9954
Peter Collingbournee9200682011-05-13 03:29:01 +00009955bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9956 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009957
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009958 switch (E->getCastKind()) {
9959 default:
Richard Smith11562c52011-10-28 17:51:58 +00009960 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009961
9962 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009963 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009964 return EvaluateInteger(SubExpr, IntResult, Info) &&
9965 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9966 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009967 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009968
9969 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009970 if (!Visit(SubExpr))
9971 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009972 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9973 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009974 }
John McCalld7646252010-11-14 08:17:51 +00009975
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009976 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009977 ComplexValue V;
9978 if (!EvaluateComplex(SubExpr, V, Info))
9979 return false;
9980 Result = V.getComplexFloatReal();
9981 return true;
9982 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009983 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009984}
9985
Eli Friedman24c01542008-08-22 00:06:13 +00009986//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009987// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009988//===----------------------------------------------------------------------===//
9989
9990namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009991class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009992 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009993 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009994
Anders Carlsson537969c2008-11-16 20:27:53 +00009995public:
John McCall93d91dc2010-05-07 17:22:02 +00009996 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009997 : ExprEvaluatorBaseTy(info), Result(Result) {}
9998
Richard Smith2e312c82012-03-03 22:46:17 +00009999 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010000 Result.setFrom(V);
10001 return true;
10002 }
Mike Stump11289f42009-09-09 15:08:12 +000010003
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010004 bool ZeroInitialization(const Expr *E);
10005
Anders Carlsson537969c2008-11-16 20:27:53 +000010006 //===--------------------------------------------------------------------===//
10007 // Visitor Methods
10008 //===--------------------------------------------------------------------===//
10009
Peter Collingbournee9200682011-05-13 03:29:01 +000010010 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000010011 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000010012 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010013 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010014 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010015};
10016} // end anonymous namespace
10017
John McCall93d91dc2010-05-07 17:22:02 +000010018static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
10019 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000010020 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010021 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010022}
10023
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010024bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000010025 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010026 if (ElemTy->isRealFloatingType()) {
10027 Result.makeComplexFloat();
10028 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10029 Result.FloatReal = Zero;
10030 Result.FloatImag = Zero;
10031 } else {
10032 Result.makeComplexInt();
10033 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10034 Result.IntReal = Zero;
10035 Result.IntImag = Zero;
10036 }
10037 return true;
10038}
10039
Peter Collingbournee9200682011-05-13 03:29:01 +000010040bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10041 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010042
10043 if (SubExpr->getType()->isRealFloatingType()) {
10044 Result.makeComplexFloat();
10045 APFloat &Imag = Result.FloatImag;
10046 if (!EvaluateFloat(SubExpr, Imag, Info))
10047 return false;
10048
10049 Result.FloatReal = APFloat(Imag.getSemantics());
10050 return true;
10051 } else {
10052 assert(SubExpr->getType()->isIntegerType() &&
10053 "Unexpected imaginary literal.");
10054
10055 Result.makeComplexInt();
10056 APSInt &Imag = Result.IntImag;
10057 if (!EvaluateInteger(SubExpr, Imag, Info))
10058 return false;
10059
10060 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10061 return true;
10062 }
10063}
10064
Peter Collingbournee9200682011-05-13 03:29:01 +000010065bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010066
John McCallfcef3cf2010-12-14 17:51:41 +000010067 switch (E->getCastKind()) {
10068 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010069 case CK_BaseToDerived:
10070 case CK_DerivedToBase:
10071 case CK_UncheckedDerivedToBase:
10072 case CK_Dynamic:
10073 case CK_ToUnion:
10074 case CK_ArrayToPointerDecay:
10075 case CK_FunctionToPointerDecay:
10076 case CK_NullToPointer:
10077 case CK_NullToMemberPointer:
10078 case CK_BaseToDerivedMemberPointer:
10079 case CK_DerivedToBaseMemberPointer:
10080 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000010081 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000010082 case CK_ConstructorConversion:
10083 case CK_IntegralToPointer:
10084 case CK_PointerToIntegral:
10085 case CK_PointerToBoolean:
10086 case CK_ToVoid:
10087 case CK_VectorSplat:
10088 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000010089 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000010090 case CK_IntegralToBoolean:
10091 case CK_IntegralToFloating:
10092 case CK_FloatingToIntegral:
10093 case CK_FloatingToBoolean:
10094 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000010095 case CK_CPointerToObjCPointerCast:
10096 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010097 case CK_AnyPointerToBlockPointerCast:
10098 case CK_ObjCObjectLValueCast:
10099 case CK_FloatingComplexToReal:
10100 case CK_FloatingComplexToBoolean:
10101 case CK_IntegralComplexToReal:
10102 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000010103 case CK_ARCProduceObject:
10104 case CK_ARCConsumeObject:
10105 case CK_ARCReclaimReturnedObject:
10106 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000010107 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000010108 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +000010109 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +000010110 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +000010111 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000010112 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000010113 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +000010114 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000010115
John McCallfcef3cf2010-12-14 17:51:41 +000010116 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010117 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000010118 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +000010119 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010120
10121 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000010122 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010123 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010124 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010125
10126 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010127 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000010128 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010129 return false;
10130
John McCallfcef3cf2010-12-14 17:51:41 +000010131 Result.makeComplexFloat();
10132 Result.FloatImag = APFloat(Real.getSemantics());
10133 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010134 }
10135
John McCallfcef3cf2010-12-14 17:51:41 +000010136 case CK_FloatingComplexCast: {
10137 if (!Visit(E->getSubExpr()))
10138 return false;
10139
10140 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10141 QualType From
10142 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10143
Richard Smith357362d2011-12-13 06:39:58 +000010144 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
10145 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010146 }
10147
10148 case CK_FloatingComplexToIntegralComplex: {
10149 if (!Visit(E->getSubExpr()))
10150 return false;
10151
10152 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10153 QualType From
10154 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10155 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000010156 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
10157 To, Result.IntReal) &&
10158 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
10159 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010160 }
10161
10162 case CK_IntegralRealToComplex: {
10163 APSInt &Real = Result.IntReal;
10164 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
10165 return false;
10166
10167 Result.makeComplexInt();
10168 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
10169 return true;
10170 }
10171
10172 case CK_IntegralComplexCast: {
10173 if (!Visit(E->getSubExpr()))
10174 return false;
10175
10176 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10177 QualType From
10178 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10179
Richard Smith911e1422012-01-30 22:27:01 +000010180 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
10181 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010182 return true;
10183 }
10184
10185 case CK_IntegralComplexToFloatingComplex: {
10186 if (!Visit(E->getSubExpr()))
10187 return false;
10188
Ted Kremenek28831752012-08-23 20:46:57 +000010189 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010190 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000010191 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010192 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000010193 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
10194 To, Result.FloatReal) &&
10195 HandleIntToFloatCast(Info, E, From, Result.IntImag,
10196 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010197 }
10198 }
10199
10200 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010201}
10202
John McCall93d91dc2010-05-07 17:22:02 +000010203bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000010204 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000010205 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10206
Chandler Carrutha216cad2014-10-11 00:57:18 +000010207 // Track whether the LHS or RHS is real at the type system level. When this is
10208 // the case we can simplify our evaluation strategy.
10209 bool LHSReal = false, RHSReal = false;
10210
10211 bool LHSOK;
10212 if (E->getLHS()->getType()->isRealFloatingType()) {
10213 LHSReal = true;
10214 APFloat &Real = Result.FloatReal;
10215 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
10216 if (LHSOK) {
10217 Result.makeComplexFloat();
10218 Result.FloatImag = APFloat(Real.getSemantics());
10219 }
10220 } else {
10221 LHSOK = Visit(E->getLHS());
10222 }
George Burgess IVa145e252016-05-25 22:38:36 +000010223 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000010224 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010225
John McCall93d91dc2010-05-07 17:22:02 +000010226 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010227 if (E->getRHS()->getType()->isRealFloatingType()) {
10228 RHSReal = true;
10229 APFloat &Real = RHS.FloatReal;
10230 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
10231 return false;
10232 RHS.makeComplexFloat();
10233 RHS.FloatImag = APFloat(Real.getSemantics());
10234 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000010235 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010236
Chandler Carrutha216cad2014-10-11 00:57:18 +000010237 assert(!(LHSReal && RHSReal) &&
10238 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010239 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010240 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000010241 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010242 if (Result.isComplexFloat()) {
10243 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
10244 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010245 if (LHSReal)
10246 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10247 else if (!RHSReal)
10248 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
10249 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010250 } else {
10251 Result.getComplexIntReal() += RHS.getComplexIntReal();
10252 Result.getComplexIntImag() += RHS.getComplexIntImag();
10253 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010254 break;
John McCalle3027922010-08-25 11:45:40 +000010255 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010256 if (Result.isComplexFloat()) {
10257 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
10258 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010259 if (LHSReal) {
10260 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10261 Result.getComplexFloatImag().changeSign();
10262 } else if (!RHSReal) {
10263 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
10264 APFloat::rmNearestTiesToEven);
10265 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010266 } else {
10267 Result.getComplexIntReal() -= RHS.getComplexIntReal();
10268 Result.getComplexIntImag() -= RHS.getComplexIntImag();
10269 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010270 break;
John McCalle3027922010-08-25 11:45:40 +000010271 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010272 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010273 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +000010274 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010275 // following naming scheme:
10276 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000010277 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010278 APFloat &A = LHS.getComplexFloatReal();
10279 APFloat &B = LHS.getComplexFloatImag();
10280 APFloat &C = RHS.getComplexFloatReal();
10281 APFloat &D = RHS.getComplexFloatImag();
10282 APFloat &ResR = Result.getComplexFloatReal();
10283 APFloat &ResI = Result.getComplexFloatImag();
10284 if (LHSReal) {
10285 assert(!RHSReal && "Cannot have two real operands for a complex op!");
10286 ResR = A * C;
10287 ResI = A * D;
10288 } else if (RHSReal) {
10289 ResR = C * A;
10290 ResI = C * B;
10291 } else {
10292 // In the fully general case, we need to handle NaNs and infinities
10293 // robustly.
10294 APFloat AC = A * C;
10295 APFloat BD = B * D;
10296 APFloat AD = A * D;
10297 APFloat BC = B * C;
10298 ResR = AC - BD;
10299 ResI = AD + BC;
10300 if (ResR.isNaN() && ResI.isNaN()) {
10301 bool Recalc = false;
10302 if (A.isInfinity() || B.isInfinity()) {
10303 A = APFloat::copySign(
10304 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10305 B = APFloat::copySign(
10306 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10307 if (C.isNaN())
10308 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10309 if (D.isNaN())
10310 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10311 Recalc = true;
10312 }
10313 if (C.isInfinity() || D.isInfinity()) {
10314 C = APFloat::copySign(
10315 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10316 D = APFloat::copySign(
10317 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10318 if (A.isNaN())
10319 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10320 if (B.isNaN())
10321 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10322 Recalc = true;
10323 }
10324 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
10325 AD.isInfinity() || BC.isInfinity())) {
10326 if (A.isNaN())
10327 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10328 if (B.isNaN())
10329 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10330 if (C.isNaN())
10331 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10332 if (D.isNaN())
10333 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10334 Recalc = true;
10335 }
10336 if (Recalc) {
10337 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
10338 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
10339 }
10340 }
10341 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010342 } else {
John McCall93d91dc2010-05-07 17:22:02 +000010343 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000010344 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010345 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
10346 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000010347 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010348 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
10349 LHS.getComplexIntImag() * RHS.getComplexIntReal());
10350 }
10351 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010352 case BO_Div:
10353 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010354 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +000010355 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010356 // following naming scheme:
10357 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010358 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010359 APFloat &A = LHS.getComplexFloatReal();
10360 APFloat &B = LHS.getComplexFloatImag();
10361 APFloat &C = RHS.getComplexFloatReal();
10362 APFloat &D = RHS.getComplexFloatImag();
10363 APFloat &ResR = Result.getComplexFloatReal();
10364 APFloat &ResI = Result.getComplexFloatImag();
10365 if (RHSReal) {
10366 ResR = A / C;
10367 ResI = B / C;
10368 } else {
10369 if (LHSReal) {
10370 // No real optimizations we can do here, stub out with zero.
10371 B = APFloat::getZero(A.getSemantics());
10372 }
10373 int DenomLogB = 0;
10374 APFloat MaxCD = maxnum(abs(C), abs(D));
10375 if (MaxCD.isFinite()) {
10376 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000010377 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
10378 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010379 }
10380 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000010381 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
10382 APFloat::rmNearestTiesToEven);
10383 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
10384 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010385 if (ResR.isNaN() && ResI.isNaN()) {
10386 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
10387 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
10388 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
10389 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
10390 D.isFinite()) {
10391 A = APFloat::copySign(
10392 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10393 B = APFloat::copySign(
10394 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10395 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
10396 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
10397 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
10398 C = APFloat::copySign(
10399 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10400 D = APFloat::copySign(
10401 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10402 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
10403 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
10404 }
10405 }
10406 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010407 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010408 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
10409 return Error(E, diag::note_expr_divide_by_zero);
10410
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010411 ComplexValue LHS = Result;
10412 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
10413 RHS.getComplexIntImag() * RHS.getComplexIntImag();
10414 Result.getComplexIntReal() =
10415 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10416 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10417 Result.getComplexIntImag() =
10418 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10419 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10420 }
10421 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010422 }
10423
John McCall93d91dc2010-05-07 17:22:02 +000010424 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010425}
10426
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010427bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10428 // Get the operand value into 'Result'.
10429 if (!Visit(E->getSubExpr()))
10430 return false;
10431
10432 switch (E->getOpcode()) {
10433 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010434 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010435 case UO_Extension:
10436 return true;
10437 case UO_Plus:
10438 // The result is always just the subexpr.
10439 return true;
10440 case UO_Minus:
10441 if (Result.isComplexFloat()) {
10442 Result.getComplexFloatReal().changeSign();
10443 Result.getComplexFloatImag().changeSign();
10444 }
10445 else {
10446 Result.getComplexIntReal() = -Result.getComplexIntReal();
10447 Result.getComplexIntImag() = -Result.getComplexIntImag();
10448 }
10449 return true;
10450 case UO_Not:
10451 if (Result.isComplexFloat())
10452 Result.getComplexFloatImag().changeSign();
10453 else
10454 Result.getComplexIntImag() = -Result.getComplexIntImag();
10455 return true;
10456 }
10457}
10458
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010459bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10460 if (E->getNumInits() == 2) {
10461 if (E->getType()->isComplexType()) {
10462 Result.makeComplexFloat();
10463 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10464 return false;
10465 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10466 return false;
10467 } else {
10468 Result.makeComplexInt();
10469 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10470 return false;
10471 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10472 return false;
10473 }
10474 return true;
10475 }
10476 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10477}
10478
Anders Carlsson537969c2008-11-16 20:27:53 +000010479//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000010480// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10481// implicit conversion.
10482//===----------------------------------------------------------------------===//
10483
10484namespace {
10485class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000010486 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010487 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000010488 APValue &Result;
10489public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010490 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10491 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000010492
10493 bool Success(const APValue &V, const Expr *E) {
10494 Result = V;
10495 return true;
10496 }
10497
10498 bool ZeroInitialization(const Expr *E) {
10499 ImplicitValueInitExpr VIE(
10500 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010501 // For atomic-qualified class (and array) types in C++, initialize the
10502 // _Atomic-wrapped subobject directly, in-place.
10503 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10504 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000010505 }
10506
10507 bool VisitCastExpr(const CastExpr *E) {
10508 switch (E->getCastKind()) {
10509 default:
10510 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10511 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010512 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10513 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000010514 }
10515 }
10516};
10517} // end anonymous namespace
10518
Richard Smith64cb9ca2017-02-22 22:09:50 +000010519static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10520 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000010521 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010522 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000010523}
10524
10525//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000010526// Void expression evaluation, primarily for a cast to void on the LHS of a
10527// comma operator
10528//===----------------------------------------------------------------------===//
10529
10530namespace {
10531class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010532 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000010533public:
10534 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10535
Richard Smith2e312c82012-03-03 22:46:17 +000010536 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000010537
Richard Smith7cd577b2017-08-17 19:35:50 +000010538 bool ZeroInitialization(const Expr *E) { return true; }
10539
Richard Smith42d3af92011-12-07 00:43:50 +000010540 bool VisitCastExpr(const CastExpr *E) {
10541 switch (E->getCastKind()) {
10542 default:
10543 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10544 case CK_ToVoid:
10545 VisitIgnoredValue(E->getSubExpr());
10546 return true;
10547 }
10548 }
Hal Finkela8443c32014-07-17 14:49:58 +000010549
10550 bool VisitCallExpr(const CallExpr *E) {
10551 switch (E->getBuiltinCallee()) {
10552 default:
10553 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10554 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000010555 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000010556 // The argument is not evaluated!
10557 return true;
10558 }
10559 }
Richard Smith42d3af92011-12-07 00:43:50 +000010560};
10561} // end anonymous namespace
10562
10563static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10564 assert(E->isRValue() && E->getType()->isVoidType());
10565 return VoidExprEvaluator(Info).Visit(E);
10566}
10567
10568//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000010569// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000010570//===----------------------------------------------------------------------===//
10571
Richard Smith2e312c82012-03-03 22:46:17 +000010572static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000010573 // In C, function designators are not lvalues, but we evaluate them as if they
10574 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000010575 QualType T = E->getType();
10576 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000010577 LValue LV;
10578 if (!EvaluateLValue(E, LV, Info))
10579 return false;
10580 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010581 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010582 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000010583 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010584 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010585 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010586 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010587 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000010588 LValue LV;
10589 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010590 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010591 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010592 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000010593 llvm::APFloat F(0.0);
10594 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010595 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000010596 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000010597 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000010598 ComplexValue C;
10599 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010600 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010601 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010602 } else if (T->isFixedPointType()) {
10603 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010604 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000010605 MemberPtr P;
10606 if (!EvaluateMemberPointer(E, P, Info))
10607 return false;
10608 P.moveInto(Result);
10609 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000010610 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010611 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010612 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010613 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000010614 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010615 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010616 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010617 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010618 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010619 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000010620 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010621 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010622 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010623 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010624 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000010625 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000010626 if (!EvaluateVoid(E, Info))
10627 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010628 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010629 QualType Unqual = T.getAtomicUnqualifiedType();
10630 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10631 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010632 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010633 if (!EvaluateAtomic(E, &LV, Value, Info))
10634 return false;
10635 } else {
10636 if (!EvaluateAtomic(E, nullptr, Result, Info))
10637 return false;
10638 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010639 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010640 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010641 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010642 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010643 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010644 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010645 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010646
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010647 return true;
10648}
10649
Richard Smithb228a862012-02-15 02:18:13 +000010650/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10651/// cases, the in-place evaluation is essential, since later initializers for
10652/// an object can indirectly refer to subobjects which were initialized earlier.
10653static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010654 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010655 assert(!E->isValueDependent());
10656
Richard Smith7525ff62013-05-09 07:14:00 +000010657 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010658 return false;
10659
10660 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010661 // Evaluate arrays and record types in-place, so that later initializers can
10662 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010663 QualType T = E->getType();
10664 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010665 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010666 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010667 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010668 else if (T->isAtomicType()) {
10669 QualType Unqual = T.getAtomicUnqualifiedType();
10670 if (Unqual->isArrayType() || Unqual->isRecordType())
10671 return EvaluateAtomic(E, &This, Result, Info);
10672 }
Richard Smithed5165f2011-11-04 05:33:44 +000010673 }
10674
10675 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010676 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010677}
10678
Richard Smithf57d8cb2011-12-09 22:58:01 +000010679/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10680/// lvalue-to-rvalue cast if it is an lvalue.
10681static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010682 if (E->getType().isNull())
10683 return false;
10684
Nick Lewyckyc190f962017-05-02 01:06:16 +000010685 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010686 return false;
10687
Richard Smith2e312c82012-03-03 22:46:17 +000010688 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010689 return false;
10690
10691 if (E->isGLValue()) {
10692 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010693 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010694 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010695 return false;
10696 }
10697
Richard Smith2e312c82012-03-03 22:46:17 +000010698 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010699 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010700}
Richard Smith11562c52011-10-28 17:51:58 +000010701
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010702static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010703 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010704 // Fast-path evaluations of integer literals, since we sometimes see files
10705 // containing vast quantities of these.
10706 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10707 Result.Val = APValue(APSInt(L->getValue(),
10708 L->getType()->isUnsignedIntegerType()));
10709 IsConst = true;
10710 return true;
10711 }
James Dennett0492ef02014-03-14 17:44:10 +000010712
10713 // This case should be rare, but we need to check it before we check on
10714 // the type below.
10715 if (Exp->getType().isNull()) {
10716 IsConst = false;
10717 return true;
10718 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010719
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010720 // FIXME: Evaluating values of large array and record types can cause
10721 // performance problems. Only do so in C++11 for now.
10722 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10723 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010724 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010725 IsConst = false;
10726 return true;
10727 }
10728 return false;
10729}
10730
10731
Richard Smith7b553f12011-10-29 00:50:52 +000010732/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010733/// any crazy technique (that has nothing to do with language standards) that
10734/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010735/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10736/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010737bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010738 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010739 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010740 return IsConst;
Fangrui Song6907ce22018-07-30 19:24:48 +000010741
Richard Smith6d4c6582013-11-05 22:18:15 +000010742 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010743 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010744}
10745
Jay Foad39c79802011-01-12 09:06:06 +000010746bool Expr::EvaluateAsBooleanCondition(bool &Result,
10747 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010748 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010749 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010750 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010751}
10752
Richard Smith3f1d6de2018-05-21 20:36:58 +000010753static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10754 Expr::SideEffectsKind SEK) {
10755 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10756 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10757}
10758
Richard Smith5fab0c92011-12-28 19:48:30 +000010759bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10760 SideEffectsKind AllowSideEffects) const {
10761 if (!getType()->isIntegralOrEnumerationType())
10762 return false;
10763
Richard Smith11562c52011-10-28 17:51:58 +000010764 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010765 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000010766 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010767 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010768
Richard Smith11562c52011-10-28 17:51:58 +000010769 Result = ExprResult.Val.getInt();
10770 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010771}
10772
Richard Trieube234c32016-04-21 21:04:55 +000010773bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10774 SideEffectsKind AllowSideEffects) const {
10775 if (!getType()->isRealFloatingType())
10776 return false;
10777
10778 EvalResult ExprResult;
10779 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000010780 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000010781 return false;
10782
10783 Result = ExprResult.Val.getFloat();
10784 return true;
10785}
10786
Jay Foad39c79802011-01-12 09:06:06 +000010787bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010788 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010789
John McCall45d55e42010-05-07 21:00:08 +000010790 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010791 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10792 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000010793 Ctx.getLValueReferenceType(getType()), LV,
10794 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000010795 return false;
10796
Richard Smith2e312c82012-03-03 22:46:17 +000010797 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010798 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010799}
10800
Reid Kleckner1a840d22018-05-10 18:57:35 +000010801bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
10802 const ASTContext &Ctx) const {
10803 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
10804 EvalInfo Info(Ctx, Result, EM);
10805 if (!::Evaluate(Result.Val, Info, this))
10806 return false;
10807
10808 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
10809 Usage);
10810}
10811
Richard Smithd0b4dd62011-12-19 06:19:21 +000010812bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10813 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010814 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010815 // FIXME: Evaluating initializers for large array and record types can cause
10816 // performance problems. Only do so in C++11 for now.
10817 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010818 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010819 return false;
10820
Richard Smithd0b4dd62011-12-19 06:19:21 +000010821 Expr::EvalStatus EStatus;
10822 EStatus.Diag = &Notes;
10823
Richard Smith0c6124b2015-12-03 01:36:22 +000010824 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10825 ? EvalInfo::EM_ConstantExpression
10826 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010827 InitInfo.setEvaluatingDecl(VD, Value);
10828
10829 LValue LVal;
10830 LVal.set(VD);
10831
Richard Smithfddd3842011-12-30 21:15:51 +000010832 // C++11 [basic.start.init]p2:
10833 // Variables with static storage duration or thread storage duration shall be
10834 // zero-initialized before any other initialization takes place.
10835 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010836 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010837 !VD->getType()->isReferenceType()) {
10838 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010839 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010840 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010841 return false;
10842 }
10843
Richard Smith7525ff62013-05-09 07:14:00 +000010844 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10845 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010846 EStatus.HasSideEffects)
10847 return false;
10848
10849 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10850 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010851}
10852
Richard Smith7b553f12011-10-29 00:50:52 +000010853/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10854/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010855bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010856 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010857 return EvaluateAsRValue(Result, Ctx) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000010858 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010859}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010860
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010861APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010862 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010863 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010864 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010865 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010866 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010867 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010868 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010869
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010870 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010871}
John McCall864e3962010-05-07 05:32:02 +000010872
Richard Smithe9ff7702013-11-05 22:23:30 +000010873void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010874 bool IsConst;
10875 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010876 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010877 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010878 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10879 }
10880}
10881
Richard Smithe6c01442013-06-05 00:46:14 +000010882bool Expr::EvalResult::isGlobalLValue() const {
10883 assert(Val.isLValue());
10884 return IsGlobalLValue(Val.getLValueBase());
10885}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010886
10887
John McCall864e3962010-05-07 05:32:02 +000010888/// isIntegerConstantExpr - this recursive routine will test if an expression is
10889/// an integer constant expression.
10890
10891/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10892/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010893
10894// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010895// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10896// and a (possibly null) SourceLocation indicating the location of the problem.
10897//
John McCall864e3962010-05-07 05:32:02 +000010898// Note that to reduce code duplication, this helper does no evaluation
10899// itself; the caller checks whether the expression is evaluatable, and
10900// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010901// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010902
Dan Gohman28ade552010-07-26 21:25:24 +000010903namespace {
10904
Richard Smith9e575da2012-12-28 13:25:52 +000010905enum ICEKind {
10906 /// This expression is an ICE.
10907 IK_ICE,
10908 /// This expression is not an ICE, but if it isn't evaluated, it's
10909 /// a legal subexpression for an ICE. This return value is used to handle
10910 /// the comma operator in C99 mode, and non-constant subexpressions.
10911 IK_ICEIfUnevaluated,
10912 /// This expression is not an ICE, and is not a legal subexpression for one.
10913 IK_NotICE
10914};
10915
John McCall864e3962010-05-07 05:32:02 +000010916struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010917 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010918 SourceLocation Loc;
10919
Richard Smith9e575da2012-12-28 13:25:52 +000010920 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010921};
10922
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010923}
Dan Gohman28ade552010-07-26 21:25:24 +000010924
Richard Smith9e575da2012-12-28 13:25:52 +000010925static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10926
10927static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010928
Craig Toppera31a8822013-08-22 07:09:37 +000010929static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010930 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010931 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010932 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010933 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000010934
John McCall864e3962010-05-07 05:32:02 +000010935 return NoDiag();
10936}
10937
Craig Toppera31a8822013-08-22 07:09:37 +000010938static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010939 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010940 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010941 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000010942
10943 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010944#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010945#define STMT(Node, Base) case Expr::Node##Class:
10946#define EXPR(Node, Base)
10947#include "clang/AST/StmtNodes.inc"
10948 case Expr::PredefinedExprClass:
10949 case Expr::FloatingLiteralClass:
10950 case Expr::ImaginaryLiteralClass:
10951 case Expr::StringLiteralClass:
10952 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010953 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010954 case Expr::MemberExprClass:
10955 case Expr::CompoundAssignOperatorClass:
10956 case Expr::CompoundLiteralExprClass:
10957 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010958 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010959 case Expr::ArrayInitLoopExprClass:
10960 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010961 case Expr::NoInitExprClass:
10962 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010963 case Expr::ImplicitValueInitExprClass:
10964 case Expr::ParenListExprClass:
10965 case Expr::VAArgExprClass:
10966 case Expr::AddrLabelExprClass:
10967 case Expr::StmtExprClass:
10968 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010969 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010970 case Expr::CXXDynamicCastExprClass:
10971 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010972 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010973 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010974 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010975 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010976 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010977 case Expr::CXXThisExprClass:
10978 case Expr::CXXThrowExprClass:
10979 case Expr::CXXNewExprClass:
10980 case Expr::CXXDeleteExprClass:
10981 case Expr::CXXPseudoDestructorExprClass:
10982 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010983 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010984 case Expr::DependentScopeDeclRefExprClass:
10985 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010986 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010987 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010988 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010989 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010990 case Expr::CXXTemporaryObjectExprClass:
10991 case Expr::CXXUnresolvedConstructExprClass:
10992 case Expr::CXXDependentScopeMemberExprClass:
10993 case Expr::UnresolvedMemberExprClass:
10994 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010995 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010996 case Expr::ObjCArrayLiteralClass:
10997 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010998 case Expr::ObjCEncodeExprClass:
10999 case Expr::ObjCMessageExprClass:
11000 case Expr::ObjCSelectorExprClass:
11001 case Expr::ObjCProtocolExprClass:
11002 case Expr::ObjCIvarRefExprClass:
11003 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011004 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000011005 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000011006 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000011007 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000011008 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000011009 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000011010 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000011011 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000011012 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000011013 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000011014 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000011015 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000011016 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000011017 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000011018 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000011019 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000011020 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000011021 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011022 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000011023 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011024 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011025 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000011026
Richard Smithf137f932014-01-25 20:50:08 +000011027 case Expr::InitListExprClass: {
11028 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
11029 // form "T x = { a };" is equivalent to "T x = a;".
11030 // Unless we're initializing a reference, T is a scalar as it is known to be
11031 // of integral or enumeration type.
11032 if (E->isRValue())
11033 if (cast<InitListExpr>(E)->getNumInits() == 1)
11034 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011035 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000011036 }
11037
Douglas Gregor820ba7b2011-01-04 17:33:58 +000011038 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000011039 case Expr::GNUNullExprClass:
11040 // GCC considers the GNU __null value to be an integral constant expression.
11041 return NoDiag();
11042
John McCall7c454bb2011-07-15 05:09:51 +000011043 case Expr::SubstNonTypeTemplateParmExprClass:
11044 return
11045 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
11046
John McCall864e3962010-05-07 05:32:02 +000011047 case Expr::ParenExprClass:
11048 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000011049 case Expr::GenericSelectionExprClass:
11050 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011051 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000011052 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011053 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011054 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000011055 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000011056 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000011057 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000011058 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000011059 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000011060 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011061 return NoDiag();
11062 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000011063 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000011064 // C99 6.6/3 allows function calls within unevaluated subexpressions of
11065 // constant expressions, but they can never be ICEs because an ICE cannot
11066 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000011067 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000011068 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000011069 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011070 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011071 }
Richard Smith6365c912012-02-24 22:12:32 +000011072 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011073 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
11074 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000011075 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011076 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000011077 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000011078 // Parameter variables are never constants. Without this check,
11079 // getAnyInitializer() can find a default argument, which leads
11080 // to chaos.
11081 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000011082 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011083
11084 // C++ 7.1.5.1p2
11085 // A variable of non-volatile const-qualified integral or enumeration
11086 // type initialized by an ICE can be used in ICEs.
11087 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000011088 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000011089 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000011090
Richard Smithd0b4dd62011-12-19 06:19:21 +000011091 const VarDecl *VD;
11092 // Look for a declaration of this variable that has an initializer, and
11093 // check whether it is an ICE.
11094 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
11095 return NoDiag();
11096 else
Richard Smith9e575da2012-12-28 13:25:52 +000011097 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011098 }
11099 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011100 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000011101 }
John McCall864e3962010-05-07 05:32:02 +000011102 case Expr::UnaryOperatorClass: {
11103 const UnaryOperator *Exp = cast<UnaryOperator>(E);
11104 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011105 case UO_PostInc:
11106 case UO_PostDec:
11107 case UO_PreInc:
11108 case UO_PreDec:
11109 case UO_AddrOf:
11110 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000011111 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000011112 // C99 6.6/3 allows increment and decrement within unevaluated
11113 // subexpressions of constant expressions, but they can never be ICEs
11114 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011115 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000011116 case UO_Extension:
11117 case UO_LNot:
11118 case UO_Plus:
11119 case UO_Minus:
11120 case UO_Not:
11121 case UO_Real:
11122 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000011123 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011124 }
Richard Smith9e575da2012-12-28 13:25:52 +000011125
John McCall864e3962010-05-07 05:32:02 +000011126 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000011127 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000011128 }
11129 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000011130 // Note that per C99, offsetof must be an ICE. And AFAIK, using
11131 // EvaluateAsRValue matches the proposed gcc behavior for cases like
11132 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
11133 // compliance: we should warn earlier for offsetof expressions with
11134 // array subscripts that aren't ICEs, and if the array subscripts
11135 // are ICEs, the value of the offsetof must be an integer constant.
11136 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011137 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000011138 case Expr::UnaryExprOrTypeTraitExprClass: {
11139 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
11140 if ((Exp->getKind() == UETT_SizeOf) &&
11141 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011142 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011143 return NoDiag();
11144 }
11145 case Expr::BinaryOperatorClass: {
11146 const BinaryOperator *Exp = cast<BinaryOperator>(E);
11147 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011148 case BO_PtrMemD:
11149 case BO_PtrMemI:
11150 case BO_Assign:
11151 case BO_MulAssign:
11152 case BO_DivAssign:
11153 case BO_RemAssign:
11154 case BO_AddAssign:
11155 case BO_SubAssign:
11156 case BO_ShlAssign:
11157 case BO_ShrAssign:
11158 case BO_AndAssign:
11159 case BO_XorAssign:
11160 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000011161 // C99 6.6/3 allows assignments within unevaluated subexpressions of
11162 // constant expressions, but they can never be ICEs because an ICE cannot
11163 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011164 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011165
John McCalle3027922010-08-25 11:45:40 +000011166 case BO_Mul:
11167 case BO_Div:
11168 case BO_Rem:
11169 case BO_Add:
11170 case BO_Sub:
11171 case BO_Shl:
11172 case BO_Shr:
11173 case BO_LT:
11174 case BO_GT:
11175 case BO_LE:
11176 case BO_GE:
11177 case BO_EQ:
11178 case BO_NE:
11179 case BO_And:
11180 case BO_Xor:
11181 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011182 case BO_Comma:
11183 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000011184 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11185 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000011186 if (Exp->getOpcode() == BO_Div ||
11187 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000011188 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000011189 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000011190 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000011191 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011192 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011193 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011194 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000011195 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011196 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011197 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011198 }
11199 }
11200 }
John McCalle3027922010-08-25 11:45:40 +000011201 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011202 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000011203 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
11204 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000011205 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011206 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011207 } else {
11208 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011209 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011210 }
11211 }
Richard Smith9e575da2012-12-28 13:25:52 +000011212 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011213 }
John McCalle3027922010-08-25 11:45:40 +000011214 case BO_LAnd:
11215 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000011216 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11217 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011218 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000011219 // Rare case where the RHS has a comma "side-effect"; we need
11220 // to actually check the condition to see whether the side
11221 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000011222 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000011223 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000011224 return RHSResult;
11225 return NoDiag();
11226 }
11227
Richard Smith9e575da2012-12-28 13:25:52 +000011228 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011229 }
11230 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000011231 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000011232 }
11233 case Expr::ImplicitCastExprClass:
11234 case Expr::CStyleCastExprClass:
11235 case Expr::CXXFunctionalCastExprClass:
11236 case Expr::CXXStaticCastExprClass:
11237 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000011238 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000011239 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011240 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000011241 if (isa<ExplicitCastExpr>(E)) {
11242 if (const FloatingLiteral *FL
11243 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
11244 unsigned DestWidth = Ctx.getIntWidth(E->getType());
11245 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
11246 APSInt IgnoredVal(DestWidth, !DestSigned);
11247 bool Ignored;
11248 // If the value does not fit in the destination type, the behavior is
11249 // undefined, so we are not required to treat it as a constant
11250 // expression.
11251 if (FL->getValue().convertToInteger(IgnoredVal,
11252 llvm::APFloat::rmTowardZero,
11253 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011254 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000011255 return NoDiag();
11256 }
11257 }
Eli Friedman76d4e432011-09-29 21:49:34 +000011258 switch (cast<CastExpr>(E)->getCastKind()) {
11259 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011260 case CK_AtomicToNonAtomic:
11261 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000011262 case CK_NoOp:
11263 case CK_IntegralToBoolean:
11264 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000011265 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000011266 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011267 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000011268 }
John McCall864e3962010-05-07 05:32:02 +000011269 }
John McCallc07a0c72011-02-17 10:25:35 +000011270 case Expr::BinaryConditionalOperatorClass: {
11271 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
11272 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011273 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000011274 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011275 if (FalseResult.Kind == IK_NotICE) return FalseResult;
11276 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
11277 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000011278 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000011279 return FalseResult;
11280 }
John McCall864e3962010-05-07 05:32:02 +000011281 case Expr::ConditionalOperatorClass: {
11282 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
11283 // If the condition (ignoring parens) is a __builtin_constant_p call,
11284 // then only the true side is actually considered in an integer constant
11285 // expression, and it is fully evaluated. This is an important GNU
11286 // extension. See GCC PR38377 for discussion.
11287 if (const CallExpr *CallCE
11288 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000011289 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000011290 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011291 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011292 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011293 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011294
Richard Smithf57d8cb2011-12-09 22:58:01 +000011295 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
11296 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011297
Richard Smith9e575da2012-12-28 13:25:52 +000011298 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011299 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011300 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011301 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011302 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000011303 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011304 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000011305 return NoDiag();
11306 // Rare case where the diagnostics depend on which side is evaluated
11307 // Note that if we get here, CondResult is 0, and at least one of
11308 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000011309 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000011310 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000011311 return TrueResult;
11312 }
11313 case Expr::CXXDefaultArgExprClass:
11314 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000011315 case Expr::CXXDefaultInitExprClass:
11316 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011317 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000011318 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011319 }
11320 }
11321
David Blaikiee4d798f2012-01-20 21:50:17 +000011322 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000011323}
11324
Richard Smithf57d8cb2011-12-09 22:58:01 +000011325/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000011326static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011327 const Expr *E,
11328 llvm::APSInt *Value,
11329 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000011330 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011331 if (Loc) *Loc = E->getExprLoc();
11332 return false;
11333 }
11334
Richard Smith66e05fe2012-01-18 05:21:49 +000011335 APValue Result;
11336 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000011337 return false;
11338
Richard Smith98710fc2014-11-13 23:03:19 +000011339 if (!Result.isInt()) {
11340 if (Loc) *Loc = E->getExprLoc();
11341 return false;
11342 }
11343
Richard Smith66e05fe2012-01-18 05:21:49 +000011344 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000011345 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011346}
11347
Craig Toppera31a8822013-08-22 07:09:37 +000011348bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
11349 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011350 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000011351 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011352
Richard Smith9e575da2012-12-28 13:25:52 +000011353 ICEDiag D = CheckICE(this, Ctx);
11354 if (D.Kind != IK_ICE) {
11355 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000011356 return false;
11357 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011358 return true;
11359}
11360
Craig Toppera31a8822013-08-22 07:09:37 +000011361bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011362 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011363 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011364 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
11365
11366 if (!isIntegerConstantExpr(Ctx, Loc))
11367 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000011368 // The only possible side-effects here are due to UB discovered in the
11369 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
11370 // required to treat the expression as an ICE, so we produce the folded
11371 // value.
11372 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000011373 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000011374 return true;
11375}
Richard Smith66e05fe2012-01-18 05:21:49 +000011376
Craig Toppera31a8822013-08-22 07:09:37 +000011377bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000011378 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000011379}
11380
Craig Toppera31a8822013-08-22 07:09:37 +000011381bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000011382 SourceLocation *Loc) const {
11383 // We support this checking in C++98 mode in order to diagnose compatibility
11384 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011385 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000011386
Richard Smith98a0a492012-02-14 21:38:30 +000011387 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000011388 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011389 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000011390 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000011391 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000011392
11393 APValue Scratch;
11394 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
11395
11396 if (!Diags.empty()) {
11397 IsConstExpr = false;
11398 if (Loc) *Loc = Diags[0].first;
11399 } else if (!IsConstExpr) {
11400 // FIXME: This shouldn't happen.
11401 if (Loc) *Loc = getExprLoc();
11402 }
11403
11404 return IsConstExpr;
11405}
Richard Smith253c2a32012-01-27 01:14:48 +000011406
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011407bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
11408 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000011409 ArrayRef<const Expr*> Args,
11410 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011411 Expr::EvalStatus Status;
11412 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
11413
George Burgess IV177399e2017-01-09 04:12:14 +000011414 LValue ThisVal;
11415 const LValue *ThisPtr = nullptr;
11416 if (This) {
11417#ifndef NDEBUG
11418 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11419 assert(MD && "Don't provide `this` for non-methods.");
11420 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11421#endif
11422 if (EvaluateObjectArgument(Info, This, ThisVal))
11423 ThisPtr = &ThisVal;
11424 if (Info.EvalStatus.HasSideEffects)
11425 return false;
11426 }
11427
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011428 ArgVector ArgValues(Args.size());
11429 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11430 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000011431 if ((*I)->isValueDependent() ||
11432 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011433 // If evaluation fails, throw away the argument entirely.
11434 ArgValues[I - Args.begin()] = APValue();
11435 if (Info.EvalStatus.HasSideEffects)
11436 return false;
11437 }
11438
11439 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000011440 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011441 ArgValues.data());
11442 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11443}
11444
Richard Smith253c2a32012-01-27 01:14:48 +000011445bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011446 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000011447 PartialDiagnosticAt> &Diags) {
11448 // FIXME: It would be useful to check constexpr function templates, but at the
11449 // moment the constant expression evaluator cannot cope with the non-rigorous
11450 // ASTs which we build for dependent expressions.
11451 if (FD->isDependentContext())
11452 return true;
11453
11454 Expr::EvalStatus Status;
11455 Status.Diag = &Diags;
11456
Richard Smith6d4c6582013-11-05 22:18:15 +000011457 EvalInfo Info(FD->getASTContext(), Status,
11458 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000011459
11460 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000011461 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000011462
Richard Smith7525ff62013-05-09 07:14:00 +000011463 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000011464 // is a temporary being used as the 'this' pointer.
11465 LValue This;
11466 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011467 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000011468
Richard Smith253c2a32012-01-27 01:14:48 +000011469 ArrayRef<const Expr*> Args;
11470
Richard Smith2e312c82012-03-03 22:46:17 +000011471 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000011472 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11473 // Evaluate the call as a constant initializer, to allow the construction
11474 // of objects of non-literal types.
11475 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000011476 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11477 } else {
11478 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000011479 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000011480 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000011481 }
Richard Smith253c2a32012-01-27 01:14:48 +000011482
11483 return Diags.empty();
11484}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011485
11486bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11487 const FunctionDecl *FD,
11488 SmallVectorImpl<
11489 PartialDiagnosticAt> &Diags) {
11490 Expr::EvalStatus Status;
11491 Status.Diag = &Diags;
11492
11493 EvalInfo Info(FD->getASTContext(), Status,
11494 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
11495
11496 // Fabricate a call stack frame to give the arguments a plausible cover story.
11497 ArrayRef<const Expr*> Args;
11498 ArgVector ArgValues(0);
11499 bool Success = EvaluateArgs(Args, ArgValues, Info);
11500 (void)Success;
11501 assert(Success &&
11502 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000011503 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011504
11505 APValue ResultScratch;
11506 Evaluate(ResultScratch, Info, E);
11507 return Diags.empty();
11508}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011509
11510bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11511 unsigned Type) const {
11512 if (!getType()->isPointerType())
11513 return false;
11514
11515 Expr::EvalStatus Status;
11516 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000011517 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011518}