blob: 6fced96484192e2fbb75603cfa1afad766b1814c [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"
Tim Northover314fbfa2018-11-02 13:14:11 +000042#include "clang/AST/OSLog.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000043#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000044#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000045#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000046#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000047#include "clang/Basic/TargetInfo.h"
Fangrui Song407659a2018-11-30 23:41:18 +000048#include "llvm/Support/SaveAndRestore.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000049#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000050#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000051#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000052
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000053#define DEBUG_TYPE "exprconstant"
54
Anders Carlsson7a241ba2008-07-03 04:20:39 +000055using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000056using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000057using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000058
Richard Smithb228a862012-02-15 02:18:13 +000059static bool IsGlobalLValue(APValue::LValueBase B);
60
John McCall93d91dc2010-05-07 17:22:02 +000061namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000062 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000063 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000064 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000065
Richard Smithb228a862012-02-15 02:18:13 +000066 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000067 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000068 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000069 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000070 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000071 //
72 // extern int arr[]; void f() { extern int arr[3]; };
73 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000074 //
75 // For now, we take the array bound from the most recent declaration.
76 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
77 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
78 QualType T = Redecl->getType();
79 if (!T->isIncompleteArrayType())
80 return T;
81 }
82 return D->getType();
83 }
Richard Smith84401042013-06-03 05:03:02 +000084
85 const Expr *Base = B.get<const Expr*>();
86
87 // For a materialized temporary, the type of the temporary we materialized
88 // may not be the type of the expression.
89 if (const MaterializeTemporaryExpr *MTE =
90 dyn_cast<MaterializeTemporaryExpr>(Base)) {
91 SmallVector<const Expr *, 2> CommaLHSs;
92 SmallVector<SubobjectAdjustment, 2> Adjustments;
93 const Expr *Temp = MTE->GetTemporaryExpr();
94 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
95 Adjustments);
96 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000097 // for it directly. Otherwise use the type after adjustment.
98 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000099 return Inner->getType();
100 }
101
102 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000103 }
104
Richard Smithd62306a2011-11-10 06:34:14 +0000105 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000106 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +0000107 static
Richard Smith84f6dcf2012-02-02 01:16:57 +0000108 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +0000109 APValue::BaseOrMemberType Value;
110 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +0000111 return Value;
112 }
113
114 /// Get an LValue path entry, which is known to not be an array index, as a
115 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000116 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000117 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000118 }
119 /// Get an LValue path entry, which is known to not be an array index, as a
120 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000121 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000122 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000123 }
124 /// Determine whether this LValue path entry for a base class names a virtual
125 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000126 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000127 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000128 }
129
George Burgess IVe3763372016-12-22 02:50:20 +0000130 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
131 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
132 const FunctionDecl *Callee = CE->getDirectCallee();
133 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
134 }
135
136 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
137 /// This will look through a single cast.
138 ///
139 /// Returns null if we couldn't unwrap a function with alloc_size.
140 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
141 if (!E->getType()->isPointerType())
142 return nullptr;
143
144 E = E->IgnoreParens();
145 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000146 // probably be a cast of some kind. In exotic cases, we might also see a
147 // top-level ExprWithCleanups. Ignore them either way.
Bill Wendling7c44da22018-10-31 03:48:47 +0000148 if (const auto *FE = dyn_cast<FullExpr>(E))
149 E = FE->getSubExpr()->IgnoreParens();
George Burgess IV47638762018-03-07 04:52:34 +0000150
George Burgess IVe3763372016-12-22 02:50:20 +0000151 if (const auto *Cast = dyn_cast<CastExpr>(E))
152 E = Cast->getSubExpr()->IgnoreParens();
153
154 if (const auto *CE = dyn_cast<CallExpr>(E))
155 return getAllocSizeAttr(CE) ? CE : nullptr;
156 return nullptr;
157 }
158
159 /// Determines whether or not the given Base contains a call to a function
160 /// with the alloc_size attribute.
161 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
162 const auto *E = Base.dyn_cast<const Expr *>();
163 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
164 }
165
Richard Smith6f4f0f12017-10-20 22:56:25 +0000166 /// The bound to claim that an array of unknown bound has.
167 /// The value in MostDerivedArraySize is undefined in this case. So, set it
168 /// to an arbitrary value that's likely to loudly break things if it's used.
169 static const uint64_t AssumedSizeForUnsizedArray =
170 std::numeric_limits<uint64_t>::max() / 2;
171
George Burgess IVe3763372016-12-22 02:50:20 +0000172 /// Determines if an LValue with the given LValueBase will have an unsized
173 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000174 /// Find the path length and type of the most-derived subobject in the given
175 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000176 static unsigned
177 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
178 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000179 uint64_t &ArraySize, QualType &Type, bool &IsArray,
180 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000181 // This only accepts LValueBases from APValues, and APValues don't support
182 // arrays that lack size info.
183 assert(!isBaseAnAllocSizeCall(Base) &&
184 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000185 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000186 Type = getType(Base);
187
Richard Smith80815602011-11-07 05:07:52 +0000188 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000189 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000190 const ArrayType *AT = Ctx.getAsArrayType(Type);
191 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000192 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000193 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000194
195 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
196 ArraySize = CAT->getSize().getZExtValue();
197 } else {
198 assert(I == 0 && "unexpected unsized array designator");
199 FirstEntryIsUnsizedArray = true;
200 ArraySize = AssumedSizeForUnsizedArray;
201 }
Richard Smith66c96992012-02-18 22:04:06 +0000202 } else if (Type->isAnyComplexType()) {
203 const ComplexType *CT = Type->castAs<ComplexType>();
204 Type = CT->getElementType();
205 ArraySize = 2;
206 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000207 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000208 } else if (const FieldDecl *FD = getAsField(Path[I])) {
209 Type = FD->getType();
210 ArraySize = 0;
211 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000212 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000213 } else {
Richard Smith80815602011-11-07 05:07:52 +0000214 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000215 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000216 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 }
Richard Smith80815602011-11-07 05:07:52 +0000218 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000219 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000220 }
221
Richard Smitha8105bc2012-01-06 16:39:00 +0000222 // The order of this enum is important for diagnostics.
223 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000224 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000225 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000226 };
227
Richard Smith96e0c102011-11-04 02:25:55 +0000228 /// A path from a glvalue to a subobject of that glvalue.
229 struct SubobjectDesignator {
230 /// True if the subobject was named in a manner not supported by C++11. Such
231 /// lvalues can still be folded, but they are not core constant expressions
232 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000233 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000234
Richard Smitha8105bc2012-01-06 16:39:00 +0000235 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000236 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000237
Daniel Jasperffdee092017-05-02 19:21:42 +0000238 /// Indicator of whether the first entry is an unsized array.
239 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000240
George Burgess IVa51c4072015-10-16 01:49:01 +0000241 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000242 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000243
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 /// The length of the path to the most-derived object of which this is a
245 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000246 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000247
George Burgess IVa51c4072015-10-16 01:49:01 +0000248 /// The size of the array of which the most-derived object is an element.
249 /// This will always be 0 if the most-derived object is not an array
250 /// element. 0 is not an indicator of whether or not the most-derived object
251 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000252 ///
253 /// If the current array is an unsized array, the value of this is
254 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000255 uint64_t MostDerivedArraySize;
256
257 /// The type of the most derived object referred to by this address.
258 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000259
Richard Smith80815602011-11-07 05:07:52 +0000260 typedef APValue::LValuePathEntry PathEntry;
261
Richard Smith96e0c102011-11-04 02:25:55 +0000262 /// The entries on the path from the glvalue to the designated subobject.
263 SmallVector<PathEntry, 8> Entries;
264
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000266
Richard Smitha8105bc2012-01-06 16:39:00 +0000267 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000268 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000269 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000270 MostDerivedPathLength(0), MostDerivedArraySize(0),
271 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000272
273 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000274 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000275 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000276 MostDerivedPathLength(0), MostDerivedArraySize(0) {
277 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000278 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000279 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000280 ArrayRef<PathEntry> VEntries = V.getLValuePath();
281 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000282 if (V.getLValueBase()) {
283 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000284 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000285 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000286 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000287 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000288 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000289 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000290 }
Richard Smith80815602011-11-07 05:07:52 +0000291 }
292 }
293
Richard Smith96e0c102011-11-04 02:25:55 +0000294 void setInvalid() {
295 Invalid = true;
296 Entries.clear();
297 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000298
George Burgess IVe3763372016-12-22 02:50:20 +0000299 /// Determine whether the most derived subobject is an array without a
300 /// known bound.
301 bool isMostDerivedAnUnsizedArray() const {
302 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000303 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000304 }
305
306 /// Determine what the most derived array's size is. Results in an assertion
307 /// failure if the most derived array lacks a size.
308 uint64_t getMostDerivedArraySize() const {
309 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
310 return MostDerivedArraySize;
311 }
312
Richard Smitha8105bc2012-01-06 16:39:00 +0000313 /// Determine whether this is a one-past-the-end pointer.
314 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000315 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000316 if (IsOnePastTheEnd)
317 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000318 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000319 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
320 return true;
321 return false;
322 }
323
Richard Smith06f71b52018-08-04 00:57:17 +0000324 /// Get the range of valid index adjustments in the form
325 /// {maximum value that can be subtracted from this pointer,
326 /// maximum value that can be added to this pointer}
327 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
328 if (Invalid || isMostDerivedAnUnsizedArray())
329 return {0, 0};
330
331 // [expr.add]p4: For the purposes of these operators, a pointer to a
332 // nonarray object behaves the same as a pointer to the first element of
333 // an array of length one with the type of the object as its element type.
334 bool IsArray = MostDerivedPathLength == Entries.size() &&
335 MostDerivedIsArrayElement;
336 uint64_t ArrayIndex =
337 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
338 uint64_t ArraySize =
339 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
340 return {ArrayIndex, ArraySize - ArrayIndex};
341 }
342
Richard Smitha8105bc2012-01-06 16:39:00 +0000343 /// Check that this refers to a valid subobject.
344 bool isValidSubobject() const {
345 if (Invalid)
346 return false;
347 return !isOnePastTheEnd();
348 }
349 /// Check that this refers to a valid subobject, and if not, produce a
350 /// relevant diagnostic and set the designator as invalid.
351 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
352
Richard Smith06f71b52018-08-04 00:57:17 +0000353 /// Get the type of the designated object.
354 QualType getType(ASTContext &Ctx) const {
355 assert(!Invalid && "invalid designator has no subobject type");
356 return MostDerivedPathLength == Entries.size()
357 ? MostDerivedType
358 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
359 }
360
Richard Smitha8105bc2012-01-06 16:39:00 +0000361 /// Update this designator to refer to the first element within this array.
362 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000363 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000364 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000365 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000366
367 // This is a most-derived object.
368 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000369 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000370 MostDerivedArraySize = CAT->getSize().getZExtValue();
371 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000372 }
George Burgess IVe3763372016-12-22 02:50:20 +0000373 /// Update this designator to refer to the first element within the array of
374 /// elements of type T. This is an array of unknown size.
375 void addUnsizedArrayUnchecked(QualType ElemTy) {
376 PathEntry Entry;
377 Entry.ArrayIndex = 0;
378 Entries.push_back(Entry);
379
380 MostDerivedType = ElemTy;
381 MostDerivedIsArrayElement = true;
382 // The value in MostDerivedArraySize is undefined in this case. So, set it
383 // to an arbitrary value that's likely to loudly break things if it's
384 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000385 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000386 MostDerivedPathLength = Entries.size();
387 }
Richard Smith96e0c102011-11-04 02:25:55 +0000388 /// Update this designator to refer to the given base or member of this
389 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000390 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000391 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000392 APValue::BaseOrMemberType Value(D, Virtual);
393 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000394 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000395
396 // If this isn't a base class, it's a new most-derived object.
397 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
398 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000399 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000400 MostDerivedArraySize = 0;
401 MostDerivedPathLength = Entries.size();
402 }
Richard Smith96e0c102011-11-04 02:25:55 +0000403 }
Richard Smith66c96992012-02-18 22:04:06 +0000404 /// Update this designator to refer to the given complex component.
405 void addComplexUnchecked(QualType EltTy, bool Imag) {
406 PathEntry Entry;
407 Entry.ArrayIndex = Imag;
408 Entries.push_back(Entry);
409
410 // This is technically a most-derived object, though in practice this
411 // is unlikely to matter.
412 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000413 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000414 MostDerivedArraySize = 2;
415 MostDerivedPathLength = Entries.size();
416 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000417 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000418 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
419 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000420 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000421 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
422 if (Invalid || !N) return;
423 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
424 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000425 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000426 // Can't verify -- trust that the user is doing the right thing (or if
427 // not, trust that the caller will catch the bad behavior).
428 // FIXME: Should we reject if this overflows, at least?
429 Entries.back().ArrayIndex += TruncatedN;
430 return;
431 }
432
433 // [expr.add]p4: For the purposes of these operators, a pointer to a
434 // nonarray object behaves the same as a pointer to the first element of
435 // an array of length one with the type of the object as its element type.
436 bool IsArray = MostDerivedPathLength == Entries.size() &&
437 MostDerivedIsArrayElement;
438 uint64_t ArrayIndex =
439 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
440 uint64_t ArraySize =
441 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
442
443 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
444 // Calculate the actual index in a wide enough type, so we can include
445 // it in the note.
446 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
447 (llvm::APInt&)N += ArrayIndex;
448 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
449 diagnosePointerArithmetic(Info, E, N);
450 setInvalid();
451 return;
452 }
453
454 ArrayIndex += TruncatedN;
455 assert(ArrayIndex <= ArraySize &&
456 "bounds check succeeded for out-of-bounds index");
457
458 if (IsArray)
459 Entries.back().ArrayIndex = ArrayIndex;
460 else
461 IsOnePastTheEnd = (ArrayIndex != 0);
462 }
Richard Smith96e0c102011-11-04 02:25:55 +0000463 };
464
Richard Smith254a73d2011-10-28 22:34:42 +0000465 /// A stack frame in the constexpr call stack.
466 struct CallStackFrame {
467 EvalInfo &Info;
468
469 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000470 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000471
Richard Smithf6f003a2011-12-16 19:06:07 +0000472 /// Callee - The function which was called.
473 const FunctionDecl *Callee;
474
Richard Smithd62306a2011-11-10 06:34:14 +0000475 /// This - The binding for the this pointer in this call, if any.
476 const LValue *This;
477
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000478 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000479 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000480 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000481
Eli Friedman4830ec82012-06-25 21:21:08 +0000482 // Note that we intentionally use std::map here so that references to
483 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000484 typedef std::pair<const void *, unsigned> MapKeyTy;
485 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000486 /// Temporaries - Temporary lvalues materialized within this stack frame.
487 MapTy Temporaries;
488
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000489 /// CallLoc - The location of the call expression for this call.
490 SourceLocation CallLoc;
491
492 /// Index - The call index of this call.
493 unsigned Index;
494
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000495 /// The stack of integers for tracking version numbers for temporaries.
496 SmallVector<unsigned, 2> TempVersionStack = {1};
497 unsigned CurTempVersion = TempVersionStack.back();
498
499 unsigned getTempVersion() const { return TempVersionStack.back(); }
500
501 void pushTempVersion() {
502 TempVersionStack.push_back(++CurTempVersion);
503 }
504
505 void popTempVersion() {
506 TempVersionStack.pop_back();
507 }
508
Faisal Vali051e3a22017-02-16 04:12:21 +0000509 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000510 // on the overall stack usage of deeply-recursing constexpr evaluations.
Faisal Vali051e3a22017-02-16 04:12:21 +0000511 // (We should cache this map rather than recomputing it repeatedly.)
512 // But let's try this and see how it goes; we can look into caching the map
513 // as a later change.
514
515 /// LambdaCaptureFields - Mapping from captured variables/this to
516 /// corresponding data members in the closure class.
517 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
518 FieldDecl *LambdaThisCaptureField;
519
Richard Smithf6f003a2011-12-16 19:06:07 +0000520 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
521 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000522 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000523 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000524
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000525 // Return the temporary for Key whose version number is Version.
526 APValue *getTemporary(const void *Key, unsigned Version) {
527 MapKeyTy KV(Key, Version);
528 auto LB = Temporaries.lower_bound(KV);
529 if (LB != Temporaries.end() && LB->first == KV)
530 return &LB->second;
531 // Pair (Key,Version) wasn't found in the map. Check that no elements
532 // in the map have 'Key' as their key.
533 assert((LB == Temporaries.end() || LB->first.first != Key) &&
534 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
535 "Element with key 'Key' found in map");
536 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000537 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000538
539 // Return the current temporary for Key in the map.
540 APValue *getCurrentTemporary(const void *Key) {
541 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
542 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
543 return &std::prev(UB)->second;
544 return nullptr;
545 }
546
547 // Return the version number of the current temporary for Key.
548 unsigned getCurrentTemporaryVersion(const void *Key) const {
549 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
550 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
551 return std::prev(UB)->first.second;
552 return 0;
553 }
554
Richard Smith08d6a2c2013-07-24 07:11:57 +0000555 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000556 };
557
Richard Smith852c9db2013-04-20 22:23:05 +0000558 /// Temporarily override 'this'.
559 class ThisOverrideRAII {
560 public:
561 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
562 : Frame(Frame), OldThis(Frame.This) {
563 if (Enable)
564 Frame.This = NewThis;
565 }
566 ~ThisOverrideRAII() {
567 Frame.This = OldThis;
568 }
569 private:
570 CallStackFrame &Frame;
571 const LValue *OldThis;
572 };
573
Richard Smith92b1ce02011-12-12 09:28:41 +0000574 /// A partial diagnostic which we might know in advance that we are not going
575 /// to emit.
576 class OptionalDiagnostic {
577 PartialDiagnostic *Diag;
578
579 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000580 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
581 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000582
583 template<typename T>
584 OptionalDiagnostic &operator<<(const T &v) {
585 if (Diag)
586 *Diag << v;
587 return *this;
588 }
Richard Smithfe800032012-01-31 04:08:20 +0000589
590 OptionalDiagnostic &operator<<(const APSInt &I) {
591 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000592 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000593 I.toString(Buffer);
594 *Diag << StringRef(Buffer.data(), Buffer.size());
595 }
596 return *this;
597 }
598
599 OptionalDiagnostic &operator<<(const APFloat &F) {
600 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000601 // FIXME: Force the precision of the source value down so we don't
602 // print digits which are usually useless (we don't really care here if
603 // we truncate a digit by accident in edge cases). Ideally,
Fangrui Song6907ce22018-07-30 19:24:48 +0000604 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000605 // representation which rounds to the correct value, but it's a bit
606 // tricky to implement.
607 unsigned precision =
608 llvm::APFloat::semanticsPrecision(F.getSemantics());
609 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000610 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000611 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000612 *Diag << StringRef(Buffer.data(), Buffer.size());
613 }
614 return *this;
615 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000616 };
617
Richard Smith08d6a2c2013-07-24 07:11:57 +0000618 /// A cleanup, and a flag indicating whether it is lifetime-extended.
619 class Cleanup {
620 llvm::PointerIntPair<APValue*, 1, bool> Value;
621
622 public:
623 Cleanup(APValue *Val, bool IsLifetimeExtended)
624 : Value(Val, IsLifetimeExtended) {}
625
626 bool isLifetimeExtended() const { return Value.getInt(); }
627 void endLifetime() {
628 *Value.getPointer() = APValue();
629 }
630 };
631
Richard Smithb228a862012-02-15 02:18:13 +0000632 /// EvalInfo - This is a private struct used by the evaluator to capture
633 /// information about a subexpression as it is folded. It retains information
634 /// about the AST context, but also maintains information about the folded
635 /// expression.
636 ///
637 /// If an expression could be evaluated, it is still possible it is not a C
638 /// "integer constant expression" or constant expression. If not, this struct
639 /// captures information about how and why not.
640 ///
641 /// One bit of information passed *into* the request for constant folding
642 /// indicates whether the subexpression is "evaluated" or not according to C
643 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
644 /// evaluate the expression regardless of what the RHS is, but C only allows
645 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000646 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000647 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000648
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000649 /// EvalStatus - Contains information about the evaluation.
650 Expr::EvalStatus &EvalStatus;
651
652 /// CurrentCall - The top of the constexpr call stack.
653 CallStackFrame *CurrentCall;
654
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000655 /// CallStackDepth - The number of calls in the call stack right now.
656 unsigned CallStackDepth;
657
Richard Smithb228a862012-02-15 02:18:13 +0000658 /// NextCallIndex - The next call index to assign.
659 unsigned NextCallIndex;
660
Richard Smitha3d3bd22013-05-08 02:12:03 +0000661 /// StepsLeft - The remaining number of evaluation steps we're permitted
662 /// to perform. This is essentially a limit for the number of statements
663 /// we will evaluate.
664 unsigned StepsLeft;
665
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000666 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000667 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000668 CallStackFrame BottomFrame;
669
Richard Smith08d6a2c2013-07-24 07:11:57 +0000670 /// A stack of values whose lifetimes end at the end of some surrounding
671 /// evaluation frame.
672 llvm::SmallVector<Cleanup, 16> CleanupStack;
673
Richard Smithd62306a2011-11-10 06:34:14 +0000674 /// EvaluatingDecl - This is the declaration whose initializer is being
675 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000676 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000677
678 /// EvaluatingDeclValue - This is the value being constructed for the
679 /// declaration whose initializer is being evaluated, if any.
680 APValue *EvaluatingDeclValue;
681
Erik Pilkington42925492017-10-04 00:18:55 +0000682 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
683 /// the call index that that lvalue was allocated in.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000684 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
685 EvaluatingObject;
Erik Pilkington42925492017-10-04 00:18:55 +0000686
687 /// EvaluatingConstructors - Set of objects that are currently being
688 /// constructed.
689 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
690
691 struct EvaluatingConstructorRAII {
692 EvalInfo &EI;
693 EvaluatingObject Object;
694 bool DidInsert;
695 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
696 : EI(EI), Object(Object) {
697 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
698 }
699 ~EvaluatingConstructorRAII() {
700 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
701 }
702 };
703
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000704 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
705 unsigned Version) {
706 return EvaluatingConstructors.count(
707 EvaluatingObject(Decl, {CallIndex, Version}));
Erik Pilkington42925492017-10-04 00:18:55 +0000708 }
709
Richard Smith410306b2016-12-12 02:53:20 +0000710 /// The current array initialization index, if we're performing array
711 /// initialization.
712 uint64_t ArrayInitIndex = -1;
713
Richard Smith357362d2011-12-13 06:39:58 +0000714 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
715 /// notes attached to it will also be stored, otherwise they will not be.
716 bool HasActiveDiagnostic;
717
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000718 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000719 /// fold (not just why it's not strictly a constant expression)?
720 bool HasFoldFailureDiagnostic;
721
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000722 /// Whether or not we're currently speculatively evaluating.
George Burgess IV8c892b52016-05-25 22:31:54 +0000723 bool IsSpeculativelyEvaluating;
724
Fangrui Song407659a2018-11-30 23:41:18 +0000725 /// Whether or not we're in a context where the front end requires a
726 /// constant value.
727 bool InConstantContext;
728
Richard Smith6d4c6582013-11-05 22:18:15 +0000729 enum EvaluationMode {
730 /// Evaluate as a constant expression. Stop if we find that the expression
731 /// is not a constant expression.
732 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000733
Richard Smith6d4c6582013-11-05 22:18:15 +0000734 /// Evaluate as a potential constant expression. Keep going if we hit a
735 /// construct that we can't evaluate yet (because we don't yet know the
736 /// value of something) but stop if we hit something that could never be
737 /// a constant expression.
738 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000739
Richard Smith6d4c6582013-11-05 22:18:15 +0000740 /// Fold the expression to a constant. Stop if we hit a side-effect that
741 /// we can't model.
742 EM_ConstantFold,
743
744 /// Evaluate the expression looking for integer overflow and similar
745 /// issues. Don't worry about side-effects, and try to visit all
746 /// subexpressions.
747 EM_EvaluateForOverflow,
748
749 /// Evaluate in any way we know how. Don't worry about side-effects that
750 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000751 EM_IgnoreSideEffects,
752
753 /// Evaluate as a constant expression. Stop if we find that the expression
754 /// is not a constant expression. Some expressions can be retried in the
755 /// optimizer if we don't constant fold them here, but in an unevaluated
756 /// context we try to fold them immediately since the optimizer never
757 /// gets a chance to look at it.
758 EM_ConstantExpressionUnevaluated,
759
760 /// Evaluate as a potential constant expression. Keep going if we hit a
761 /// construct that we can't evaluate yet (because we don't yet know the
762 /// value of something) but stop if we hit something that could never be
763 /// a constant expression. Some expressions can be retried in the
764 /// optimizer if we don't constant fold them here, but in an unevaluated
765 /// context we try to fold them immediately since the optimizer never
766 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000767 EM_PotentialConstantExpressionUnevaluated,
Richard Smith6d4c6582013-11-05 22:18:15 +0000768 } EvalMode;
769
770 /// Are we checking whether the expression is a potential constant
771 /// expression?
772 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000773 return EvalMode == EM_PotentialConstantExpression ||
774 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000775 }
776
777 /// Are we checking an expression for overflow?
778 // FIXME: We should check for any kind of undefined or suspicious behavior
779 // in such constructs, not just overflow.
780 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
781
782 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000783 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000784 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000785 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000786 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
787 EvaluatingDecl((const ValueDecl *)nullptr),
788 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000789 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
Fangrui Song407659a2018-11-30 23:41:18 +0000790 InConstantContext(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000791
Richard Smith7525ff62013-05-09 07:14:00 +0000792 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
793 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000794 EvaluatingDeclValue = &Value;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000795 EvaluatingConstructors.insert({Base, {0, 0}});
Richard Smithd62306a2011-11-10 06:34:14 +0000796 }
797
David Blaikiebbafb8a2012-03-11 07:00:24 +0000798 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000799
Richard Smith357362d2011-12-13 06:39:58 +0000800 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000801 // Don't perform any constexpr calls (other than the call we're checking)
802 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000803 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000804 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000805 if (NextCallIndex == 0) {
806 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000807 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000808 return false;
809 }
Richard Smith357362d2011-12-13 06:39:58 +0000810 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
811 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000812 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000813 << getLangOpts().ConstexprCallDepth;
814 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000815 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000816
Richard Smithb228a862012-02-15 02:18:13 +0000817 CallStackFrame *getCallFrame(unsigned CallIndex) {
818 assert(CallIndex && "no call index in getCallFrame");
819 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
820 // be null in this loop.
821 CallStackFrame *Frame = CurrentCall;
822 while (Frame->Index > CallIndex)
823 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000824 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000825 }
826
Richard Smitha3d3bd22013-05-08 02:12:03 +0000827 bool nextStep(const Stmt *S) {
828 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000829 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000830 return false;
831 }
832 --StepsLeft;
833 return true;
834 }
835
Richard Smith357362d2011-12-13 06:39:58 +0000836 private:
837 /// Add a diagnostic to the diagnostics list.
838 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
839 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
840 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
841 return EvalStatus.Diag->back().second;
842 }
843
Richard Smithf6f003a2011-12-16 19:06:07 +0000844 /// Add notes containing a call stack to the current point of evaluation.
845 void addCallStack(unsigned Limit);
846
Faisal Valie690b7a2016-07-02 22:34:24 +0000847 private:
848 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
849 unsigned ExtraNotes, bool IsCCEDiag) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000850
Richard Smith92b1ce02011-12-12 09:28:41 +0000851 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000852 // If we have a prior diagnostic, it will be noting that the expression
853 // isn't a constant expression. This diagnostic is more important,
854 // unless we require this evaluation to produce a constant expression.
855 //
856 // FIXME: We might want to show both diagnostics to the user in
857 // EM_ConstantFold mode.
858 if (!EvalStatus.Diag->empty()) {
859 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000860 case EM_ConstantFold:
861 case EM_IgnoreSideEffects:
862 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000863 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000864 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000865 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000866 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000867 case EM_ConstantExpression:
868 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000869 case EM_ConstantExpressionUnevaluated:
870 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000871 HasActiveDiagnostic = false;
872 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000873 }
874 }
875
Richard Smithf6f003a2011-12-16 19:06:07 +0000876 unsigned CallStackNotes = CallStackDepth - 1;
877 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
878 if (Limit)
879 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000880 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000881 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000882
Richard Smith357362d2011-12-13 06:39:58 +0000883 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000884 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000885 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000886 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
887 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000888 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000889 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000890 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000891 }
Richard Smith357362d2011-12-13 06:39:58 +0000892 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000893 return OptionalDiagnostic();
894 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000895 public:
896 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
897 OptionalDiagnostic
898 FFDiag(SourceLocation Loc,
899 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
900 unsigned ExtraNotes = 0) {
901 return Diag(Loc, DiagId, ExtraNotes, false);
902 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000903
Faisal Valie690b7a2016-07-02 22:34:24 +0000904 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000905 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000906 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000907 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000908 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000909 HasActiveDiagnostic = false;
910 return OptionalDiagnostic();
911 }
912
Richard Smith92b1ce02011-12-12 09:28:41 +0000913 /// Diagnose that the evaluation does not produce a C++11 core constant
914 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000915 ///
916 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
917 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000918 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000919 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000920 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000921 // Don't override a previous diagnostic. Don't bother collecting
922 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000923 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000924 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000925 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000926 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000927 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000928 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000929 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
930 = diag::note_invalid_subexpr_in_const_expr,
931 unsigned ExtraNotes = 0) {
932 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
933 }
Richard Smith357362d2011-12-13 06:39:58 +0000934 /// Add a note to a prior diagnostic.
935 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
936 if (!HasActiveDiagnostic)
937 return OptionalDiagnostic();
938 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000939 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000940
941 /// Add a stack of notes to a prior diagnostic.
942 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
943 if (HasActiveDiagnostic) {
944 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
945 Diags.begin(), Diags.end());
946 }
947 }
Richard Smith253c2a32012-01-27 01:14:48 +0000948
Richard Smith6d4c6582013-11-05 22:18:15 +0000949 /// Should we continue evaluation after encountering a side-effect that we
950 /// couldn't model?
951 bool keepEvaluatingAfterSideEffect() {
952 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000953 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000954 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000955 case EM_EvaluateForOverflow:
956 case EM_IgnoreSideEffects:
957 return true;
958
Richard Smith6d4c6582013-11-05 22:18:15 +0000959 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000960 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000961 case EM_ConstantFold:
962 return false;
963 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000964 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000965 }
966
967 /// Note that we have had a side-effect, and determine whether we should
968 /// keep evaluating.
969 bool noteSideEffect() {
970 EvalStatus.HasSideEffects = true;
971 return keepEvaluatingAfterSideEffect();
972 }
973
Richard Smithce8eca52015-12-08 03:21:47 +0000974 /// Should we continue evaluation after encountering undefined behavior?
975 bool keepEvaluatingAfterUndefinedBehavior() {
976 switch (EvalMode) {
977 case EM_EvaluateForOverflow:
978 case EM_IgnoreSideEffects:
979 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000980 return true;
981
982 case EM_PotentialConstantExpression:
983 case EM_PotentialConstantExpressionUnevaluated:
984 case EM_ConstantExpression:
985 case EM_ConstantExpressionUnevaluated:
986 return false;
987 }
988 llvm_unreachable("Missed EvalMode case");
989 }
990
991 /// Note that we hit something that was technically undefined behavior, but
992 /// that we can evaluate past it (such as signed overflow or floating-point
993 /// division by zero.)
994 bool noteUndefinedBehavior() {
995 EvalStatus.HasUndefinedBehavior = true;
996 return keepEvaluatingAfterUndefinedBehavior();
997 }
998
Richard Smith253c2a32012-01-27 01:14:48 +0000999 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001000 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +00001001 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +00001002 if (!StepsLeft)
1003 return false;
1004
1005 switch (EvalMode) {
1006 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001007 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001008 case EM_EvaluateForOverflow:
1009 return true;
1010
1011 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001012 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001013 case EM_ConstantFold:
1014 case EM_IgnoreSideEffects:
1015 return false;
1016 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001017 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001018 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001019
George Burgess IV8c892b52016-05-25 22:31:54 +00001020 /// Notes that we failed to evaluate an expression that other expressions
1021 /// directly depend on, and determine if we should keep evaluating. This
1022 /// should only be called if we actually intend to keep evaluating.
1023 ///
1024 /// Call noteSideEffect() instead if we may be able to ignore the value that
1025 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1026 ///
1027 /// (Foo(), 1) // use noteSideEffect
1028 /// (Foo() || true) // use noteSideEffect
1029 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001030 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001031 // Failure when evaluating some expression often means there is some
1032 // subexpression whose evaluation was skipped. Therefore, (because we
1033 // don't track whether we skipped an expression when unwinding after an
1034 // evaluation failure) every evaluation failure that bubbles up from a
1035 // subexpression implies that a side-effect has potentially happened. We
1036 // skip setting the HasSideEffects flag to true until we decide to
1037 // continue evaluating after that point, which happens here.
1038 bool KeepGoing = keepEvaluatingAfterFailure();
1039 EvalStatus.HasSideEffects |= KeepGoing;
1040 return KeepGoing;
1041 }
1042
Richard Smith410306b2016-12-12 02:53:20 +00001043 class ArrayInitLoopIndex {
1044 EvalInfo &Info;
1045 uint64_t OuterIndex;
1046
1047 public:
1048 ArrayInitLoopIndex(EvalInfo &Info)
1049 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1050 Info.ArrayInitIndex = 0;
1051 }
1052 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1053
1054 operator uint64_t&() { return Info.ArrayInitIndex; }
1055 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001056 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001057
1058 /// Object used to treat all foldable expressions as constant expressions.
1059 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001060 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001061 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001062 bool HadNoPriorDiags;
1063 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001064
Richard Smith6d4c6582013-11-05 22:18:15 +00001065 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1066 : Info(Info),
1067 Enabled(Enabled),
1068 HadNoPriorDiags(Info.EvalStatus.Diag &&
1069 Info.EvalStatus.Diag->empty() &&
1070 !Info.EvalStatus.HasSideEffects),
1071 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001072 if (Enabled &&
1073 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1074 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001075 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001076 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001077 void keepDiagnostics() { Enabled = false; }
1078 ~FoldConstant() {
1079 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001080 !Info.EvalStatus.HasSideEffects)
1081 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001082 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001083 }
1084 };
Richard Smith17100ba2012-02-16 02:46:34 +00001085
James Y Knight892b09b2018-10-10 02:53:43 +00001086 /// RAII object used to set the current evaluation mode to ignore
1087 /// side-effects.
1088 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001089 EvalInfo &Info;
1090 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001091 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001092 : Info(Info), OldMode(Info.EvalMode) {
1093 if (!Info.checkingPotentialConstantExpression())
James Y Knight892b09b2018-10-10 02:53:43 +00001094 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001095 }
1096
James Y Knight892b09b2018-10-10 02:53:43 +00001097 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001098 };
1099
George Burgess IV8c892b52016-05-25 22:31:54 +00001100 /// RAII object used to optionally suppress diagnostics and side-effects from
1101 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001102 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001103 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001104 Expr::EvalStatus OldStatus;
1105 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001106
George Burgess IV8c892b52016-05-25 22:31:54 +00001107 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001108 Info = Other.Info;
1109 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001110 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001111 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001112 }
1113
1114 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001115 if (!Info)
1116 return;
1117
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001118 Info->EvalStatus = OldStatus;
1119 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001120 }
1121
Richard Smith17100ba2012-02-16 02:46:34 +00001122 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001123 SpeculativeEvaluationRAII() = default;
1124
1125 SpeculativeEvaluationRAII(
1126 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001127 : Info(&Info), OldStatus(Info.EvalStatus),
1128 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001129 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001130 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001131 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001132
1133 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1134 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1135 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001136 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001137
1138 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1139 maybeRestoreState();
1140 moveFromAndCancel(std::move(Other));
1141 return *this;
1142 }
1143
1144 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001145 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001146
1147 /// RAII object wrapping a full-expression or block scope, and handling
1148 /// the ending of the lifetime of temporaries created within it.
1149 template<bool IsFullExpression>
1150 class ScopeRAII {
1151 EvalInfo &Info;
1152 unsigned OldStackSize;
1153 public:
1154 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001155 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1156 // Push a new temporary version. This is needed to distinguish between
1157 // temporaries created in different iterations of a loop.
1158 Info.CurrentCall->pushTempVersion();
1159 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001160 ~ScopeRAII() {
1161 // Body moved to a static method to encourage the compiler to inline away
1162 // instances of this class.
1163 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001164 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001165 }
1166 private:
1167 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1168 unsigned NewEnd = OldStackSize;
1169 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1170 I != N; ++I) {
1171 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1172 // Full-expression cleanup of a lifetime-extended temporary: nothing
1173 // to do, just move this cleanup to the right place in the stack.
1174 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1175 ++NewEnd;
1176 } else {
1177 // End the lifetime of the object.
1178 Info.CleanupStack[I].endLifetime();
1179 }
1180 }
1181 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1182 Info.CleanupStack.end());
1183 }
1184 };
1185 typedef ScopeRAII<false> BlockScopeRAII;
1186 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001187}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001188
Richard Smitha8105bc2012-01-06 16:39:00 +00001189bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1190 CheckSubobjectKind CSK) {
1191 if (Invalid)
1192 return false;
1193 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001194 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001195 << CSK;
1196 setInvalid();
1197 return false;
1198 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001199 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1200 // must actually be at least one array element; even a VLA cannot have a
1201 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001202 return true;
1203}
1204
Richard Smith6f4f0f12017-10-20 22:56:25 +00001205void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1206 const Expr *E) {
1207 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1208 // Do not set the designator as invalid: we can represent this situation,
1209 // and correct handling of __builtin_object_size requires us to do so.
1210}
1211
Richard Smitha8105bc2012-01-06 16:39:00 +00001212void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001213 const Expr *E,
1214 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001215 // If we're complaining, we must be able to statically determine the size of
1216 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001217 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001218 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001219 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001220 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001221 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001222 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001223 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001224 setInvalid();
1225}
1226
Richard Smithf6f003a2011-12-16 19:06:07 +00001227CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1228 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001229 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001230 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1231 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001232 Info.CurrentCall = this;
1233 ++Info.CallStackDepth;
1234}
1235
1236CallStackFrame::~CallStackFrame() {
1237 assert(Info.CurrentCall == this && "calls retired out of order");
1238 --Info.CallStackDepth;
1239 Info.CurrentCall = Caller;
1240}
1241
Richard Smith08d6a2c2013-07-24 07:11:57 +00001242APValue &CallStackFrame::createTemporary(const void *Key,
1243 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001244 unsigned Version = Info.CurrentCall->getTempVersion();
1245 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smith08d6a2c2013-07-24 07:11:57 +00001246 assert(Result.isUninit() && "temporary created multiple times");
1247 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1248 return Result;
1249}
1250
Richard Smith84401042013-06-03 05:03:02 +00001251static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001252
1253void EvalInfo::addCallStack(unsigned Limit) {
1254 // Determine which calls to skip, if any.
1255 unsigned ActiveCalls = CallStackDepth - 1;
1256 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1257 if (Limit && Limit < ActiveCalls) {
1258 SkipStart = Limit / 2 + Limit % 2;
1259 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001260 }
1261
Richard Smithf6f003a2011-12-16 19:06:07 +00001262 // Walk the call stack and add the diagnostics.
1263 unsigned CallIdx = 0;
1264 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1265 Frame = Frame->Caller, ++CallIdx) {
1266 // Skip this call?
1267 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1268 if (CallIdx == SkipStart) {
1269 // Note that we're skipping calls.
1270 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1271 << unsigned(ActiveCalls - Limit);
1272 }
1273 continue;
1274 }
1275
Richard Smith5179eb72016-06-28 19:03:57 +00001276 // Use a different note for an inheriting constructor, because from the
1277 // user's perspective it's not really a function at all.
1278 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1279 if (CD->isInheritingConstructor()) {
1280 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1281 << CD->getParent();
1282 continue;
1283 }
1284 }
1285
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001286 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001287 llvm::raw_svector_ostream Out(Buffer);
1288 describeCall(Frame, Out);
1289 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1290 }
1291}
1292
Hubert Tong147b7432018-12-12 16:53:43 +00001293/// Kinds of access we can perform on an object, for diagnostics.
1294enum AccessKinds {
1295 AK_Read,
1296 AK_Assign,
1297 AK_Increment,
1298 AK_Decrement
1299};
1300
Richard Smithf6f003a2011-12-16 19:06:07 +00001301namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001302 struct ComplexValue {
1303 private:
1304 bool IsInt;
1305
1306 public:
1307 APSInt IntReal, IntImag;
1308 APFloat FloatReal, FloatImag;
1309
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001310 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001311
1312 void makeComplexFloat() { IsInt = false; }
1313 bool isComplexFloat() const { return !IsInt; }
1314 APFloat &getComplexFloatReal() { return FloatReal; }
1315 APFloat &getComplexFloatImag() { return FloatImag; }
1316
1317 void makeComplexInt() { IsInt = true; }
1318 bool isComplexInt() const { return IsInt; }
1319 APSInt &getComplexIntReal() { return IntReal; }
1320 APSInt &getComplexIntImag() { return IntImag; }
1321
Richard Smith2e312c82012-03-03 22:46:17 +00001322 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001323 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001324 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001325 else
Richard Smith2e312c82012-03-03 22:46:17 +00001326 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001327 }
Richard Smith2e312c82012-03-03 22:46:17 +00001328 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001329 assert(v.isComplexFloat() || v.isComplexInt());
1330 if (v.isComplexFloat()) {
1331 makeComplexFloat();
1332 FloatReal = v.getComplexFloatReal();
1333 FloatImag = v.getComplexFloatImag();
1334 } else {
1335 makeComplexInt();
1336 IntReal = v.getComplexIntReal();
1337 IntImag = v.getComplexIntImag();
1338 }
1339 }
John McCall93d91dc2010-05-07 17:22:02 +00001340 };
John McCall45d55e42010-05-07 21:00:08 +00001341
1342 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001343 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001344 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001345 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001346 bool IsNullPtr : 1;
1347 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001348
Richard Smithce40ad62011-11-12 22:28:03 +00001349 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001350 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001351 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001352 SubobjectDesignator &getLValueDesignator() { return Designator; }
1353 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001354 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001355
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001356 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1357 unsigned getLValueVersion() const { return Base.getVersion(); }
1358
Richard Smith2e312c82012-03-03 22:46:17 +00001359 void moveInto(APValue &V) const {
1360 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001361 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001362 else {
1363 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001364 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001365 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001366 }
John McCall45d55e42010-05-07 21:00:08 +00001367 }
Richard Smith2e312c82012-03-03 22:46:17 +00001368 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001369 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001370 Base = V.getLValueBase();
1371 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001372 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001373 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001374 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001375 }
1376
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001377 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001378#ifndef NDEBUG
1379 // We only allow a few types of invalid bases. Enforce that here.
1380 if (BInvalid) {
1381 const auto *E = B.get<const Expr *>();
1382 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1383 "Unexpected type of invalid base");
1384 }
1385#endif
1386
Richard Smithce40ad62011-11-12 22:28:03 +00001387 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001388 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001389 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001390 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001391 IsNullPtr = false;
1392 }
1393
1394 void setNull(QualType PointerTy, uint64_t TargetVal) {
1395 Base = (Expr *)nullptr;
1396 Offset = CharUnits::fromQuantity(TargetVal);
1397 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001398 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1399 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001400 }
1401
George Burgess IV3a03fab2015-09-04 21:28:13 +00001402 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001403 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001404 }
1405
Hubert Tong147b7432018-12-12 16:53:43 +00001406 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001407 // Check that this LValue is not based on a null pointer. If it is, produce
1408 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001409 template <typename GenDiagType>
1410 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001411 if (Designator.Invalid)
1412 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001413 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001414 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001415 Designator.setInvalid();
1416 return false;
1417 }
1418 return true;
1419 }
1420
Hubert Tong147b7432018-12-12 16:53:43 +00001421 public:
1422 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1423 CheckSubobjectKind CSK) {
1424 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1425 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1426 });
1427 }
1428
1429 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1430 AccessKinds AK) {
1431 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1432 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1433 });
1434 }
1435
Richard Smitha8105bc2012-01-06 16:39:00 +00001436 // Check this LValue refers to an object. If not, set the designator to be
1437 // invalid and emit a diagnostic.
1438 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001439 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001440 Designator.checkSubobject(Info, E, CSK);
1441 }
1442
1443 void addDecl(EvalInfo &Info, const Expr *E,
1444 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001445 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1446 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001447 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001448 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1449 if (!Designator.Entries.empty()) {
1450 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1451 Designator.setInvalid();
1452 return;
1453 }
Richard Smithefdb5032017-11-15 03:03:56 +00001454 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1455 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1456 Designator.FirstEntryIsAnUnsizedArray = true;
1457 Designator.addUnsizedArrayUnchecked(ElemTy);
1458 }
George Burgess IVe3763372016-12-22 02:50:20 +00001459 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001460 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001461 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1462 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001463 }
Richard Smith66c96992012-02-18 22:04:06 +00001464 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001465 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1466 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001467 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001468 void clearIsNullPointer() {
1469 IsNullPtr = false;
1470 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001471 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1472 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001473 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1474 // but we're not required to diagnose it and it's valid in C++.)
1475 if (!Index)
1476 return;
1477
1478 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1479 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1480 // offsets.
1481 uint64_t Offset64 = Offset.getQuantity();
1482 uint64_t ElemSize64 = ElementSize.getQuantity();
1483 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1484 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1485
1486 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001487 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001488 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001489 }
1490 void adjustOffset(CharUnits N) {
1491 Offset += N;
1492 if (N.getQuantity())
1493 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001494 }
John McCall45d55e42010-05-07 21:00:08 +00001495 };
Richard Smith027bf112011-11-17 22:56:20 +00001496
1497 struct MemberPtr {
1498 MemberPtr() {}
1499 explicit MemberPtr(const ValueDecl *Decl) :
1500 DeclAndIsDerivedMember(Decl, false), Path() {}
1501
1502 /// The member or (direct or indirect) field referred to by this member
1503 /// pointer, or 0 if this is a null member pointer.
1504 const ValueDecl *getDecl() const {
1505 return DeclAndIsDerivedMember.getPointer();
1506 }
1507 /// Is this actually a member of some type derived from the relevant class?
1508 bool isDerivedMember() const {
1509 return DeclAndIsDerivedMember.getInt();
1510 }
1511 /// Get the class which the declaration actually lives in.
1512 const CXXRecordDecl *getContainingRecord() const {
1513 return cast<CXXRecordDecl>(
1514 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1515 }
1516
Richard Smith2e312c82012-03-03 22:46:17 +00001517 void moveInto(APValue &V) const {
1518 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001519 }
Richard Smith2e312c82012-03-03 22:46:17 +00001520 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001521 assert(V.isMemberPointer());
1522 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1523 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1524 Path.clear();
1525 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1526 Path.insert(Path.end(), P.begin(), P.end());
1527 }
1528
1529 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1530 /// whether the member is a member of some class derived from the class type
1531 /// of the member pointer.
1532 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1533 /// Path - The path of base/derived classes from the member declaration's
1534 /// class (exclusive) to the class type of the member pointer (inclusive).
1535 SmallVector<const CXXRecordDecl*, 4> Path;
1536
1537 /// Perform a cast towards the class of the Decl (either up or down the
1538 /// hierarchy).
1539 bool castBack(const CXXRecordDecl *Class) {
1540 assert(!Path.empty());
1541 const CXXRecordDecl *Expected;
1542 if (Path.size() >= 2)
1543 Expected = Path[Path.size() - 2];
1544 else
1545 Expected = getContainingRecord();
1546 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1547 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1548 // if B does not contain the original member and is not a base or
1549 // derived class of the class containing the original member, the result
1550 // of the cast is undefined.
1551 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1552 // (D::*). We consider that to be a language defect.
1553 return false;
1554 }
1555 Path.pop_back();
1556 return true;
1557 }
1558 /// Perform a base-to-derived member pointer cast.
1559 bool castToDerived(const CXXRecordDecl *Derived) {
1560 if (!getDecl())
1561 return true;
1562 if (!isDerivedMember()) {
1563 Path.push_back(Derived);
1564 return true;
1565 }
1566 if (!castBack(Derived))
1567 return false;
1568 if (Path.empty())
1569 DeclAndIsDerivedMember.setInt(false);
1570 return true;
1571 }
1572 /// Perform a derived-to-base member pointer cast.
1573 bool castToBase(const CXXRecordDecl *Base) {
1574 if (!getDecl())
1575 return true;
1576 if (Path.empty())
1577 DeclAndIsDerivedMember.setInt(true);
1578 if (isDerivedMember()) {
1579 Path.push_back(Base);
1580 return true;
1581 }
1582 return castBack(Base);
1583 }
1584 };
Richard Smith357362d2011-12-13 06:39:58 +00001585
Richard Smith7bb00672012-02-01 01:42:44 +00001586 /// Compare two member pointers, which are assumed to be of the same type.
1587 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1588 if (!LHS.getDecl() || !RHS.getDecl())
1589 return !LHS.getDecl() && !RHS.getDecl();
1590 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1591 return false;
1592 return LHS.Path == RHS.Path;
1593 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001594}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001595
Richard Smith2e312c82012-03-03 22:46:17 +00001596static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001597static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1598 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001599 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001600static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1601 bool InvalidBaseOK = false);
1602static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1603 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001604static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1605 EvalInfo &Info);
1606static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001607static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001608static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001609 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001610static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001611static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001612static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1613 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001614static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001615
1616//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001617// Misc utilities
1618//===----------------------------------------------------------------------===//
1619
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001620/// A helper function to create a temporary and set an LValue.
1621template <class KeyTy>
1622static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1623 LValue &LV, CallStackFrame &Frame) {
1624 LV.set({Key, Frame.Info.CurrentCall->Index,
1625 Frame.Info.CurrentCall->getTempVersion()});
1626 return Frame.createTemporary(Key, IsLifetimeExtended);
1627}
1628
Richard Smithd6cc1982017-01-31 02:23:02 +00001629/// Negate an APSInt in place, converting it to a signed form if necessary, and
1630/// preserving its value (by extending by up to one bit as needed).
1631static void negateAsSigned(APSInt &Int) {
1632 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1633 Int = Int.extend(Int.getBitWidth() + 1);
1634 Int.setIsSigned(true);
1635 }
1636 Int = -Int;
1637}
1638
Richard Smith84401042013-06-03 05:03:02 +00001639/// Produce a string describing the given constexpr call.
1640static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1641 unsigned ArgIndex = 0;
1642 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1643 !isa<CXXConstructorDecl>(Frame->Callee) &&
1644 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1645
1646 if (!IsMemberCall)
1647 Out << *Frame->Callee << '(';
1648
1649 if (Frame->This && IsMemberCall) {
1650 APValue Val;
1651 Frame->This->moveInto(Val);
1652 Val.printPretty(Out, Frame->Info.Ctx,
1653 Frame->This->Designator.MostDerivedType);
1654 // FIXME: Add parens around Val if needed.
1655 Out << "->" << *Frame->Callee << '(';
1656 IsMemberCall = false;
1657 }
1658
1659 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1660 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1661 if (ArgIndex > (unsigned)IsMemberCall)
1662 Out << ", ";
1663
1664 const ParmVarDecl *Param = *I;
1665 const APValue &Arg = Frame->Arguments[ArgIndex];
1666 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1667
1668 if (ArgIndex == 0 && IsMemberCall)
1669 Out << "->" << *Frame->Callee << '(';
1670 }
1671
1672 Out << ')';
1673}
1674
Richard Smithd9f663b2013-04-22 15:31:51 +00001675/// Evaluate an expression to see if it had side-effects, and discard its
1676/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001677/// \return \c true if the caller should keep evaluating.
1678static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001679 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001680 if (!Evaluate(Scratch, Info, E))
1681 // We don't need the value, but we might have skipped a side effect here.
1682 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001683 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001684}
1685
Richard Smithd62306a2011-11-10 06:34:14 +00001686/// Should this call expression be treated as a string literal?
1687static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001688 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001689 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1690 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1691}
1692
Richard Smithce40ad62011-11-12 22:28:03 +00001693static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001694 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1695 // constant expression of pointer type that evaluates to...
1696
1697 // ... a null pointer value, or a prvalue core constant expression of type
1698 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001699 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001700
Richard Smithce40ad62011-11-12 22:28:03 +00001701 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1702 // ... the address of an object with static storage duration,
1703 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1704 return VD->hasGlobalStorage();
1705 // ... the address of a function,
1706 return isa<FunctionDecl>(D);
1707 }
1708
1709 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001710 switch (E->getStmtClass()) {
1711 default:
1712 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001713 case Expr::CompoundLiteralExprClass: {
1714 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1715 return CLE->isFileScope() && CLE->isLValue();
1716 }
Richard Smithe6c01442013-06-05 00:46:14 +00001717 case Expr::MaterializeTemporaryExprClass:
1718 // A materialized temporary might have been lifetime-extended to static
1719 // storage duration.
1720 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001721 // A string literal has static storage duration.
1722 case Expr::StringLiteralClass:
1723 case Expr::PredefinedExprClass:
1724 case Expr::ObjCStringLiteralClass:
1725 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001726 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001727 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001728 return true;
1729 case Expr::CallExprClass:
1730 return IsStringLiteralCall(cast<CallExpr>(E));
1731 // For GCC compatibility, &&label has static storage duration.
1732 case Expr::AddrLabelExprClass:
1733 return true;
1734 // A Block literal expression may be used as the initialization value for
1735 // Block variables at global or local static scope.
1736 case Expr::BlockExprClass:
1737 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001738 case Expr::ImplicitValueInitExprClass:
1739 // FIXME:
1740 // We can never form an lvalue with an implicit value initialization as its
1741 // base through expression evaluation, so these only appear in one case: the
1742 // implicit variable declaration we invent when checking whether a constexpr
1743 // constructor can produce a constant expression. We must assume that such
1744 // an expression might be a global lvalue.
1745 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001746 }
John McCall95007602010-05-10 23:27:23 +00001747}
1748
Richard Smith06f71b52018-08-04 00:57:17 +00001749static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1750 return LVal.Base.dyn_cast<const ValueDecl*>();
1751}
1752
1753static bool IsLiteralLValue(const LValue &Value) {
1754 if (Value.getLValueCallIndex())
1755 return false;
1756 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1757 return E && !isa<MaterializeTemporaryExpr>(E);
1758}
1759
1760static bool IsWeakLValue(const LValue &Value) {
1761 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1762 return Decl && Decl->isWeak();
1763}
1764
1765static bool isZeroSized(const LValue &Value) {
1766 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1767 if (Decl && isa<VarDecl>(Decl)) {
1768 QualType Ty = Decl->getType();
1769 if (Ty->isArrayType())
1770 return Ty->isIncompleteType() ||
1771 Decl->getASTContext().getTypeSize(Ty) == 0;
1772 }
1773 return false;
1774}
1775
1776static bool HasSameBase(const LValue &A, const LValue &B) {
1777 if (!A.getLValueBase())
1778 return !B.getLValueBase();
1779 if (!B.getLValueBase())
1780 return false;
1781
1782 if (A.getLValueBase().getOpaqueValue() !=
1783 B.getLValueBase().getOpaqueValue()) {
1784 const Decl *ADecl = GetLValueBaseDecl(A);
1785 if (!ADecl)
1786 return false;
1787 const Decl *BDecl = GetLValueBaseDecl(B);
1788 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1789 return false;
1790 }
1791
1792 return IsGlobalLValue(A.getLValueBase()) ||
1793 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1794 A.getLValueVersion() == B.getLValueVersion());
1795}
1796
Richard Smithb228a862012-02-15 02:18:13 +00001797static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1798 assert(Base && "no location for a null lvalue");
1799 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1800 if (VD)
1801 Info.Note(VD->getLocation(), diag::note_declared_at);
1802 else
Ted Kremenek28831752012-08-23 20:46:57 +00001803 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001804 diag::note_constexpr_temporary_here);
1805}
1806
Richard Smith80815602011-11-07 05:07:52 +00001807/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001808/// value for an address or reference constant expression. Return true if we
1809/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001810static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001811 QualType Type, const LValue &LVal,
1812 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001813 bool IsReferenceType = Type->isReferenceType();
1814
Richard Smith357362d2011-12-13 06:39:58 +00001815 APValue::LValueBase Base = LVal.getLValueBase();
1816 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1817
Richard Smith0dea49e2012-02-18 04:58:18 +00001818 // Check that the object is a global. Note that the fake 'this' object we
1819 // manufacture when checking potential constant expressions is conservatively
1820 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001821 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001822 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001823 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001824 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001825 << IsReferenceType << !Designator.Entries.empty()
1826 << !!VD << VD;
1827 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001828 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001829 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001830 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001831 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001832 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001833 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001834 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001835 LVal.getLValueCallIndex() == 0) &&
1836 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001837
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001838 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1839 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001840 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001841 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001842 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001843
Hans Wennborg82dd8772014-06-25 22:19:48 +00001844 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001845 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001846 return false;
1847 }
1848 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1849 // __declspec(dllimport) must be handled very carefully:
1850 // We must never initialize an expression with the thunk in C++.
1851 // Doing otherwise would allow the same id-expression to yield
1852 // different addresses for the same function in different translation
1853 // units. However, this means that we must dynamically initialize the
1854 // expression with the contents of the import address table at runtime.
1855 //
1856 // The C language has no notion of ODR; furthermore, it has no notion of
1857 // dynamic initialization. This means that we are permitted to
1858 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001859 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1860 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001861 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001862 }
1863 }
1864
Richard Smitha8105bc2012-01-06 16:39:00 +00001865 // Allow address constant expressions to be past-the-end pointers. This is
1866 // an extension: the standard requires them to point to an object.
1867 if (!IsReferenceType)
1868 return true;
1869
1870 // A reference constant expression must refer to an object.
1871 if (!Base) {
1872 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001873 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001874 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001875 }
1876
Richard Smith357362d2011-12-13 06:39:58 +00001877 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001878 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001879 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001880 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001881 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001882 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001883 }
1884
Richard Smith80815602011-11-07 05:07:52 +00001885 return true;
1886}
1887
Reid Klecknercd016d82017-07-07 22:04:29 +00001888/// Member pointers are constant expressions unless they point to a
1889/// non-virtual dllimport member function.
1890static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1891 SourceLocation Loc,
1892 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001893 const APValue &Value,
1894 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00001895 const ValueDecl *Member = Value.getMemberPointerDecl();
1896 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1897 if (!FD)
1898 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001899 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1900 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00001901}
1902
Richard Smithfddd3842011-12-30 21:15:51 +00001903/// Check that this core constant expression is of literal type, and if not,
1904/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001905static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001906 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001907 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001908 return true;
1909
Richard Smith7525ff62013-05-09 07:14:00 +00001910 // C++1y: A constant initializer for an object o [...] may also invoke
1911 // constexpr constructors for o and its subobjects even if those objects
1912 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001913 //
1914 // C++11 missed this detail for aggregates, so classes like this:
1915 // struct foo_t { union { int i; volatile int j; } u; };
1916 // are not (obviously) initializable like so:
1917 // __attribute__((__require_constant_initialization__))
1918 // static const foo_t x = {{0}};
1919 // because "i" is a subobject with non-literal initialization (due to the
1920 // volatile member of the union). See:
1921 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1922 // Therefore, we use the C++1y behavior.
1923 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001924 return true;
1925
Richard Smithfddd3842011-12-30 21:15:51 +00001926 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001927 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001928 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001929 << E->getType();
1930 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001931 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001932 return false;
1933}
1934
Richard Smith0b0a0b62011-10-29 20:57:55 +00001935/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001936/// constant expression. If not, report an appropriate diagnostic. Does not
1937/// check that the expression is of literal type.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001938static bool
1939CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1940 const APValue &Value,
1941 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
Richard Smith1a90f592013-06-18 17:51:51 +00001942 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001943 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001944 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001945 return false;
1946 }
1947
Richard Smith77be48a2014-07-31 06:31:19 +00001948 // We allow _Atomic(T) to be initialized from anything that T can be
1949 // initialized from.
1950 if (const AtomicType *AT = Type->getAs<AtomicType>())
1951 Type = AT->getValueType();
1952
Richard Smithb228a862012-02-15 02:18:13 +00001953 // Core issue 1454: For a literal constant expression of array or class type,
1954 // each subobject of its value shall have been initialized by a constant
1955 // expression.
1956 if (Value.isArray()) {
1957 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1958 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1959 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001960 Value.getArrayInitializedElt(I), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001961 return false;
1962 }
1963 if (!Value.hasArrayFiller())
1964 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001965 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1966 Usage);
Richard Smith80815602011-11-07 05:07:52 +00001967 }
Richard Smithb228a862012-02-15 02:18:13 +00001968 if (Value.isUnion() && Value.getUnionField()) {
1969 return CheckConstantExpression(Info, DiagLoc,
1970 Value.getUnionField()->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001971 Value.getUnionValue(), Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001972 }
1973 if (Value.isStruct()) {
1974 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1975 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1976 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001977 for (const CXXBaseSpecifier &BS : CD->bases()) {
1978 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
1979 Value.getStructBase(BaseIndex), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001980 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001981 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00001982 }
1983 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001984 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001985 if (I->isUnnamedBitfield())
1986 continue;
1987
David Blaikie2d7c57e2012-04-30 02:36:29 +00001988 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001989 Value.getStructField(I->getFieldIndex()),
1990 Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001991 return false;
1992 }
1993 }
1994
1995 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001996 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001997 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00001998 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001999 }
2000
Reid Klecknercd016d82017-07-07 22:04:29 +00002001 if (Value.isMemberPointer())
Reid Kleckner1a840d22018-05-10 18:57:35 +00002002 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00002003
Richard Smithb228a862012-02-15 02:18:13 +00002004 // Everything else is fine.
2005 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002006}
2007
Richard Smith2e312c82012-03-03 22:46:17 +00002008static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00002009 // A null base expression indicates a null pointer. These are always
2010 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00002011 if (!Value.getLValueBase()) {
2012 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002013 return true;
2014 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002015
Richard Smith027bf112011-11-17 22:56:20 +00002016 // We have a non-null base. These are generally known to be true, but if it's
2017 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002018 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002019 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002020 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002021}
2022
Richard Smith2e312c82012-03-03 22:46:17 +00002023static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002024 switch (Val.getKind()) {
2025 case APValue::Uninitialized:
2026 return false;
2027 case APValue::Int:
2028 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002029 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00002030 case APValue::FixedPoint:
2031 Result = Val.getFixedPoint().getBoolValue();
2032 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002033 case APValue::Float:
2034 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002035 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002036 case APValue::ComplexInt:
2037 Result = Val.getComplexIntReal().getBoolValue() ||
2038 Val.getComplexIntImag().getBoolValue();
2039 return true;
2040 case APValue::ComplexFloat:
2041 Result = !Val.getComplexFloatReal().isZero() ||
2042 !Val.getComplexFloatImag().isZero();
2043 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002044 case APValue::LValue:
2045 return EvalPointerValueAsBool(Val, Result);
2046 case APValue::MemberPointer:
2047 Result = Val.getMemberPointerDecl();
2048 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002049 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002050 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002051 case APValue::Struct:
2052 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002053 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002054 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002055 }
2056
Richard Smith11562c52011-10-28 17:51:58 +00002057 llvm_unreachable("unknown APValue kind");
2058}
2059
2060static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2061 EvalInfo &Info) {
2062 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002063 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002064 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002065 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002066 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002067}
2068
Richard Smith357362d2011-12-13 06:39:58 +00002069template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002070static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002071 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002072 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002073 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002074 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002075}
2076
2077static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2078 QualType SrcType, const APFloat &Value,
2079 QualType DestType, APSInt &Result) {
2080 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002081 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002082 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002083
Richard Smith357362d2011-12-13 06:39:58 +00002084 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002085 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002086 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2087 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002088 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002089 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002090}
2091
Richard Smith357362d2011-12-13 06:39:58 +00002092static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2093 QualType SrcType, QualType DestType,
2094 APFloat &Result) {
2095 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002096 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002097 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2098 APFloat::rmNearestTiesToEven, &ignored)
2099 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002100 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002101 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002102}
2103
Richard Smith911e1422012-01-30 22:27:01 +00002104static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2105 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002106 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002107 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002108 // Figure out if this is a truncate, extend or noop cast.
2109 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002110 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002111 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002112 if (DestType->isBooleanType())
2113 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002114 return Result;
2115}
2116
Richard Smith357362d2011-12-13 06:39:58 +00002117static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2118 QualType SrcType, const APSInt &Value,
2119 QualType DestType, APFloat &Result) {
2120 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2121 if (Result.convertFromAPInt(Value, Value.isSigned(),
2122 APFloat::rmNearestTiesToEven)
2123 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002124 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002125 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002126}
2127
Richard Smith49ca8aa2013-08-06 07:09:20 +00002128static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2129 APValue &Value, const FieldDecl *FD) {
2130 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2131
2132 if (!Value.isInt()) {
2133 // Trying to store a pointer-cast-to-integer into a bitfield.
2134 // FIXME: In this case, we should provide the diagnostic for casting
2135 // a pointer to an integer.
2136 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002137 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002138 return false;
2139 }
2140
2141 APSInt &Int = Value.getInt();
2142 unsigned OldBitWidth = Int.getBitWidth();
2143 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2144 if (NewBitWidth < OldBitWidth)
2145 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2146 return true;
2147}
2148
Eli Friedman803acb32011-12-22 03:51:45 +00002149static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2150 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002151 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002152 if (!Evaluate(SVal, Info, E))
2153 return false;
2154 if (SVal.isInt()) {
2155 Res = SVal.getInt();
2156 return true;
2157 }
2158 if (SVal.isFloat()) {
2159 Res = SVal.getFloat().bitcastToAPInt();
2160 return true;
2161 }
2162 if (SVal.isVector()) {
2163 QualType VecTy = E->getType();
2164 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2165 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2166 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2167 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2168 Res = llvm::APInt::getNullValue(VecSize);
2169 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2170 APValue &Elt = SVal.getVectorElt(i);
2171 llvm::APInt EltAsInt;
2172 if (Elt.isInt()) {
2173 EltAsInt = Elt.getInt();
2174 } else if (Elt.isFloat()) {
2175 EltAsInt = Elt.getFloat().bitcastToAPInt();
2176 } else {
2177 // Don't try to handle vectors of anything other than int or float
2178 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002179 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002180 return false;
2181 }
2182 unsigned BaseEltSize = EltAsInt.getBitWidth();
2183 if (BigEndian)
2184 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2185 else
2186 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2187 }
2188 return true;
2189 }
2190 // Give up if the input isn't an int, float, or vector. For example, we
2191 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002192 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002193 return false;
2194}
2195
Richard Smith43e77732013-05-07 04:50:00 +00002196/// Perform the given integer operation, which is known to need at most BitWidth
2197/// bits, and check for overflow in the original type (if that type was not an
2198/// unsigned type).
2199template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002200static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2201 const APSInt &LHS, const APSInt &RHS,
2202 unsigned BitWidth, Operation Op,
2203 APSInt &Result) {
2204 if (LHS.isUnsigned()) {
2205 Result = Op(LHS, RHS);
2206 return true;
2207 }
Richard Smith43e77732013-05-07 04:50:00 +00002208
2209 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002210 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002211 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002212 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002213 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002214 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002215 << Result.toString(10) << E->getType();
2216 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002217 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002218 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002219 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002220}
2221
2222/// Perform the given binary integer operation.
2223static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2224 BinaryOperatorKind Opcode, APSInt RHS,
2225 APSInt &Result) {
2226 switch (Opcode) {
2227 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002228 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002229 return false;
2230 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002231 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2232 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002233 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002234 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2235 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002236 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002237 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2238 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002239 case BO_And: Result = LHS & RHS; return true;
2240 case BO_Xor: Result = LHS ^ RHS; return true;
2241 case BO_Or: Result = LHS | RHS; return true;
2242 case BO_Div:
2243 case BO_Rem:
2244 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002245 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002246 return false;
2247 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002248 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2249 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2250 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002251 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2252 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002253 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2254 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002255 return true;
2256 case BO_Shl: {
2257 if (Info.getLangOpts().OpenCL)
2258 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2259 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2260 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2261 RHS.isUnsigned());
2262 else if (RHS.isSigned() && RHS.isNegative()) {
2263 // During constant-folding, a negative shift is an opposite shift. Such
2264 // a shift is not a constant expression.
2265 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2266 RHS = -RHS;
2267 goto shift_right;
2268 }
2269 shift_left:
2270 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2271 // the shifted type.
2272 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2273 if (SA != RHS) {
2274 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2275 << RHS << E->getType() << LHS.getBitWidth();
2276 } else if (LHS.isSigned()) {
2277 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2278 // operand, and must not overflow the corresponding unsigned type.
2279 if (LHS.isNegative())
2280 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2281 else if (LHS.countLeadingZeros() < SA)
2282 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2283 }
2284 Result = LHS << SA;
2285 return true;
2286 }
2287 case BO_Shr: {
2288 if (Info.getLangOpts().OpenCL)
2289 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2290 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2291 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2292 RHS.isUnsigned());
2293 else if (RHS.isSigned() && RHS.isNegative()) {
2294 // During constant-folding, a negative shift is an opposite shift. Such a
2295 // shift is not a constant expression.
2296 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2297 RHS = -RHS;
2298 goto shift_left;
2299 }
2300 shift_right:
2301 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2302 // shifted type.
2303 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2304 if (SA != RHS)
2305 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2306 << RHS << E->getType() << LHS.getBitWidth();
2307 Result = LHS >> SA;
2308 return true;
2309 }
2310
2311 case BO_LT: Result = LHS < RHS; return true;
2312 case BO_GT: Result = LHS > RHS; return true;
2313 case BO_LE: Result = LHS <= RHS; return true;
2314 case BO_GE: Result = LHS >= RHS; return true;
2315 case BO_EQ: Result = LHS == RHS; return true;
2316 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002317 case BO_Cmp:
2318 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002319 }
2320}
2321
Richard Smith861b5b52013-05-07 23:34:45 +00002322/// Perform the given binary floating-point operation, in-place, on LHS.
2323static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2324 APFloat &LHS, BinaryOperatorKind Opcode,
2325 const APFloat &RHS) {
2326 switch (Opcode) {
2327 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002328 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002329 return false;
2330 case BO_Mul:
2331 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2332 break;
2333 case BO_Add:
2334 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2335 break;
2336 case BO_Sub:
2337 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2338 break;
2339 case BO_Div:
2340 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2341 break;
2342 }
2343
Richard Smith0c6124b2015-12-03 01:36:22 +00002344 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002345 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002346 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002347 }
Richard Smith861b5b52013-05-07 23:34:45 +00002348 return true;
2349}
2350
Richard Smitha8105bc2012-01-06 16:39:00 +00002351/// Cast an lvalue referring to a base subobject to a derived class, by
2352/// truncating the lvalue's path to the given length.
2353static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2354 const RecordDecl *TruncatedType,
2355 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002356 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002357
2358 // Check we actually point to a derived class object.
2359 if (TruncatedElements == D.Entries.size())
2360 return true;
2361 assert(TruncatedElements >= D.MostDerivedPathLength &&
2362 "not casting to a derived class");
2363 if (!Result.checkSubobject(Info, E, CSK_Derived))
2364 return false;
2365
2366 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002367 const RecordDecl *RD = TruncatedType;
2368 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002369 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002370 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2371 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002372 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002373 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002374 else
Richard Smithd62306a2011-11-10 06:34:14 +00002375 Result.Offset -= Layout.getBaseClassOffset(Base);
2376 RD = Base;
2377 }
Richard Smith027bf112011-11-17 22:56:20 +00002378 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002379 return true;
2380}
2381
John McCalld7bca762012-05-01 00:38:49 +00002382static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002383 const CXXRecordDecl *Derived,
2384 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002385 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002386 if (!RL) {
2387 if (Derived->isInvalidDecl()) return false;
2388 RL = &Info.Ctx.getASTRecordLayout(Derived);
2389 }
2390
Richard Smithd62306a2011-11-10 06:34:14 +00002391 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002392 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002393 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002394}
2395
Richard Smitha8105bc2012-01-06 16:39:00 +00002396static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002397 const CXXRecordDecl *DerivedDecl,
2398 const CXXBaseSpecifier *Base) {
2399 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2400
John McCalld7bca762012-05-01 00:38:49 +00002401 if (!Base->isVirtual())
2402 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002403
Richard Smitha8105bc2012-01-06 16:39:00 +00002404 SubobjectDesignator &D = Obj.Designator;
2405 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002406 return false;
2407
Richard Smitha8105bc2012-01-06 16:39:00 +00002408 // Extract most-derived object and corresponding type.
2409 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2410 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2411 return false;
2412
2413 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002414 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002415 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2416 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002417 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002418 return true;
2419}
2420
Richard Smith84401042013-06-03 05:03:02 +00002421static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2422 QualType Type, LValue &Result) {
2423 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2424 PathE = E->path_end();
2425 PathI != PathE; ++PathI) {
2426 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2427 *PathI))
2428 return false;
2429 Type = (*PathI)->getType();
2430 }
2431 return true;
2432}
2433
Richard Smithd62306a2011-11-10 06:34:14 +00002434/// Update LVal to refer to the given field, which must be a member of the type
2435/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002436static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002437 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002438 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002439 if (!RL) {
2440 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002441 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002442 }
Richard Smithd62306a2011-11-10 06:34:14 +00002443
2444 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002445 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002446 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002447 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002448}
2449
Richard Smith1b78b3d2012-01-25 22:15:11 +00002450/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002451static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002452 LValue &LVal,
2453 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002454 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002455 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002456 return false;
2457 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002458}
2459
Richard Smithd62306a2011-11-10 06:34:14 +00002460/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002461static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2462 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002463 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2464 // extension.
2465 if (Type->isVoidType() || Type->isFunctionType()) {
2466 Size = CharUnits::One();
2467 return true;
2468 }
2469
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002470 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002471 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002472 return false;
2473 }
2474
Richard Smithd62306a2011-11-10 06:34:14 +00002475 if (!Type->isConstantSizeType()) {
2476 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002477 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002478 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002479 return false;
2480 }
2481
2482 Size = Info.Ctx.getTypeSizeInChars(Type);
2483 return true;
2484}
2485
2486/// Update a pointer value to model pointer arithmetic.
2487/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002488/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002489/// \param LVal - The pointer value to be updated.
2490/// \param EltTy - The pointee type represented by LVal.
2491/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002492static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2493 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002494 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002495 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002496 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002497 return false;
2498
Yaxun Liu402804b2016-12-15 08:09:08 +00002499 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002500 return true;
2501}
2502
Richard Smithd6cc1982017-01-31 02:23:02 +00002503static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2504 LValue &LVal, QualType EltTy,
2505 int64_t Adjustment) {
2506 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2507 APSInt::get(Adjustment));
2508}
2509
Richard Smith66c96992012-02-18 22:04:06 +00002510/// Update an lvalue to refer to a component of a complex number.
2511/// \param Info - Information about the ongoing evaluation.
2512/// \param LVal - The lvalue to be updated.
2513/// \param EltTy - The complex number's component type.
2514/// \param Imag - False for the real component, true for the imaginary.
2515static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2516 LValue &LVal, QualType EltTy,
2517 bool Imag) {
2518 if (Imag) {
2519 CharUnits SizeOfComponent;
2520 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2521 return false;
2522 LVal.Offset += SizeOfComponent;
2523 }
2524 LVal.addComplex(Info, E, EltTy, Imag);
2525 return true;
2526}
2527
Faisal Vali051e3a22017-02-16 04:12:21 +00002528static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2529 QualType Type, const LValue &LVal,
2530 APValue &RVal);
2531
Richard Smith27908702011-10-24 17:54:18 +00002532/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002533///
2534/// \param Info Information about the ongoing evaluation.
2535/// \param E An expression to be used when printing diagnostics.
2536/// \param VD The variable whose initializer should be obtained.
2537/// \param Frame The frame in which the variable was created. Must be null
2538/// if this variable is not local to the evaluation.
2539/// \param Result Filled in with a pointer to the value of the variable.
2540static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2541 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002542 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002543
Richard Smith254a73d2011-10-28 22:34:42 +00002544 // If this is a parameter to an active constexpr function call, perform
2545 // argument substitution.
2546 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002547 // Assume arguments of a potential constant expression are unknown
2548 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002549 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002550 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002551 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002552 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002553 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002554 }
Richard Smith3229b742013-05-05 21:17:10 +00002555 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002556 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002557 }
Richard Smith27908702011-10-24 17:54:18 +00002558
Richard Smithd9f663b2013-04-22 15:31:51 +00002559 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002560 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002561 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2562 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002563 if (!Result) {
2564 // Assume variables referenced within a lambda's call operator that were
2565 // not declared within the call operator are captures and during checking
2566 // of a potential constant expression, assume they are unknown constant
2567 // expressions.
2568 assert(isLambdaCallOperator(Frame->Callee) &&
2569 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2570 "missing value for local variable");
2571 if (Info.checkingPotentialConstantExpression())
2572 return false;
2573 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002574 Info.FFDiag(E->getBeginLoc(),
2575 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002576 << "captures not currently allowed";
2577 return false;
2578 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002579 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002580 }
2581
Richard Smithd0b4dd62011-12-19 06:19:21 +00002582 // Dig out the initializer, and use the declaration which it's attached to.
2583 const Expr *Init = VD->getAnyInitializer(VD);
2584 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002585 // If we're checking a potential constant expression, the variable could be
2586 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002587 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002588 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002589 return false;
2590 }
2591
Richard Smithd62306a2011-11-10 06:34:14 +00002592 // If we're currently evaluating the initializer of this declaration, use that
2593 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002594 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002595 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002596 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002597 }
2598
Richard Smithcecf1842011-11-01 21:06:14 +00002599 // Never evaluate the initializer of a weak variable. We can't be sure that
2600 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002601 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002602 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002603 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002604 }
Richard Smithcecf1842011-11-01 21:06:14 +00002605
Richard Smithd0b4dd62011-12-19 06:19:21 +00002606 // Check that we can fold the initializer. In C++, we will have already done
2607 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002608 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002609 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002610 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002611 Notes.size() + 1) << VD;
2612 Info.Note(VD->getLocation(), diag::note_declared_at);
2613 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002614 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002615 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002616 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002617 Notes.size() + 1) << VD;
2618 Info.Note(VD->getLocation(), diag::note_declared_at);
2619 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002620 }
Richard Smith27908702011-10-24 17:54:18 +00002621
Richard Smith3229b742013-05-05 21:17:10 +00002622 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002623 return true;
Richard Smith27908702011-10-24 17:54:18 +00002624}
2625
Richard Smith11562c52011-10-28 17:51:58 +00002626static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002627 Qualifiers Quals = T.getQualifiers();
2628 return Quals.hasConst() && !Quals.hasVolatile();
2629}
2630
Richard Smithe97cbd72011-11-11 04:05:33 +00002631/// Get the base index of the given base class within an APValue representing
2632/// the given derived class.
2633static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2634 const CXXRecordDecl *Base) {
2635 Base = Base->getCanonicalDecl();
2636 unsigned Index = 0;
2637 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2638 E = Derived->bases_end(); I != E; ++I, ++Index) {
2639 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2640 return Index;
2641 }
2642
2643 llvm_unreachable("base class missing from derived class's bases list");
2644}
2645
Richard Smith3da88fa2013-04-26 14:36:30 +00002646/// Extract the value of a character from a string literal.
2647static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2648 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002649 // FIXME: Support MakeStringConstant
2650 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2651 std::string Str;
2652 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2653 assert(Index <= Str.size() && "Index too large");
2654 return APSInt::getUnsigned(Str.c_str()[Index]);
2655 }
2656
Alexey Bataevec474782014-10-09 08:45:04 +00002657 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2658 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002659 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();
Richard Smith9ec1e482012-04-15 02:50:59 +00002664 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002665
2666 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002667 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002668 if (Index < S->getLength())
2669 Value = S->getCodeUnit(Index);
2670 return Value;
2671}
2672
Richard Smith3da88fa2013-04-26 14:36:30 +00002673// Expand a string literal into an array of characters.
2674static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2675 APValue &Result) {
2676 const StringLiteral *S = cast<StringLiteral>(Lit);
2677 const ConstantArrayType *CAT =
2678 Info.Ctx.getAsConstantArrayType(S->getType());
2679 assert(CAT && "string literal isn't an array");
2680 QualType CharType = CAT->getElementType();
2681 assert(CharType->isIntegerType() && "unexpected character type");
2682
2683 unsigned Elts = CAT->getSize().getZExtValue();
2684 Result = APValue(APValue::UninitArray(),
2685 std::min(S->getLength(), Elts), Elts);
2686 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2687 CharType->isUnsignedIntegerType());
2688 if (Result.hasArrayFiller())
2689 Result.getArrayFiller() = APValue(Value);
2690 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2691 Value = S->getCodeUnit(I);
2692 Result.getArrayInitializedElt(I) = APValue(Value);
2693 }
2694}
2695
2696// Expand an array so that it has more than Index filled elements.
2697static void expandArray(APValue &Array, unsigned Index) {
2698 unsigned Size = Array.getArraySize();
2699 assert(Index < Size);
2700
2701 // Always at least double the number of elements for which we store a value.
2702 unsigned OldElts = Array.getArrayInitializedElts();
2703 unsigned NewElts = std::max(Index+1, OldElts * 2);
2704 NewElts = std::min(Size, std::max(NewElts, 8u));
2705
2706 // Copy the data across.
2707 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2708 for (unsigned I = 0; I != OldElts; ++I)
2709 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2710 for (unsigned I = OldElts; I != NewElts; ++I)
2711 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2712 if (NewValue.hasArrayFiller())
2713 NewValue.getArrayFiller() = Array.getArrayFiller();
2714 Array.swap(NewValue);
2715}
2716
Richard Smithb01fe402014-09-16 01:24:02 +00002717/// Determine whether a type would actually be read by an lvalue-to-rvalue
2718/// conversion. If it's of class type, we may assume that the copy operation
2719/// is trivial. Note that this is never true for a union type with fields
2720/// (because the copy always "reads" the active member) and always true for
2721/// a non-class type.
2722static bool isReadByLvalueToRvalueConversion(QualType T) {
2723 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2724 if (!RD || (RD->isUnion() && !RD->field_empty()))
2725 return true;
2726 if (RD->isEmpty())
2727 return false;
2728
2729 for (auto *Field : RD->fields())
2730 if (isReadByLvalueToRvalueConversion(Field->getType()))
2731 return true;
2732
2733 for (auto &BaseSpec : RD->bases())
2734 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2735 return true;
2736
2737 return false;
2738}
2739
2740/// Diagnose an attempt to read from any unreadable field within the specified
2741/// type, which might be a class type.
2742static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2743 QualType T) {
2744 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2745 if (!RD)
2746 return false;
2747
2748 if (!RD->hasMutableFields())
2749 return false;
2750
2751 for (auto *Field : RD->fields()) {
2752 // If we're actually going to read this field in some way, then it can't
2753 // be mutable. If we're in a union, then assigning to a mutable field
2754 // (even an empty one) can change the active member, so that's not OK.
2755 // FIXME: Add core issue number for the union case.
2756 if (Field->isMutable() &&
2757 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002758 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002759 Info.Note(Field->getLocation(), diag::note_declared_at);
2760 return true;
2761 }
2762
2763 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2764 return true;
2765 }
2766
2767 for (auto &BaseSpec : RD->bases())
2768 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2769 return true;
2770
2771 // All mutable fields were empty, and thus not actually read.
2772 return false;
2773}
2774
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002775namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002776/// A handle to a complete object (an object that is not a subobject of
2777/// another object).
2778struct CompleteObject {
2779 /// The value of the complete object.
2780 APValue *Value;
2781 /// The type of the complete object.
2782 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002783 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002784
Craig Topper36250ad2014-05-12 05:36:57 +00002785 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002786 CompleteObject(APValue *Value, QualType Type,
2787 bool LifetimeStartedInEvaluation)
2788 : Value(Value), Type(Type),
2789 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002790 assert(Value && "missing value for complete object");
2791 }
2792
Aaron Ballman67347662015-02-15 22:00:28 +00002793 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002794};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002795} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002796
Richard Smith3da88fa2013-04-26 14:36:30 +00002797/// Find the designated sub-object of an rvalue.
2798template<typename SubobjectHandler>
2799typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002800findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002801 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002802 if (Sub.Invalid)
2803 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002804 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002805 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002806 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002807 Info.FFDiag(E, Sub.isOnePastTheEnd()
2808 ? diag::note_constexpr_access_past_end
2809 : diag::note_constexpr_access_unsized_array)
2810 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002811 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002812 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002813 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002814 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002815
Richard Smith3229b742013-05-05 21:17:10 +00002816 APValue *O = Obj.Value;
2817 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002818 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002819 const bool MayReadMutableMembers =
2820 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002821
Richard Smithd62306a2011-11-10 06:34:14 +00002822 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002823 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2824 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002825 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002826 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002827 return handler.failed();
2828 }
2829
Richard Smith49ca8aa2013-08-06 07:09:20 +00002830 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002831 // If we are reading an object of class type, there may still be more
2832 // things we need to check: if there are any mutable subobjects, we
2833 // cannot perform this read. (This only happens when performing a trivial
2834 // copy or assignment.)
2835 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002836 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002837 return handler.failed();
2838
Richard Smith49ca8aa2013-08-06 07:09:20 +00002839 if (!handler.found(*O, ObjType))
2840 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002841
Richard Smith49ca8aa2013-08-06 07:09:20 +00002842 // If we modified a bit-field, truncate it to the right width.
2843 if (handler.AccessKind != AK_Read &&
2844 LastField && LastField->isBitField() &&
2845 !truncateBitfieldValue(Info, E, *O, LastField))
2846 return false;
2847
2848 return true;
2849 }
2850
Craig Topper36250ad2014-05-12 05:36:57 +00002851 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002852 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002853 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002854 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002855 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002856 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002857 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002858 // Note, it should not be possible to form a pointer with a valid
2859 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002860 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002861 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002862 << handler.AccessKind;
2863 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002864 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002865 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002866 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002867
2868 ObjType = CAT->getElementType();
2869
Richard Smith14a94132012-02-17 03:35:37 +00002870 // An array object is represented as either an Array APValue or as an
2871 // LValue which refers to a string literal.
2872 if (O->isLValue()) {
2873 assert(I == N - 1 && "extracting subobject of character?");
2874 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002875 if (handler.AccessKind != AK_Read)
2876 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2877 *O);
2878 else
2879 return handler.foundString(*O, ObjType, Index);
2880 }
2881
2882 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002883 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002884 else if (handler.AccessKind != AK_Read) {
2885 expandArray(*O, Index);
2886 O = &O->getArrayInitializedElt(Index);
2887 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002888 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002889 } else if (ObjType->isAnyComplexType()) {
2890 // Next subobject is a complex number.
2891 uint64_t Index = Sub.Entries[I].ArrayIndex;
2892 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002893 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002894 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002895 << handler.AccessKind;
2896 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002897 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002898 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002899 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002900
2901 bool WasConstQualified = ObjType.isConstQualified();
2902 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2903 if (WasConstQualified)
2904 ObjType.addConst();
2905
Richard Smith66c96992012-02-18 22:04:06 +00002906 assert(I == N - 1 && "extracting subobject of scalar?");
2907 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002908 return handler.found(Index ? O->getComplexIntImag()
2909 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002910 } else {
2911 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002912 return handler.found(Index ? O->getComplexFloatImag()
2913 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002914 }
Richard Smithd62306a2011-11-10 06:34:14 +00002915 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002916 // In C++14 onwards, it is permitted to read a mutable member whose
2917 // lifetime began within the evaluation.
2918 // FIXME: Should we also allow this in C++11?
2919 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2920 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002921 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002922 << Field;
2923 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002924 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002925 }
2926
Richard Smithd62306a2011-11-10 06:34:14 +00002927 // Next subobject is a class, struct or union field.
2928 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2929 if (RD->isUnion()) {
2930 const FieldDecl *UnionField = O->getUnionField();
2931 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002932 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002933 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002934 << handler.AccessKind << Field << !UnionField << UnionField;
2935 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002936 }
Richard Smithd62306a2011-11-10 06:34:14 +00002937 O = &O->getUnionValue();
2938 } else
2939 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002940
2941 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002942 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002943 if (WasConstQualified && !Field->isMutable())
2944 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002945
2946 if (ObjType.isVolatileQualified()) {
2947 if (Info.getLangOpts().CPlusPlus) {
2948 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002949 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002950 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002951 Info.Note(Field->getLocation(), diag::note_declared_at);
2952 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002953 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002954 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002955 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002956 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002957
2958 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002959 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002960 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002961 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2962 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2963 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002964
2965 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002966 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002967 if (WasConstQualified)
2968 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002969 }
2970 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002971}
2972
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002973namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002974struct ExtractSubobjectHandler {
2975 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002976 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002977
2978 static const AccessKinds AccessKind = AK_Read;
2979
2980 typedef bool result_type;
2981 bool failed() { return false; }
2982 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002983 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002984 return true;
2985 }
2986 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002987 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002988 return true;
2989 }
2990 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002991 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002992 return true;
2993 }
2994 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002995 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002996 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2997 return true;
2998 }
2999};
Richard Smith3229b742013-05-05 21:17:10 +00003000} // end anonymous namespace
3001
Richard Smith3da88fa2013-04-26 14:36:30 +00003002const AccessKinds ExtractSubobjectHandler::AccessKind;
3003
3004/// Extract the designated sub-object of an rvalue.
3005static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003006 const CompleteObject &Obj,
3007 const SubobjectDesignator &Sub,
3008 APValue &Result) {
3009 ExtractSubobjectHandler Handler = { Info, Result };
3010 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003011}
3012
Richard Smith3229b742013-05-05 21:17:10 +00003013namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003014struct ModifySubobjectHandler {
3015 EvalInfo &Info;
3016 APValue &NewVal;
3017 const Expr *E;
3018
3019 typedef bool result_type;
3020 static const AccessKinds AccessKind = AK_Assign;
3021
3022 bool checkConst(QualType QT) {
3023 // Assigning to a const object has undefined behavior.
3024 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003025 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003026 return false;
3027 }
3028 return true;
3029 }
3030
3031 bool failed() { return false; }
3032 bool found(APValue &Subobj, QualType SubobjType) {
3033 if (!checkConst(SubobjType))
3034 return false;
3035 // We've been given ownership of NewVal, so just swap it in.
3036 Subobj.swap(NewVal);
3037 return true;
3038 }
3039 bool found(APSInt &Value, QualType SubobjType) {
3040 if (!checkConst(SubobjType))
3041 return false;
3042 if (!NewVal.isInt()) {
3043 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003044 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003045 return false;
3046 }
3047 Value = NewVal.getInt();
3048 return true;
3049 }
3050 bool found(APFloat &Value, QualType SubobjType) {
3051 if (!checkConst(SubobjType))
3052 return false;
3053 Value = NewVal.getFloat();
3054 return true;
3055 }
3056 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3057 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
3058 }
3059};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003060} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003061
Richard Smith3229b742013-05-05 21:17:10 +00003062const AccessKinds ModifySubobjectHandler::AccessKind;
3063
Richard Smith3da88fa2013-04-26 14:36:30 +00003064/// Update the designated sub-object of an rvalue to the given value.
3065static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003066 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003067 const SubobjectDesignator &Sub,
3068 APValue &NewVal) {
3069 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003070 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003071}
3072
Richard Smith84f6dcf2012-02-02 01:16:57 +00003073/// Find the position where two subobject designators diverge, or equivalently
3074/// the length of the common initial subsequence.
3075static unsigned FindDesignatorMismatch(QualType ObjType,
3076 const SubobjectDesignator &A,
3077 const SubobjectDesignator &B,
3078 bool &WasArrayIndex) {
3079 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3080 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003081 if (!ObjType.isNull() &&
3082 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003083 // Next subobject is an array element.
3084 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3085 WasArrayIndex = true;
3086 return I;
3087 }
Richard Smith66c96992012-02-18 22:04:06 +00003088 if (ObjType->isAnyComplexType())
3089 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3090 else
3091 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003092 } else {
3093 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3094 WasArrayIndex = false;
3095 return I;
3096 }
3097 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3098 // Next subobject is a field.
3099 ObjType = FD->getType();
3100 else
3101 // Next subobject is a base class.
3102 ObjType = QualType();
3103 }
3104 }
3105 WasArrayIndex = false;
3106 return I;
3107}
3108
3109/// Determine whether the given subobject designators refer to elements of the
3110/// same array object.
3111static bool AreElementsOfSameArray(QualType ObjType,
3112 const SubobjectDesignator &A,
3113 const SubobjectDesignator &B) {
3114 if (A.Entries.size() != B.Entries.size())
3115 return false;
3116
George Burgess IVa51c4072015-10-16 01:49:01 +00003117 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003118 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3119 // A is a subobject of the array element.
3120 return false;
3121
3122 // If A (and B) designates an array element, the last entry will be the array
3123 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3124 // of length 1' case, and the entire path must match.
3125 bool WasArrayIndex;
3126 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3127 return CommonLength >= A.Entries.size() - IsArray;
3128}
3129
Richard Smith3229b742013-05-05 21:17:10 +00003130/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003131static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3132 AccessKinds AK, const LValue &LVal,
3133 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003134 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003135 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003136 return CompleteObject();
3137 }
3138
Craig Topper36250ad2014-05-12 05:36:57 +00003139 CallStackFrame *Frame = nullptr;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003140 if (LVal.getLValueCallIndex()) {
3141 Frame = Info.getCallFrame(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003142 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003143 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003144 << AK << LVal.Base.is<const ValueDecl*>();
3145 NoteLValueLocation(Info, LVal.Base);
3146 return CompleteObject();
3147 }
Richard Smith3229b742013-05-05 21:17:10 +00003148 }
3149
3150 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3151 // is not a constant expression (even if the object is non-volatile). We also
3152 // apply this rule to C++98, in order to conform to the expected 'volatile'
3153 // semantics.
3154 if (LValType.isVolatileQualified()) {
3155 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003156 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003157 << AK << LValType;
3158 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003159 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003160 return CompleteObject();
3161 }
3162
3163 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003164 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003165 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003166 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003167
3168 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3169 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3170 // In C++11, constexpr, non-volatile variables initialized with constant
3171 // expressions are constant expressions too. Inside constexpr functions,
3172 // parameters are constant expressions even if they're non-const.
3173 // In C++1y, objects local to a constant expression (those with a Frame) are
3174 // both readable and writable inside constant expressions.
3175 // In C, such things can also be folded, although they are not ICEs.
3176 const VarDecl *VD = dyn_cast<VarDecl>(D);
3177 if (VD) {
3178 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3179 VD = VDef;
3180 }
3181 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003182 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003183 return CompleteObject();
3184 }
3185
3186 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003187 if (BaseType.isVolatileQualified()) {
3188 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003189 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003190 << AK << 1 << VD;
3191 Info.Note(VD->getLocation(), diag::note_declared_at);
3192 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003193 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003194 }
3195 return CompleteObject();
3196 }
3197
3198 // Unless we're looking at a local variable or argument in a constexpr call,
3199 // the variable we're reading must be const.
3200 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003201 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003202 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3203 // OK, we can read and modify an object if we're in the process of
3204 // evaluating its initializer, because its lifetime began in this
3205 // evaluation.
3206 } else if (AK != AK_Read) {
3207 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003208 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003209 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003210 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003211 // OK, we can read this variable.
3212 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003213 // In OpenCL if a variable is in constant address space it is a const value.
3214 if (!(BaseType.isConstQualified() ||
3215 (Info.getLangOpts().OpenCL &&
3216 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003217 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003218 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003219 Info.Note(VD->getLocation(), diag::note_declared_at);
3220 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003221 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003222 }
3223 return CompleteObject();
3224 }
3225 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3226 // We support folding of const floating-point types, in order to make
3227 // static const data members of such types (supported as an extension)
3228 // more useful.
3229 if (Info.getLangOpts().CPlusPlus11) {
3230 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3231 Info.Note(VD->getLocation(), diag::note_declared_at);
3232 } else {
3233 Info.CCEDiag(E);
3234 }
George Burgess IVb5316982016-12-27 05:33:20 +00003235 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3236 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3237 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003238 } else {
3239 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003240 if (Info.checkingPotentialConstantExpression() &&
3241 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3242 // The definition of this variable could be constexpr. We can't
3243 // access it right now, but may be able to in future.
3244 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003245 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003246 Info.Note(VD->getLocation(), diag::note_declared_at);
3247 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003248 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003249 }
3250 return CompleteObject();
3251 }
3252 }
3253
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003254 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003255 return CompleteObject();
3256 } else {
3257 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3258
3259 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003260 if (const MaterializeTemporaryExpr *MTE =
3261 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3262 assert(MTE->getStorageDuration() == SD_Static &&
3263 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003264
Richard Smithe6c01442013-06-05 00:46:14 +00003265 // Per C++1y [expr.const]p2:
3266 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3267 // - a [...] glvalue of integral or enumeration type that refers to
3268 // a non-volatile const object [...]
3269 // [...]
3270 // - a [...] glvalue of literal type that refers to a non-volatile
3271 // object whose lifetime began within the evaluation of e.
3272 //
3273 // C++11 misses the 'began within the evaluation of e' check and
3274 // instead allows all temporaries, including things like:
3275 // int &&r = 1;
3276 // int x = ++r;
3277 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003278 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003279 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3280 const ValueDecl *ED = MTE->getExtendingDecl();
3281 if (!(BaseType.isConstQualified() &&
3282 BaseType->isIntegralOrEnumerationType()) &&
3283 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003284 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003285 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3286 return CompleteObject();
3287 }
3288
3289 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3290 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003291 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003292 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003293 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003294 return CompleteObject();
3295 }
3296 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003297 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003298 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003299 }
Richard Smith3229b742013-05-05 21:17:10 +00003300
3301 // Volatile temporary objects cannot be accessed in constant expressions.
3302 if (BaseType.isVolatileQualified()) {
3303 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003304 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003305 << AK << 0;
3306 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3307 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003308 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003309 }
3310 return CompleteObject();
3311 }
3312 }
3313
Richard Smith7525ff62013-05-09 07:14:00 +00003314 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003315 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003316 // object under construction.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003317 if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3318 LVal.getLValueCallIndex(),
3319 LVal.getLValueVersion())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003320 BaseType = Info.Ctx.getCanonicalType(BaseType);
3321 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003322 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003323 }
3324
Richard Smith9defb7d2018-02-21 03:38:30 +00003325 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003326 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003327 //
3328 // FIXME: Not all local state is mutable. Allow local constant subobjects
3329 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003330 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3331 Info.EvalStatus.HasSideEffects) ||
3332 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003333 return CompleteObject();
3334
Richard Smith9defb7d2018-02-21 03:38:30 +00003335 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003336}
3337
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003338/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003339/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3340/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003341///
3342/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003343/// \param Conv - The expression for which we are performing the conversion.
3344/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003345/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3346/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003347/// \param LVal - The glvalue on which we are attempting to perform this action.
3348/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003349static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003350 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003351 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003352 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003353 return false;
3354
Richard Smith3229b742013-05-05 21:17:10 +00003355 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003356 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003357 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003358 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3359 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3360 // initializer until now for such expressions. Such an expression can't be
3361 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003362 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003363 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003364 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003365 }
Richard Smith3229b742013-05-05 21:17:10 +00003366 APValue Lit;
3367 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3368 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003369 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003370 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003371 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003372 // We represent a string literal array as an lvalue pointing at the
3373 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003374 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003375 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smith9defb7d2018-02-21 03:38:30 +00003376 CompleteObject StrObj(&Str, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003377 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003378 }
Richard Smith11562c52011-10-28 17:51:58 +00003379 }
3380
Richard Smith3229b742013-05-05 21:17:10 +00003381 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3382 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003383}
3384
3385/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003386static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003387 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003388 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003389 return false;
3390
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003391 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003392 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003393 return false;
3394 }
3395
Richard Smith3229b742013-05-05 21:17:10 +00003396 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003397 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3398}
3399
3400namespace {
3401struct CompoundAssignSubobjectHandler {
3402 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003403 const Expr *E;
3404 QualType PromotedLHSType;
3405 BinaryOperatorKind Opcode;
3406 const APValue &RHS;
3407
3408 static const AccessKinds AccessKind = AK_Assign;
3409
3410 typedef bool result_type;
3411
3412 bool checkConst(QualType QT) {
3413 // Assigning to a const object has undefined behavior.
3414 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003415 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003416 return false;
3417 }
3418 return true;
3419 }
3420
3421 bool failed() { return false; }
3422 bool found(APValue &Subobj, QualType SubobjType) {
3423 switch (Subobj.getKind()) {
3424 case APValue::Int:
3425 return found(Subobj.getInt(), SubobjType);
3426 case APValue::Float:
3427 return found(Subobj.getFloat(), SubobjType);
3428 case APValue::ComplexInt:
3429 case APValue::ComplexFloat:
3430 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003431 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003432 return false;
3433 case APValue::LValue:
3434 return foundPointer(Subobj, SubobjType);
3435 default:
3436 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003437 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003438 return false;
3439 }
3440 }
3441 bool found(APSInt &Value, QualType SubobjType) {
3442 if (!checkConst(SubobjType))
3443 return false;
3444
Tan S. B.9f935e82018-12-18 07:38:06 +00003445 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003446 // We don't support compound assignment on integer-cast-to-pointer
3447 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003448 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003449 return false;
3450 }
3451
Tan S. B.9f935e82018-12-18 07:38:06 +00003452 if (RHS.isInt()) {
3453 APSInt LHS =
3454 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3455 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3456 return false;
3457 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3458 return true;
3459 } else if (RHS.isFloat()) {
3460 APFloat FValue(0.0);
3461 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3462 FValue) &&
3463 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3464 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3465 Value);
3466 }
3467
3468 Info.FFDiag(E);
3469 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003470 }
3471 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003472 return checkConst(SubobjType) &&
3473 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3474 Value) &&
3475 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3476 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003477 }
3478 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3479 if (!checkConst(SubobjType))
3480 return false;
3481
3482 QualType PointeeType;
3483 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3484 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003485
3486 if (PointeeType.isNull() || !RHS.isInt() ||
3487 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003488 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003489 return false;
3490 }
3491
Richard Smithd6cc1982017-01-31 02:23:02 +00003492 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003493 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003494 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003495
3496 LValue LVal;
3497 LVal.setFrom(Info.Ctx, Subobj);
3498 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3499 return false;
3500 LVal.moveInto(Subobj);
3501 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003502 }
3503 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3504 llvm_unreachable("shouldn't encounter string elements here");
3505 }
3506};
3507} // end anonymous namespace
3508
3509const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3510
3511/// Perform a compound assignment of LVal <op>= RVal.
3512static bool handleCompoundAssignment(
3513 EvalInfo &Info, const Expr *E,
3514 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3515 BinaryOperatorKind Opcode, const APValue &RVal) {
3516 if (LVal.Designator.Invalid)
3517 return false;
3518
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003519 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003520 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003521 return false;
3522 }
3523
3524 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3525 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3526 RVal };
3527 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3528}
3529
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003530namespace {
3531struct IncDecSubobjectHandler {
3532 EvalInfo &Info;
3533 const UnaryOperator *E;
3534 AccessKinds AccessKind;
3535 APValue *Old;
3536
Richard Smith243ef902013-05-05 23:31:59 +00003537 typedef bool result_type;
3538
3539 bool checkConst(QualType QT) {
3540 // Assigning to a const object has undefined behavior.
3541 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003542 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003543 return false;
3544 }
3545 return true;
3546 }
3547
3548 bool failed() { return false; }
3549 bool found(APValue &Subobj, QualType SubobjType) {
3550 // Stash the old value. Also clear Old, so we don't clobber it later
3551 // if we're post-incrementing a complex.
3552 if (Old) {
3553 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003554 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003555 }
3556
3557 switch (Subobj.getKind()) {
3558 case APValue::Int:
3559 return found(Subobj.getInt(), SubobjType);
3560 case APValue::Float:
3561 return found(Subobj.getFloat(), SubobjType);
3562 case APValue::ComplexInt:
3563 return found(Subobj.getComplexIntReal(),
3564 SubobjType->castAs<ComplexType>()->getElementType()
3565 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3566 case APValue::ComplexFloat:
3567 return found(Subobj.getComplexFloatReal(),
3568 SubobjType->castAs<ComplexType>()->getElementType()
3569 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3570 case APValue::LValue:
3571 return foundPointer(Subobj, SubobjType);
3572 default:
3573 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003574 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003575 return false;
3576 }
3577 }
3578 bool found(APSInt &Value, QualType SubobjType) {
3579 if (!checkConst(SubobjType))
3580 return false;
3581
3582 if (!SubobjType->isIntegerType()) {
3583 // We don't support increment / decrement on integer-cast-to-pointer
3584 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003585 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003586 return false;
3587 }
3588
3589 if (Old) *Old = APValue(Value);
3590
3591 // bool arithmetic promotes to int, and the conversion back to bool
3592 // doesn't reduce mod 2^n, so special-case it.
3593 if (SubobjType->isBooleanType()) {
3594 if (AccessKind == AK_Increment)
3595 Value = 1;
3596 else
3597 Value = !Value;
3598 return true;
3599 }
3600
3601 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003602 if (AccessKind == AK_Increment) {
3603 ++Value;
3604
3605 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3606 APSInt ActualValue(Value, /*IsUnsigned*/true);
3607 return HandleOverflow(Info, E, ActualValue, SubobjType);
3608 }
3609 } else {
3610 --Value;
3611
3612 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3613 unsigned BitWidth = Value.getBitWidth();
3614 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3615 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003616 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003617 }
3618 }
3619 return true;
3620 }
3621 bool found(APFloat &Value, QualType SubobjType) {
3622 if (!checkConst(SubobjType))
3623 return false;
3624
3625 if (Old) *Old = APValue(Value);
3626
3627 APFloat One(Value.getSemantics(), 1);
3628 if (AccessKind == AK_Increment)
3629 Value.add(One, APFloat::rmNearestTiesToEven);
3630 else
3631 Value.subtract(One, APFloat::rmNearestTiesToEven);
3632 return true;
3633 }
3634 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3635 if (!checkConst(SubobjType))
3636 return false;
3637
3638 QualType PointeeType;
3639 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3640 PointeeType = PT->getPointeeType();
3641 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003642 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003643 return false;
3644 }
3645
3646 LValue LVal;
3647 LVal.setFrom(Info.Ctx, Subobj);
3648 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3649 AccessKind == AK_Increment ? 1 : -1))
3650 return false;
3651 LVal.moveInto(Subobj);
3652 return true;
3653 }
3654 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3655 llvm_unreachable("shouldn't encounter string elements here");
3656 }
3657};
3658} // end anonymous namespace
3659
3660/// Perform an increment or decrement on LVal.
3661static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3662 QualType LValType, bool IsIncrement, APValue *Old) {
3663 if (LVal.Designator.Invalid)
3664 return false;
3665
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003666 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003667 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003668 return false;
3669 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003670
3671 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3672 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3673 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3674 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3675}
3676
Richard Smithe97cbd72011-11-11 04:05:33 +00003677/// Build an lvalue for the object argument of a member function call.
3678static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3679 LValue &This) {
3680 if (Object->getType()->isPointerType())
3681 return EvaluatePointer(Object, This, Info);
3682
3683 if (Object->isGLValue())
3684 return EvaluateLValue(Object, This, Info);
3685
Richard Smithd9f663b2013-04-22 15:31:51 +00003686 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003687 return EvaluateTemporary(Object, This, Info);
3688
Faisal Valie690b7a2016-07-02 22:34:24 +00003689 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003690 return false;
3691}
3692
3693/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3694/// lvalue referring to the result.
3695///
3696/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003697/// \param LV - An lvalue referring to the base of the member pointer.
3698/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003699/// \param IncludeMember - Specifies whether the member itself is included in
3700/// the resulting LValue subobject designator. This is not possible when
3701/// creating a bound member function.
3702/// \return The field or method declaration to which the member pointer refers,
3703/// or 0 if evaluation fails.
3704static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003705 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003706 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003707 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003708 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003709 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003710 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003711 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003712
3713 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3714 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003715 if (!MemPtr.getDecl()) {
3716 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003717 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003718 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003719 }
Richard Smith253c2a32012-01-27 01:14:48 +00003720
Richard Smith027bf112011-11-17 22:56:20 +00003721 if (MemPtr.isDerivedMember()) {
3722 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003723 // The end of the derived-to-base path for the base object must match the
3724 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003725 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003726 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003727 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003728 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003729 }
Richard Smith027bf112011-11-17 22:56:20 +00003730 unsigned PathLengthToMember =
3731 LV.Designator.Entries.size() - MemPtr.Path.size();
3732 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3733 const CXXRecordDecl *LVDecl = getAsBaseClass(
3734 LV.Designator.Entries[PathLengthToMember + I]);
3735 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003736 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003737 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003738 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003739 }
Richard Smith027bf112011-11-17 22:56:20 +00003740 }
3741
3742 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003743 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003744 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003745 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003746 } else if (!MemPtr.Path.empty()) {
3747 // Extend the LValue path with the member pointer's path.
3748 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3749 MemPtr.Path.size() + IncludeMember);
3750
3751 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003752 if (const PointerType *PT = LVType->getAs<PointerType>())
3753 LVType = PT->getPointeeType();
3754 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3755 assert(RD && "member pointer access on non-class-type expression");
3756 // The first class in the path is that of the lvalue.
3757 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3758 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003759 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003760 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003761 RD = Base;
3762 }
3763 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003764 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3765 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003766 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003767 }
3768
3769 // Add the member. Note that we cannot build bound member functions here.
3770 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003771 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003772 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003773 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003774 } else if (const IndirectFieldDecl *IFD =
3775 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003776 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003777 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003778 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003779 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003780 }
Richard Smith027bf112011-11-17 22:56:20 +00003781 }
3782
3783 return MemPtr.getDecl();
3784}
3785
Richard Smith84401042013-06-03 05:03:02 +00003786static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3787 const BinaryOperator *BO,
3788 LValue &LV,
3789 bool IncludeMember = true) {
3790 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3791
3792 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003793 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003794 MemberPtr MemPtr;
3795 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3796 }
Craig Topper36250ad2014-05-12 05:36:57 +00003797 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003798 }
3799
3800 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3801 BO->getRHS(), IncludeMember);
3802}
3803
Richard Smith027bf112011-11-17 22:56:20 +00003804/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3805/// the provided lvalue, which currently refers to the base object.
3806static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3807 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003808 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003809 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003810 return false;
3811
Richard Smitha8105bc2012-01-06 16:39:00 +00003812 QualType TargetQT = E->getType();
3813 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3814 TargetQT = PT->getPointeeType();
3815
3816 // Check this cast lands within the final derived-to-base subobject path.
3817 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003818 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003819 << D.MostDerivedType << TargetQT;
3820 return false;
3821 }
3822
Richard Smith027bf112011-11-17 22:56:20 +00003823 // Check the type of the final cast. We don't need to check the path,
3824 // since a cast can only be formed if the path is unique.
3825 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003826 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3827 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003828 if (NewEntriesSize == D.MostDerivedPathLength)
3829 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3830 else
Richard Smith027bf112011-11-17 22:56:20 +00003831 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003832 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003833 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003834 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003835 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003836 }
Richard Smith027bf112011-11-17 22:56:20 +00003837
3838 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003839 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003840}
3841
Mike Stump876387b2009-10-27 22:09:17 +00003842namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003843enum EvalStmtResult {
3844 /// Evaluation failed.
3845 ESR_Failed,
3846 /// Hit a 'return' statement.
3847 ESR_Returned,
3848 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003849 ESR_Succeeded,
3850 /// Hit a 'continue' statement.
3851 ESR_Continue,
3852 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003853 ESR_Break,
3854 /// Still scanning for 'case' or 'default' statement.
3855 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003856};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003857}
Richard Smith254a73d2011-10-28 22:34:42 +00003858
Richard Smith97fcf4b2016-08-14 23:15:52 +00003859static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3860 // We don't need to evaluate the initializer for a static local.
3861 if (!VD->hasLocalStorage())
3862 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003863
Richard Smith97fcf4b2016-08-14 23:15:52 +00003864 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003865 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00003866
Richard Smith97fcf4b2016-08-14 23:15:52 +00003867 const Expr *InitE = VD->getInit();
3868 if (!InitE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003869 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
3870 << false << VD->getType();
Richard Smith97fcf4b2016-08-14 23:15:52 +00003871 Val = APValue();
3872 return false;
3873 }
Richard Smith51f03172013-06-20 03:00:05 +00003874
Richard Smith97fcf4b2016-08-14 23:15:52 +00003875 if (InitE->isValueDependent())
3876 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003877
Richard Smith97fcf4b2016-08-14 23:15:52 +00003878 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3879 // Wipe out any partially-computed value, to allow tracking that this
3880 // evaluation failed.
3881 Val = APValue();
3882 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003883 }
3884
3885 return true;
3886}
3887
Richard Smith97fcf4b2016-08-14 23:15:52 +00003888static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3889 bool OK = true;
3890
3891 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3892 OK &= EvaluateVarDecl(Info, VD);
3893
3894 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3895 for (auto *BD : DD->bindings())
3896 if (auto *VD = BD->getHoldingVar())
3897 OK &= EvaluateDecl(Info, VD);
3898
3899 return OK;
3900}
3901
3902
Richard Smith4e18ca52013-05-06 05:56:11 +00003903/// Evaluate a condition (either a variable declaration or an expression).
3904static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3905 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003906 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003907 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3908 return false;
3909 return EvaluateAsBooleanCondition(Cond, Result, Info);
3910}
3911
Richard Smith89210072016-04-04 23:29:43 +00003912namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003913/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00003914/// statement should be stored.
3915struct StmtResult {
3916 /// The APValue that should be filled in with the returned value.
3917 APValue &Value;
3918 /// The location containing the result, if any (used to support RVO).
3919 const LValue *Slot;
3920};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003921
3922struct TempVersionRAII {
3923 CallStackFrame &Frame;
3924
3925 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3926 Frame.pushTempVersion();
3927 }
3928
3929 ~TempVersionRAII() {
3930 Frame.popTempVersion();
3931 }
3932};
3933
Richard Smith89210072016-04-04 23:29:43 +00003934}
Richard Smith52a980a2015-08-28 02:43:42 +00003935
3936static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003937 const Stmt *S,
3938 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003939
3940/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003941static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003942 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003943 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003944 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003945 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003946 case ESR_Break:
3947 return ESR_Succeeded;
3948 case ESR_Succeeded:
3949 case ESR_Continue:
3950 return ESR_Continue;
3951 case ESR_Failed:
3952 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003953 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003954 return ESR;
3955 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003956 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003957}
3958
Richard Smith496ddcf2013-05-12 17:32:42 +00003959/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003960static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003961 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003962 BlockScopeRAII Scope(Info);
3963
Richard Smith496ddcf2013-05-12 17:32:42 +00003964 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003965 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003966 {
3967 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003968 if (const Stmt *Init = SS->getInit()) {
3969 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3970 if (ESR != ESR_Succeeded)
3971 return ESR;
3972 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003973 if (SS->getConditionVariable() &&
3974 !EvaluateDecl(Info, SS->getConditionVariable()))
3975 return ESR_Failed;
3976 if (!EvaluateInteger(SS->getCond(), Value, Info))
3977 return ESR_Failed;
3978 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003979
3980 // Find the switch case corresponding to the value of the condition.
3981 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003982 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003983 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3984 SC = SC->getNextSwitchCase()) {
3985 if (isa<DefaultStmt>(SC)) {
3986 Found = SC;
3987 continue;
3988 }
3989
3990 const CaseStmt *CS = cast<CaseStmt>(SC);
3991 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3992 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3993 : LHS;
3994 if (LHS <= Value && Value <= RHS) {
3995 Found = SC;
3996 break;
3997 }
3998 }
3999
4000 if (!Found)
4001 return ESR_Succeeded;
4002
4003 // Search the switch body for the switch case and evaluate it from there.
4004 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4005 case ESR_Break:
4006 return ESR_Succeeded;
4007 case ESR_Succeeded:
4008 case ESR_Continue:
4009 case ESR_Failed:
4010 case ESR_Returned:
4011 return ESR;
4012 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004013 // This can only happen if the switch case is nested within a statement
4014 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004015 Info.FFDiag(Found->getBeginLoc(),
4016 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004017 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004018 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004019 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004020}
4021
Richard Smith254a73d2011-10-28 22:34:42 +00004022// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004023static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004024 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004025 if (!Info.nextStep(S))
4026 return ESR_Failed;
4027
Richard Smith496ddcf2013-05-12 17:32:42 +00004028 // If we're hunting down a 'case' or 'default' label, recurse through
4029 // substatements until we hit the label.
4030 if (Case) {
4031 // FIXME: We don't start the lifetime of objects whose initialization we
4032 // jump over. However, such objects must be of class type with a trivial
4033 // default constructor that initialize all subobjects, so must be empty,
4034 // so this almost never matters.
4035 switch (S->getStmtClass()) {
4036 case Stmt::CompoundStmtClass:
4037 // FIXME: Precompute which substatement of a compound statement we
4038 // would jump to, and go straight there rather than performing a
4039 // linear scan each time.
4040 case Stmt::LabelStmtClass:
4041 case Stmt::AttributedStmtClass:
4042 case Stmt::DoStmtClass:
4043 break;
4044
4045 case Stmt::CaseStmtClass:
4046 case Stmt::DefaultStmtClass:
4047 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004048 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004049 break;
4050
4051 case Stmt::IfStmtClass: {
4052 // FIXME: Precompute which side of an 'if' we would jump to, and go
4053 // straight there rather than scanning both sides.
4054 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004055
4056 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4057 // preceded by our switch label.
4058 BlockScopeRAII Scope(Info);
4059
Richard Smith496ddcf2013-05-12 17:32:42 +00004060 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4061 if (ESR != ESR_CaseNotFound || !IS->getElse())
4062 return ESR;
4063 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4064 }
4065
4066 case Stmt::WhileStmtClass: {
4067 EvalStmtResult ESR =
4068 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4069 if (ESR != ESR_Continue)
4070 return ESR;
4071 break;
4072 }
4073
4074 case Stmt::ForStmtClass: {
4075 const ForStmt *FS = cast<ForStmt>(S);
4076 EvalStmtResult ESR =
4077 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4078 if (ESR != ESR_Continue)
4079 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004080 if (FS->getInc()) {
4081 FullExpressionRAII IncScope(Info);
4082 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4083 return ESR_Failed;
4084 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004085 break;
4086 }
4087
4088 case Stmt::DeclStmtClass:
4089 // FIXME: If the variable has initialization that can't be jumped over,
4090 // bail out of any immediately-surrounding compound-statement too.
4091 default:
4092 return ESR_CaseNotFound;
4093 }
4094 }
4095
Richard Smith254a73d2011-10-28 22:34:42 +00004096 switch (S->getStmtClass()) {
4097 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004098 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004099 // Don't bother evaluating beyond an expression-statement which couldn't
4100 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004101 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004102 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004103 return ESR_Failed;
4104 return ESR_Succeeded;
4105 }
4106
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004107 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004108 return ESR_Failed;
4109
4110 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004111 return ESR_Succeeded;
4112
Richard Smithd9f663b2013-04-22 15:31:51 +00004113 case Stmt::DeclStmtClass: {
4114 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004115 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004116 // Each declaration initialization is its own full-expression.
4117 // FIXME: This isn't quite right; if we're performing aggregate
4118 // initialization, each braced subexpression is its own full-expression.
4119 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004120 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004121 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004122 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004123 return ESR_Succeeded;
4124 }
4125
Richard Smith357362d2011-12-13 06:39:58 +00004126 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004127 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004128 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004129 if (RetExpr &&
4130 !(Result.Slot
4131 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4132 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004133 return ESR_Failed;
4134 return ESR_Returned;
4135 }
Richard Smith254a73d2011-10-28 22:34:42 +00004136
4137 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004138 BlockScopeRAII Scope(Info);
4139
Richard Smith254a73d2011-10-28 22:34:42 +00004140 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004141 for (const auto *BI : CS->body()) {
4142 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004143 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004144 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004145 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004146 return ESR;
4147 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004148 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004149 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004150
4151 case Stmt::IfStmtClass: {
4152 const IfStmt *IS = cast<IfStmt>(S);
4153
4154 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004155 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004156 if (const Stmt *Init = IS->getInit()) {
4157 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4158 if (ESR != ESR_Succeeded)
4159 return ESR;
4160 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004161 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004162 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004163 return ESR_Failed;
4164
4165 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4166 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4167 if (ESR != ESR_Succeeded)
4168 return ESR;
4169 }
4170 return ESR_Succeeded;
4171 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004172
4173 case Stmt::WhileStmtClass: {
4174 const WhileStmt *WS = cast<WhileStmt>(S);
4175 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004176 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004177 bool Continue;
4178 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4179 Continue))
4180 return ESR_Failed;
4181 if (!Continue)
4182 break;
4183
4184 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4185 if (ESR != ESR_Continue)
4186 return ESR;
4187 }
4188 return ESR_Succeeded;
4189 }
4190
4191 case Stmt::DoStmtClass: {
4192 const DoStmt *DS = cast<DoStmt>(S);
4193 bool Continue;
4194 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004195 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004196 if (ESR != ESR_Continue)
4197 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004198 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004199
Richard Smith08d6a2c2013-07-24 07:11:57 +00004200 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004201 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4202 return ESR_Failed;
4203 } while (Continue);
4204 return ESR_Succeeded;
4205 }
4206
4207 case Stmt::ForStmtClass: {
4208 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004209 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004210 if (FS->getInit()) {
4211 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4212 if (ESR != ESR_Succeeded)
4213 return ESR;
4214 }
4215 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004216 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004217 bool Continue = true;
4218 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4219 FS->getCond(), Continue))
4220 return ESR_Failed;
4221 if (!Continue)
4222 break;
4223
4224 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4225 if (ESR != ESR_Continue)
4226 return ESR;
4227
Richard Smith08d6a2c2013-07-24 07:11:57 +00004228 if (FS->getInc()) {
4229 FullExpressionRAII IncScope(Info);
4230 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4231 return ESR_Failed;
4232 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004233 }
4234 return ESR_Succeeded;
4235 }
4236
Richard Smith896e0d72013-05-06 06:51:17 +00004237 case Stmt::CXXForRangeStmtClass: {
4238 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004239 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004240
Richard Smith8baa5002018-09-28 18:44:09 +00004241 // Evaluate the init-statement if present.
4242 if (FS->getInit()) {
4243 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4244 if (ESR != ESR_Succeeded)
4245 return ESR;
4246 }
4247
Richard Smith896e0d72013-05-06 06:51:17 +00004248 // Initialize the __range variable.
4249 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4250 if (ESR != ESR_Succeeded)
4251 return ESR;
4252
4253 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004254 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4255 if (ESR != ESR_Succeeded)
4256 return ESR;
4257 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004258 if (ESR != ESR_Succeeded)
4259 return ESR;
4260
4261 while (true) {
4262 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004263 {
4264 bool Continue = true;
4265 FullExpressionRAII CondExpr(Info);
4266 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4267 return ESR_Failed;
4268 if (!Continue)
4269 break;
4270 }
Richard Smith896e0d72013-05-06 06:51:17 +00004271
4272 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004273 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004274 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4275 if (ESR != ESR_Succeeded)
4276 return ESR;
4277
4278 // Loop body.
4279 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4280 if (ESR != ESR_Continue)
4281 return ESR;
4282
4283 // Increment: ++__begin
4284 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4285 return ESR_Failed;
4286 }
4287
4288 return ESR_Succeeded;
4289 }
4290
Richard Smith496ddcf2013-05-12 17:32:42 +00004291 case Stmt::SwitchStmtClass:
4292 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4293
Richard Smith4e18ca52013-05-06 05:56:11 +00004294 case Stmt::ContinueStmtClass:
4295 return ESR_Continue;
4296
4297 case Stmt::BreakStmtClass:
4298 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004299
4300 case Stmt::LabelStmtClass:
4301 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4302
4303 case Stmt::AttributedStmtClass:
4304 // As a general principle, C++11 attributes can be ignored without
4305 // any semantic impact.
4306 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4307 Case);
4308
4309 case Stmt::CaseStmtClass:
4310 case Stmt::DefaultStmtClass:
4311 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004312 case Stmt::CXXTryStmtClass:
4313 // Evaluate try blocks by evaluating all sub statements.
4314 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004315 }
4316}
4317
Richard Smithcc36f692011-12-22 02:22:31 +00004318/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4319/// default constructor. If so, we'll fold it whether or not it's marked as
4320/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4321/// so we need special handling.
4322static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004323 const CXXConstructorDecl *CD,
4324 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004325 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4326 return false;
4327
Richard Smith66e05fe2012-01-18 05:21:49 +00004328 // Value-initialization does not call a trivial default constructor, so such a
4329 // call is a core constant expression whether or not the constructor is
4330 // constexpr.
4331 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004332 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004333 // FIXME: If DiagDecl is an implicitly-declared special member function,
4334 // we should be much more explicit about why it's not constexpr.
4335 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4336 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4337 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004338 } else {
4339 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4340 }
4341 }
4342 return true;
4343}
4344
Richard Smith357362d2011-12-13 06:39:58 +00004345/// CheckConstexprFunction - Check that a function can be called in a constant
4346/// expression.
4347static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4348 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004349 const FunctionDecl *Definition,
4350 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004351 // Potential constant expressions can contain calls to declared, but not yet
4352 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004353 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004354 Declaration->isConstexpr())
4355 return false;
4356
James Y Knightc7d3e602018-10-05 17:49:48 +00004357 // Bail out if the function declaration itself is invalid. We will
4358 // have produced a relevant diagnostic while parsing it, so just
4359 // note the problematic sub-expression.
4360 if (Declaration->isInvalidDecl()) {
4361 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004362 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004363 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004364
Richard Smith357362d2011-12-13 06:39:58 +00004365 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004366 if (Definition && Definition->isConstexpr() &&
4367 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004368 return true;
4369
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004370 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004371 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004372
Richard Smith5179eb72016-06-28 19:03:57 +00004373 // If this function is not constexpr because it is an inherited
4374 // non-constexpr constructor, diagnose that directly.
4375 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4376 if (CD && CD->isInheritingConstructor()) {
4377 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004378 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004379 DiagDecl = CD = Inherited;
4380 }
4381
4382 // FIXME: If DiagDecl is an implicitly-declared special member function
4383 // or an inheriting constructor, we should be much more explicit about why
4384 // it's not constexpr.
4385 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004386 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004387 << CD->getInheritedConstructor().getConstructor()->getParent();
4388 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004389 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004390 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004391 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4392 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004393 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004394 }
4395 return false;
4396}
4397
Richard Smithbe6dd812014-11-19 21:27:17 +00004398/// Determine if a class has any fields that might need to be copied by a
4399/// trivial copy or move operation.
4400static bool hasFields(const CXXRecordDecl *RD) {
4401 if (!RD || RD->isEmpty())
4402 return false;
4403 for (auto *FD : RD->fields()) {
4404 if (FD->isUnnamedBitfield())
4405 continue;
4406 return true;
4407 }
4408 for (auto &Base : RD->bases())
4409 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4410 return true;
4411 return false;
4412}
4413
Richard Smithd62306a2011-11-10 06:34:14 +00004414namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004415typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004416}
4417
4418/// EvaluateArgs - Evaluate the arguments to a function call.
4419static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4420 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004421 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004422 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004423 I != E; ++I) {
4424 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4425 // If we're checking for a potential constant expression, evaluate all
4426 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004427 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004428 return false;
4429 Success = false;
4430 }
4431 }
4432 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004433}
4434
Richard Smith254a73d2011-10-28 22:34:42 +00004435/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004436static bool HandleFunctionCall(SourceLocation CallLoc,
4437 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004438 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004439 EvalInfo &Info, APValue &Result,
4440 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004441 ArgVector ArgValues(Args.size());
4442 if (!EvaluateArgs(Args, ArgValues, Info))
4443 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004444
Richard Smith253c2a32012-01-27 01:14:48 +00004445 if (!Info.CheckCallLimit(CallLoc))
4446 return false;
4447
4448 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004449
4450 // For a trivial copy or move assignment, perform an APValue copy. This is
4451 // essential for unions, where the operations performed by the assignment
4452 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004453 //
4454 // Skip this for non-union classes with no fields; in that case, the defaulted
4455 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004456 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004457 if (MD && MD->isDefaulted() &&
4458 (MD->getParent()->isUnion() ||
4459 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004460 assert(This &&
4461 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4462 LValue RHS;
4463 RHS.setFrom(Info.Ctx, ArgValues[0]);
4464 APValue RHSValue;
4465 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4466 RHS, RHSValue))
4467 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00004468 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00004469 RHSValue))
4470 return false;
4471 This->moveInto(Result);
4472 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004473 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00004474 // We're in a lambda; determine the lambda capture field maps unless we're
4475 // just constexpr checking a lambda's call operator. constexpr checking is
4476 // done before the captures have been added to the closure object (unless
4477 // we're inferring constexpr-ness), so we don't have access to them in this
4478 // case. But since we don't need the captures to constexpr check, we can
4479 // just ignore them.
4480 if (!Info.checkingPotentialConstantExpression())
4481 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4482 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004483 }
4484
Richard Smith52a980a2015-08-28 02:43:42 +00004485 StmtResult Ret = {Result, ResultSlot};
4486 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004487 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004488 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004489 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004490 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004491 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004492 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004493}
4494
Richard Smithd62306a2011-11-10 06:34:14 +00004495/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004496static bool HandleConstructorCall(const Expr *E, const LValue &This,
4497 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004498 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004499 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004500 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004501 if (!Info.CheckCallLimit(CallLoc))
4502 return false;
4503
Richard Smith3607ffe2012-02-13 03:54:03 +00004504 const CXXRecordDecl *RD = Definition->getParent();
4505 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004506 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004507 return false;
4508 }
4509
Erik Pilkington42925492017-10-04 00:18:55 +00004510 EvalInfo::EvaluatingConstructorRAII EvalObj(
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004511 Info, {This.getLValueBase(),
4512 {This.getLValueCallIndex(), This.getLValueVersion()}});
Richard Smith5179eb72016-06-28 19:03:57 +00004513 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004514
Richard Smith52a980a2015-08-28 02:43:42 +00004515 // FIXME: Creating an APValue just to hold a nonexistent return value is
4516 // wasteful.
4517 APValue RetVal;
4518 StmtResult Ret = {RetVal, nullptr};
4519
Richard Smith5179eb72016-06-28 19:03:57 +00004520 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004521 if (Definition->isDelegatingConstructor()) {
4522 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004523 {
4524 FullExpressionRAII InitScope(Info);
4525 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4526 return false;
4527 }
Richard Smith52a980a2015-08-28 02:43:42 +00004528 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004529 }
4530
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004531 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004532 // essential for unions (or classes with anonymous union members), where the
4533 // operations performed by the constructor cannot be represented by
4534 // ctor-initializers.
4535 //
4536 // Skip this for empty non-union classes; we should not perform an
4537 // lvalue-to-rvalue conversion on them because their copy constructor does not
4538 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004539 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004540 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004541 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004542 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004543 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004544 return handleLValueToRValueConversion(
4545 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4546 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004547 }
4548
4549 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004550 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004551 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004552 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004553
John McCalld7bca762012-05-01 00:38:49 +00004554 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004555 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4556
Richard Smith08d6a2c2013-07-24 07:11:57 +00004557 // A scope for temporaries lifetime-extended by reference members.
4558 BlockScopeRAII LifetimeExtendedScope(Info);
4559
Richard Smith253c2a32012-01-27 01:14:48 +00004560 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004561 unsigned BasesSeen = 0;
4562#ifndef NDEBUG
4563 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4564#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004565 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004566 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004567 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004568 APValue *Value = &Result;
4569
4570 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004571 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004572 if (I->isBaseInitializer()) {
4573 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004574#ifndef NDEBUG
4575 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004576 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004577 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4578 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4579 "base class initializers not in expected order");
4580 ++BaseIt;
4581#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004582 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004583 BaseType->getAsCXXRecordDecl(), &Layout))
4584 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004585 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004586 } else if ((FD = I->getMember())) {
4587 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004588 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004589 if (RD->isUnion()) {
4590 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004591 Value = &Result.getUnionValue();
4592 } else {
4593 Value = &Result.getStructField(FD->getFieldIndex());
4594 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004595 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004596 // Walk the indirect field decl's chain to find the object to initialize,
4597 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004598 auto IndirectFieldChain = IFD->chain();
4599 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004600 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004601 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4602 // Switch the union field if it differs. This happens if we had
4603 // preceding zero-initialization, and we're now initializing a union
4604 // subobject other than the first.
4605 // FIXME: In this case, the values of the other subobjects are
4606 // specified, since zero-initialization sets all padding bits to zero.
4607 if (Value->isUninit() ||
4608 (Value->isUnion() && Value->getUnionField() != FD)) {
4609 if (CD->isUnion())
4610 *Value = APValue(FD);
4611 else
4612 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004613 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004614 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004615 // Store Subobject as its parent before updating it for the last element
4616 // in the chain.
4617 if (C == IndirectFieldChain.back())
4618 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004619 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004620 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004621 if (CD->isUnion())
4622 Value = &Value->getUnionValue();
4623 else
4624 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004625 }
Richard Smithd62306a2011-11-10 06:34:14 +00004626 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004627 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004628 }
Richard Smith253c2a32012-01-27 01:14:48 +00004629
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004630 // Need to override This for implicit field initializers as in this case
4631 // This refers to innermost anonymous struct/union containing initializer,
4632 // not to currently constructed class.
4633 const Expr *Init = I->getInit();
4634 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4635 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004636 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004637 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4638 (FD && FD->isBitField() &&
4639 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004640 // If we're checking for a potential constant expression, evaluate all
4641 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004642 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004643 return false;
4644 Success = false;
4645 }
Richard Smithd62306a2011-11-10 06:34:14 +00004646 }
4647
Richard Smithd9f663b2013-04-22 15:31:51 +00004648 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004649 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004650}
4651
Richard Smith5179eb72016-06-28 19:03:57 +00004652static bool HandleConstructorCall(const Expr *E, const LValue &This,
4653 ArrayRef<const Expr*> Args,
4654 const CXXConstructorDecl *Definition,
4655 EvalInfo &Info, APValue &Result) {
4656 ArgVector ArgValues(Args.size());
4657 if (!EvaluateArgs(Args, ArgValues, Info))
4658 return false;
4659
4660 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4661 Info, Result);
4662}
4663
Eli Friedman9a156e52008-11-12 09:44:48 +00004664//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004665// Generic Evaluation
4666//===----------------------------------------------------------------------===//
4667namespace {
4668
Aaron Ballman68af21c2014-01-03 19:26:43 +00004669template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004670class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004671 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004672private:
Richard Smith52a980a2015-08-28 02:43:42 +00004673 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004674 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004675 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004676 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004677 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004678 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004679 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004680
Richard Smith17100ba2012-02-16 02:46:34 +00004681 // Check whether a conditional operator with a non-constant condition is a
4682 // potential constant expression. If neither arm is a potential constant
4683 // expression, then the conditional operator is not either.
4684 template<typename ConditionalOperator>
4685 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004686 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004687
4688 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004689 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004690 {
Richard Smith17100ba2012-02-16 02:46:34 +00004691 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004692 StmtVisitorTy::Visit(E->getFalseExpr());
4693 if (Diag.empty())
4694 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004695 }
Richard Smith17100ba2012-02-16 02:46:34 +00004696
George Burgess IV8c892b52016-05-25 22:31:54 +00004697 {
4698 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004699 Diag.clear();
4700 StmtVisitorTy::Visit(E->getTrueExpr());
4701 if (Diag.empty())
4702 return;
4703 }
4704
4705 Error(E, diag::note_constexpr_conditional_never_const);
4706 }
4707
4708
4709 template<typename ConditionalOperator>
4710 bool HandleConditionalOperator(const ConditionalOperator *E) {
4711 bool BoolResult;
4712 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004713 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004714 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004715 return false;
4716 }
4717 if (Info.noteFailure()) {
4718 StmtVisitorTy::Visit(E->getTrueExpr());
4719 StmtVisitorTy::Visit(E->getFalseExpr());
4720 }
Richard Smith17100ba2012-02-16 02:46:34 +00004721 return false;
4722 }
4723
4724 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4725 return StmtVisitorTy::Visit(EvalExpr);
4726 }
4727
Peter Collingbournee9200682011-05-13 03:29:01 +00004728protected:
4729 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004730 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004731 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4732
Richard Smith92b1ce02011-12-12 09:28:41 +00004733 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004734 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004735 }
4736
Aaron Ballman68af21c2014-01-03 19:26:43 +00004737 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004738
4739public:
4740 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4741
4742 EvalInfo &getEvalInfo() { return Info; }
4743
Richard Smithf57d8cb2011-12-09 22:58:01 +00004744 /// Report an evaluation error. This should only be called when an error is
4745 /// first discovered. When propagating an error, just return false.
4746 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004747 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004748 return false;
4749 }
4750 bool Error(const Expr *E) {
4751 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4752 }
4753
Aaron Ballman68af21c2014-01-03 19:26:43 +00004754 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004755 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004756 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004757 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004758 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004759 }
4760
Bill Wendling8003edc2018-11-09 00:41:36 +00004761 bool VisitConstantExpr(const ConstantExpr *E)
4762 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004763 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004764 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004765 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004766 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004767 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004768 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004769 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004770 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004771 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004772 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004773 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004774 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004775 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4776 TempVersionRAII RAII(*Info.CurrentCall);
4777 return StmtVisitorTy::Visit(E->getExpr());
4778 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004779 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004780 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00004781 // The initializer may not have been parsed yet, or might be erroneous.
4782 if (!E->getExpr())
4783 return Error(E);
4784 return StmtVisitorTy::Visit(E->getExpr());
4785 }
Richard Smith5894a912011-12-19 22:12:41 +00004786 // We cannot create any objects for which cleanups are required, so there is
4787 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004788 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004789 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004790
Aaron Ballman68af21c2014-01-03 19:26:43 +00004791 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004792 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4793 return static_cast<Derived*>(this)->VisitCastExpr(E);
4794 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004795 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004796 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4797 return static_cast<Derived*>(this)->VisitCastExpr(E);
4798 }
4799
Aaron Ballman68af21c2014-01-03 19:26:43 +00004800 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004801 switch (E->getOpcode()) {
4802 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004803 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004804
4805 case BO_Comma:
4806 VisitIgnoredValue(E->getLHS());
4807 return StmtVisitorTy::Visit(E->getRHS());
4808
4809 case BO_PtrMemD:
4810 case BO_PtrMemI: {
4811 LValue Obj;
4812 if (!HandleMemberPointerAccess(Info, E, Obj))
4813 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004814 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004815 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004816 return false;
4817 return DerivedSuccess(Result, E);
4818 }
4819 }
4820 }
4821
Aaron Ballman68af21c2014-01-03 19:26:43 +00004822 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004823 // Evaluate and cache the common expression. We treat it as a temporary,
4824 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004825 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004826 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004827 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004828
Richard Smith17100ba2012-02-16 02:46:34 +00004829 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004830 }
4831
Aaron Ballman68af21c2014-01-03 19:26:43 +00004832 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004833 bool IsBcpCall = false;
4834 // If the condition (ignoring parens) is a __builtin_constant_p call,
4835 // the result is a constant expression if it can be folded without
4836 // side-effects. This is an important GNU extension. See GCC PR38377
4837 // for discussion.
4838 if (const CallExpr *CallCE =
4839 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004840 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004841 IsBcpCall = true;
4842
4843 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4844 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004845 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004846 return false;
4847
Richard Smith6d4c6582013-11-05 22:18:15 +00004848 FoldConstant Fold(Info, IsBcpCall);
4849 if (!HandleConditionalOperator(E)) {
4850 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004851 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004852 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004853
4854 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004855 }
4856
Aaron Ballman68af21c2014-01-03 19:26:43 +00004857 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004858 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00004859 return DerivedSuccess(*Value, E);
4860
4861 const Expr *Source = E->getSourceExpr();
4862 if (!Source)
4863 return Error(E);
4864 if (Source == E) { // sanity checking.
4865 assert(0 && "OpaqueValueExpr recursively refers to itself");
4866 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004867 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004868 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004869 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004870
Aaron Ballman68af21c2014-01-03 19:26:43 +00004871 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004872 APValue Result;
4873 if (!handleCallExpr(E, Result, nullptr))
4874 return false;
4875 return DerivedSuccess(Result, E);
4876 }
4877
4878 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004879 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004880 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004881 QualType CalleeType = Callee->getType();
4882
Craig Topper36250ad2014-05-12 05:36:57 +00004883 const FunctionDecl *FD = nullptr;
4884 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004885 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004886 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004887
Richard Smithe97cbd72011-11-11 04:05:33 +00004888 // Extract function decl and 'this' pointer from the callee.
4889 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004890 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004891 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4892 // Explicit bound member calls, such as x.f() or p->g();
4893 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004894 return false;
4895 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004896 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004897 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004898 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4899 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004900 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4901 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004902 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004903 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004904 return Error(Callee);
4905
4906 FD = dyn_cast<FunctionDecl>(Member);
4907 if (!FD)
4908 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004909 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004910 LValue Call;
4911 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004912 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004913
Richard Smitha8105bc2012-01-06 16:39:00 +00004914 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004915 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004916 FD = dyn_cast_or_null<FunctionDecl>(
4917 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004918 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004919 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004920 // Don't call function pointers which have been cast to some other type.
4921 // Per DR (no number yet), the caller and callee can differ in noexcept.
4922 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4923 CalleeType->getPointeeType(), FD->getType())) {
4924 return Error(E);
4925 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004926
4927 // Overloaded operator calls to member functions are represented as normal
4928 // calls with '*this' as the first argument.
4929 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4930 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004931 // FIXME: When selecting an implicit conversion for an overloaded
4932 // operator delete, we sometimes try to evaluate calls to conversion
4933 // operators without a 'this' parameter!
4934 if (Args.empty())
4935 return Error(E);
4936
Nick Lewycky13073a62017-06-12 21:15:44 +00004937 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004938 return false;
4939 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004940 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00004941 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004942 // Map the static invoker for the lambda back to the call operator.
4943 // Conveniently, we don't have to slice out the 'this' argument (as is
4944 // being done for the non-static case), since a static member function
4945 // doesn't have an implicit argument passed in.
4946 const CXXRecordDecl *ClosureClass = MD->getParent();
4947 assert(
4948 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4949 "Number of captures must be zero for conversion to function-ptr");
4950
4951 const CXXMethodDecl *LambdaCallOp =
4952 ClosureClass->getLambdaCallOperator();
4953
4954 // Set 'FD', the function that will be called below, to the call
4955 // operator. If the closure object represents a generic lambda, find
4956 // the corresponding specialization of the call operator.
4957
4958 if (ClosureClass->isGenericLambda()) {
4959 assert(MD->isFunctionTemplateSpecialization() &&
4960 "A generic lambda's static-invoker function must be a "
4961 "template specialization");
4962 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4963 FunctionTemplateDecl *CallOpTemplate =
4964 LambdaCallOp->getDescribedFunctionTemplate();
4965 void *InsertPos = nullptr;
4966 FunctionDecl *CorrespondingCallOpSpecialization =
4967 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4968 assert(CorrespondingCallOpSpecialization &&
4969 "We must always have a function call operator specialization "
4970 "that corresponds to our static invoker specialization");
4971 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4972 } else
4973 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004974 }
4975
Fangrui Song6907ce22018-07-30 19:24:48 +00004976
Richard Smithe97cbd72011-11-11 04:05:33 +00004977 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004978 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004979
Richard Smith47b34932012-02-01 02:39:43 +00004980 if (This && !This->checkSubobject(Info, E, CSK_This))
4981 return false;
4982
Richard Smith3607ffe2012-02-13 03:54:03 +00004983 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4984 // calls to such functions in constant expressions.
4985 if (This && !HasQualifier &&
4986 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4987 return Error(E, diag::note_constexpr_virtual_call);
4988
Craig Topper36250ad2014-05-12 05:36:57 +00004989 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004990 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004991
Nick Lewycky13073a62017-06-12 21:15:44 +00004992 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4993 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004994 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004995 return false;
4996
Richard Smith52a980a2015-08-28 02:43:42 +00004997 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004998 }
4999
Aaron Ballman68af21c2014-01-03 19:26:43 +00005000 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005001 return StmtVisitorTy::Visit(E->getInitializer());
5002 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005003 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00005004 if (E->getNumInits() == 0)
5005 return DerivedZeroInitialization(E);
5006 if (E->getNumInits() == 1)
5007 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00005008 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005009 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005010 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005011 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005012 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005013 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005014 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005015 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005016 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005017 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005018 }
Richard Smith4ce706a2011-10-11 21:43:33 +00005019
Richard Smithd62306a2011-11-10 06:34:14 +00005020 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00005021 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005022 assert(!E->isArrow() && "missing call to bound member function?");
5023
Richard Smith2e312c82012-03-03 22:46:17 +00005024 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00005025 if (!Evaluate(Val, Info, E->getBase()))
5026 return false;
5027
5028 QualType BaseTy = E->getBase()->getType();
5029
5030 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00005031 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005032 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00005033 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00005034 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5035
Richard Smith9defb7d2018-02-21 03:38:30 +00005036 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00005037 SubobjectDesignator Designator(BaseTy);
5038 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00005039
Richard Smith3229b742013-05-05 21:17:10 +00005040 APValue Result;
5041 return extractSubobject(Info, E, Obj, Designator, Result) &&
5042 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00005043 }
5044
Aaron Ballman68af21c2014-01-03 19:26:43 +00005045 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005046 switch (E->getCastKind()) {
5047 default:
5048 break;
5049
Richard Smitha23ab512013-05-23 00:30:41 +00005050 case CK_AtomicToNonAtomic: {
5051 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00005052 // This does not need to be done in place even for class/array types:
5053 // atomic-to-non-atomic conversion implies copying the object
5054 // representation.
5055 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00005056 return false;
5057 return DerivedSuccess(AtomicVal, E);
5058 }
5059
Richard Smith11562c52011-10-28 17:51:58 +00005060 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00005061 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00005062 return StmtVisitorTy::Visit(E->getSubExpr());
5063
5064 case CK_LValueToRValue: {
5065 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005066 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5067 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005068 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00005069 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00005070 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00005071 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005072 return false;
5073 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00005074 }
5075 }
5076
Richard Smithf57d8cb2011-12-09 22:58:01 +00005077 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005078 }
5079
Aaron Ballman68af21c2014-01-03 19:26:43 +00005080 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005081 return VisitUnaryPostIncDec(UO);
5082 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005083 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005084 return VisitUnaryPostIncDec(UO);
5085 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005086 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005087 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005088 return Error(UO);
5089
5090 LValue LVal;
5091 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5092 return false;
5093 APValue RVal;
5094 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5095 UO->isIncrementOp(), &RVal))
5096 return false;
5097 return DerivedSuccess(RVal, UO);
5098 }
5099
Aaron Ballman68af21c2014-01-03 19:26:43 +00005100 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00005101 // We will have checked the full-expressions inside the statement expression
5102 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00005103 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00005104 return Error(E);
5105
Richard Smith08d6a2c2013-07-24 07:11:57 +00005106 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00005107 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005108 if (CS->body_empty())
5109 return true;
5110
Richard Smith51f03172013-06-20 03:00:05 +00005111 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5112 BE = CS->body_end();
5113 /**/; ++BI) {
5114 if (BI + 1 == BE) {
5115 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5116 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005117 Info.FFDiag((*BI)->getBeginLoc(),
5118 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005119 return false;
5120 }
5121 return this->Visit(FinalExpr);
5122 }
5123
5124 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00005125 StmtResult Result = { ReturnValue, nullptr };
5126 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00005127 if (ESR != ESR_Succeeded) {
5128 // FIXME: If the statement-expression terminated due to 'return',
5129 // 'break', or 'continue', it would be nice to propagate that to
5130 // the outer statement evaluation rather than bailing out.
5131 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005132 Info.FFDiag((*BI)->getBeginLoc(),
5133 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005134 return false;
5135 }
5136 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005137
5138 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00005139 }
5140
Richard Smith4a678122011-10-24 18:44:57 +00005141 /// Visit a value which is evaluated, but whose value is ignored.
5142 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00005143 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00005144 }
David Majnemere9807b22016-02-26 04:23:19 +00005145
5146 /// Potentially visit a MemberExpr's base expression.
5147 void VisitIgnoredBaseExpression(const Expr *E) {
5148 // While MSVC doesn't evaluate the base expression, it does diagnose the
5149 // presence of side-effecting behavior.
5150 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5151 return;
5152 VisitIgnoredValue(E);
5153 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005154};
5155
Eric Fiselier0683c0e2018-05-07 21:07:10 +00005156} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00005157
5158//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005159// Common base class for lvalue and temporary evaluation.
5160//===----------------------------------------------------------------------===//
5161namespace {
5162template<class Derived>
5163class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005164 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00005165protected:
5166 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005167 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005168 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005169 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005170
5171 bool Success(APValue::LValueBase B) {
5172 Result.set(B);
5173 return true;
5174 }
5175
George Burgess IVf9013bf2017-02-10 22:52:29 +00005176 bool evaluatePointer(const Expr *E, LValue &Result) {
5177 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5178 }
5179
Richard Smith027bf112011-11-17 22:56:20 +00005180public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005181 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5182 : ExprEvaluatorBaseTy(Info), Result(Result),
5183 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005184
Richard Smith2e312c82012-03-03 22:46:17 +00005185 bool Success(const APValue &V, const Expr *E) {
5186 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005187 return true;
5188 }
Richard Smith027bf112011-11-17 22:56:20 +00005189
Richard Smith027bf112011-11-17 22:56:20 +00005190 bool VisitMemberExpr(const MemberExpr *E) {
5191 // Handle non-static data members.
5192 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005193 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005194 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005195 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005196 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005197 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005198 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005199 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005200 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005201 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005202 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005203 BaseTy = E->getBase()->getType();
5204 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005205 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005206 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005207 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005208 Result.setInvalid(E);
5209 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005210 }
Richard Smith027bf112011-11-17 22:56:20 +00005211
Richard Smith1b78b3d2012-01-25 22:15:11 +00005212 const ValueDecl *MD = E->getMemberDecl();
5213 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5214 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5215 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5216 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005217 if (!HandleLValueMember(this->Info, E, Result, FD))
5218 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005219 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005220 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5221 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005222 } else
5223 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005224
Richard Smith1b78b3d2012-01-25 22:15:11 +00005225 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005226 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005227 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005228 RefValue))
5229 return false;
5230 return Success(RefValue, E);
5231 }
5232 return true;
5233 }
5234
5235 bool VisitBinaryOperator(const BinaryOperator *E) {
5236 switch (E->getOpcode()) {
5237 default:
5238 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5239
5240 case BO_PtrMemD:
5241 case BO_PtrMemI:
5242 return HandleMemberPointerAccess(this->Info, E, Result);
5243 }
5244 }
5245
5246 bool VisitCastExpr(const CastExpr *E) {
5247 switch (E->getCastKind()) {
5248 default:
5249 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5250
5251 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005252 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005253 if (!this->Visit(E->getSubExpr()))
5254 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005255
5256 // Now figure out the necessary offset to add to the base LV to get from
5257 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005258 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5259 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005260 }
5261 }
5262};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005263}
Richard Smith027bf112011-11-17 22:56:20 +00005264
5265//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005266// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005267//
5268// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5269// function designators (in C), decl references to void objects (in C), and
5270// temporaries (if building with -Wno-address-of-temporary).
5271//
5272// LValue evaluation produces values comprising a base expression of one of the
5273// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005274// - Declarations
5275// * VarDecl
5276// * FunctionDecl
5277// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005278// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005279// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005280// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005281// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005282// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005283// * ObjCEncodeExpr
5284// * AddrLabelExpr
5285// * BlockExpr
5286// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005287// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005288// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005289// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005290// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5291// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005292// * A MaterializeTemporaryExpr that has static storage duration, with no
5293// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005294// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005295//===----------------------------------------------------------------------===//
5296namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005297class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005298 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005299public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005300 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5301 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005302
Richard Smith11562c52011-10-28 17:51:58 +00005303 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005304 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005305
Peter Collingbournee9200682011-05-13 03:29:01 +00005306 bool VisitDeclRefExpr(const DeclRefExpr *E);
5307 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005308 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005309 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5310 bool VisitMemberExpr(const MemberExpr *E);
5311 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5312 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005313 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005314 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005315 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5316 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005317 bool VisitUnaryReal(const UnaryOperator *E);
5318 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005319 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5320 return VisitUnaryPreIncDec(UO);
5321 }
5322 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5323 return VisitUnaryPreIncDec(UO);
5324 }
Richard Smith3229b742013-05-05 21:17:10 +00005325 bool VisitBinAssign(const BinaryOperator *BO);
5326 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005327
Peter Collingbournee9200682011-05-13 03:29:01 +00005328 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005329 switch (E->getCastKind()) {
5330 default:
Richard Smith027bf112011-11-17 22:56:20 +00005331 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005332
Eli Friedmance3e02a2011-10-11 00:13:24 +00005333 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005334 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005335 if (!Visit(E->getSubExpr()))
5336 return false;
5337 Result.Designator.setInvalid();
5338 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005339
Richard Smith027bf112011-11-17 22:56:20 +00005340 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005341 if (!Visit(E->getSubExpr()))
5342 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005343 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005344 }
5345 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005346};
5347} // end anonymous namespace
5348
Richard Smith11562c52011-10-28 17:51:58 +00005349/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005350/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005351/// * function designators in C, and
5352/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005353/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005354static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5355 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005356 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005357 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005358 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005359}
5360
Peter Collingbournee9200682011-05-13 03:29:01 +00005361bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005362 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005363 return Success(FD);
5364 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005365 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005366 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005367 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005368 return Error(E);
5369}
Richard Smith733237d2011-10-24 23:14:33 +00005370
Faisal Vali0528a312016-11-13 06:09:16 +00005371
Richard Smith11562c52011-10-28 17:51:58 +00005372bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005373
5374 // If we are within a lambda's call operator, check whether the 'VD' referred
5375 // to within 'E' actually represents a lambda-capture that maps to a
5376 // data-member/field within the closure object, and if so, evaluate to the
5377 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00005378 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5379 isa<DeclRefExpr>(E) &&
5380 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5381 // We don't always have a complete capture-map when checking or inferring if
5382 // the function call operator meets the requirements of a constexpr function
5383 // - but we don't need to evaluate the captures to determine constexprness
5384 // (dcl.constexpr C++17).
5385 if (Info.checkingPotentialConstantExpression())
5386 return false;
5387
Faisal Vali051e3a22017-02-16 04:12:21 +00005388 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005389 // Start with 'Result' referring to the complete closure object...
5390 Result = *Info.CurrentCall->This;
5391 // ... then update it to refer to the field of the closure object
5392 // that represents the capture.
5393 if (!HandleLValueMember(Info, E, Result, FD))
5394 return false;
5395 // And if the field is of reference type, update 'Result' to refer to what
5396 // the field refers to.
5397 if (FD->getType()->isReferenceType()) {
5398 APValue RVal;
5399 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5400 RVal))
5401 return false;
5402 Result.setFrom(Info.Ctx, RVal);
5403 }
5404 return true;
5405 }
5406 }
Craig Topper36250ad2014-05-12 05:36:57 +00005407 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005408 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5409 // Only if a local variable was declared in the function currently being
5410 // evaluated, do we expect to be able to find its value in the current
5411 // frame. (Otherwise it was likely declared in an enclosing context and
5412 // could either have a valid evaluatable value (for e.g. a constexpr
5413 // variable) or be ill-formed (and trigger an appropriate evaluation
5414 // diagnostic)).
5415 if (Info.CurrentCall->Callee &&
5416 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5417 Frame = Info.CurrentCall;
5418 }
5419 }
Richard Smith3229b742013-05-05 21:17:10 +00005420
Richard Smithfec09922011-11-01 16:57:24 +00005421 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005422 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005423 Result.set({VD, Frame->Index,
5424 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00005425 return true;
5426 }
Richard Smithce40ad62011-11-12 22:28:03 +00005427 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005428 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005429
Richard Smith3229b742013-05-05 21:17:10 +00005430 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005431 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005432 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005433 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005434 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005435 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005436 return false;
5437 }
Richard Smith3229b742013-05-05 21:17:10 +00005438 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005439}
5440
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005441bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5442 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005443 // Walk through the expression to find the materialized temporary itself.
5444 SmallVector<const Expr *, 2> CommaLHSs;
5445 SmallVector<SubobjectAdjustment, 2> Adjustments;
5446 const Expr *Inner = E->GetTemporaryExpr()->
5447 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005448
Richard Smith84401042013-06-03 05:03:02 +00005449 // If we passed any comma operators, evaluate their LHSs.
5450 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5451 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5452 return false;
5453
Richard Smithe6c01442013-06-05 00:46:14 +00005454 // A materialized temporary with static storage duration can appear within the
5455 // result of a constant expression evaluation, so we need to preserve its
5456 // value for use outside this evaluation.
5457 APValue *Value;
5458 if (E->getStorageDuration() == SD_Static) {
5459 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005460 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005461 Result.set(E);
5462 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005463 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5464 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00005465 }
5466
Richard Smithea4ad5d2013-06-06 08:19:16 +00005467 QualType Type = Inner->getType();
5468
Richard Smith84401042013-06-03 05:03:02 +00005469 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005470 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5471 (E->getStorageDuration() == SD_Static &&
5472 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5473 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005474 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005475 }
Richard Smith84401042013-06-03 05:03:02 +00005476
5477 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005478 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5479 --I;
5480 switch (Adjustments[I].Kind) {
5481 case SubobjectAdjustment::DerivedToBaseAdjustment:
5482 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5483 Type, Result))
5484 return false;
5485 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5486 break;
5487
5488 case SubobjectAdjustment::FieldAdjustment:
5489 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5490 return false;
5491 Type = Adjustments[I].Field->getType();
5492 break;
5493
5494 case SubobjectAdjustment::MemberPointerAdjustment:
5495 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5496 Adjustments[I].Ptr.RHS))
5497 return false;
5498 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5499 break;
5500 }
5501 }
5502
5503 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005504}
5505
Peter Collingbournee9200682011-05-13 03:29:01 +00005506bool
5507LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005508 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5509 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005510 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5511 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005512 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005513}
5514
Richard Smith6e525142011-12-27 12:18:28 +00005515bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005516 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005517 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005518
Faisal Valie690b7a2016-07-02 22:34:24 +00005519 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005520 << E->getExprOperand()->getType()
5521 << E->getExprOperand()->getSourceRange();
5522 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005523}
5524
Francois Pichet0066db92012-04-16 04:08:35 +00005525bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5526 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005527}
Francois Pichet0066db92012-04-16 04:08:35 +00005528
Peter Collingbournee9200682011-05-13 03:29:01 +00005529bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005530 // Handle static data members.
5531 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005532 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005533 return VisitVarDecl(E, VD);
5534 }
5535
Richard Smith254a73d2011-10-28 22:34:42 +00005536 // Handle static member functions.
5537 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5538 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005539 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005540 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005541 }
5542 }
5543
Richard Smithd62306a2011-11-10 06:34:14 +00005544 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005545 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005546}
5547
Peter Collingbournee9200682011-05-13 03:29:01 +00005548bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005549 // FIXME: Deal with vectors as array subscript bases.
5550 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005551 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005552
Nick Lewyckyad888682017-04-27 07:27:36 +00005553 bool Success = true;
5554 if (!evaluatePointer(E->getBase(), Result)) {
5555 if (!Info.noteFailure())
5556 return false;
5557 Success = false;
5558 }
Mike Stump11289f42009-09-09 15:08:12 +00005559
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005560 APSInt Index;
5561 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005562 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005563
Nick Lewyckyad888682017-04-27 07:27:36 +00005564 return Success &&
5565 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005566}
Eli Friedman9a156e52008-11-12 09:44:48 +00005567
Peter Collingbournee9200682011-05-13 03:29:01 +00005568bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005569 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005570}
5571
Richard Smith66c96992012-02-18 22:04:06 +00005572bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5573 if (!Visit(E->getSubExpr()))
5574 return false;
5575 // __real is a no-op on scalar lvalues.
5576 if (E->getSubExpr()->getType()->isAnyComplexType())
5577 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5578 return true;
5579}
5580
5581bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5582 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5583 "lvalue __imag__ on scalar?");
5584 if (!Visit(E->getSubExpr()))
5585 return false;
5586 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5587 return true;
5588}
5589
Richard Smith243ef902013-05-05 23:31:59 +00005590bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005591 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005592 return Error(UO);
5593
5594 if (!this->Visit(UO->getSubExpr()))
5595 return false;
5596
Richard Smith243ef902013-05-05 23:31:59 +00005597 return handleIncDec(
5598 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005599 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005600}
5601
5602bool LValueExprEvaluator::VisitCompoundAssignOperator(
5603 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005604 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005605 return Error(CAO);
5606
Richard Smith3229b742013-05-05 21:17:10 +00005607 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005608
5609 // The overall lvalue result is the result of evaluating the LHS.
5610 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005611 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005612 Evaluate(RHS, this->Info, CAO->getRHS());
5613 return false;
5614 }
5615
Richard Smith3229b742013-05-05 21:17:10 +00005616 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5617 return false;
5618
Richard Smith43e77732013-05-07 04:50:00 +00005619 return handleCompoundAssignment(
5620 this->Info, CAO,
5621 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5622 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005623}
5624
5625bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005626 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005627 return Error(E);
5628
Richard Smith3229b742013-05-05 21:17:10 +00005629 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005630
5631 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005632 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005633 Evaluate(NewVal, this->Info, E->getRHS());
5634 return false;
5635 }
5636
Richard Smith3229b742013-05-05 21:17:10 +00005637 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5638 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005639
5640 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005641 NewVal);
5642}
5643
Eli Friedman9a156e52008-11-12 09:44:48 +00005644//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005645// Pointer Evaluation
5646//===----------------------------------------------------------------------===//
5647
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005648/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00005649/// returned by a function with the alloc_size attribute. Returns true if we
5650/// were successful. Places an unsigned number into `Result`.
5651///
5652/// This expects the given CallExpr to be a call to a function with an
5653/// alloc_size attribute.
5654static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5655 const CallExpr *Call,
5656 llvm::APInt &Result) {
5657 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5658
Joel E. Denny81508102018-03-13 14:51:22 +00005659 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5660 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005661 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5662 if (Call->getNumArgs() <= SizeArgNo)
5663 return false;
5664
5665 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00005666 Expr::EvalResult ExprResult;
5667 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00005668 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00005669 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00005670 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5671 return false;
5672 Into = Into.zextOrSelf(BitsInSizeT);
5673 return true;
5674 };
5675
5676 APSInt SizeOfElem;
5677 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5678 return false;
5679
Joel E. Denny81508102018-03-13 14:51:22 +00005680 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005681 Result = std::move(SizeOfElem);
5682 return true;
5683 }
5684
5685 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00005686 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005687 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5688 return false;
5689
5690 bool Overflow;
5691 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5692 if (Overflow)
5693 return false;
5694
5695 Result = std::move(BytesAvailable);
5696 return true;
5697}
5698
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005699/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00005700/// function.
5701static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5702 const LValue &LVal,
5703 llvm::APInt &Result) {
5704 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5705 "Can't get the size of a non alloc_size function");
5706 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5707 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5708 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5709}
5710
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005711/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00005712/// a function with the alloc_size attribute. If it was possible to do so, this
5713/// function will return true, make Result's Base point to said function call,
5714/// and mark Result's Base as invalid.
5715static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5716 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005717 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005718 return false;
5719
5720 // Because we do no form of static analysis, we only support const variables.
5721 //
5722 // Additionally, we can't support parameters, nor can we support static
5723 // variables (in the latter case, use-before-assign isn't UB; in the former,
5724 // we have no clue what they'll be assigned to).
5725 const auto *VD =
5726 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5727 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5728 return false;
5729
5730 const Expr *Init = VD->getAnyInitializer();
5731 if (!Init)
5732 return false;
5733
5734 const Expr *E = Init->IgnoreParens();
5735 if (!tryUnwrapAllocSizeCall(E))
5736 return false;
5737
5738 // Store E instead of E unwrapped so that the type of the LValue's base is
5739 // what the user wanted.
5740 Result.setInvalid(E);
5741
5742 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005743 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005744 return true;
5745}
5746
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005747namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005748class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005749 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005750 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005751 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005752
Peter Collingbournee9200682011-05-13 03:29:01 +00005753 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005754 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005755 return true;
5756 }
George Burgess IVe3763372016-12-22 02:50:20 +00005757
George Burgess IVf9013bf2017-02-10 22:52:29 +00005758 bool evaluateLValue(const Expr *E, LValue &Result) {
5759 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5760 }
5761
5762 bool evaluatePointer(const Expr *E, LValue &Result) {
5763 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5764 }
5765
George Burgess IVe3763372016-12-22 02:50:20 +00005766 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005767public:
Mike Stump11289f42009-09-09 15:08:12 +00005768
George Burgess IVf9013bf2017-02-10 22:52:29 +00005769 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5770 : ExprEvaluatorBaseTy(info), Result(Result),
5771 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005772
Richard Smith2e312c82012-03-03 22:46:17 +00005773 bool Success(const APValue &V, const Expr *E) {
5774 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005775 return true;
5776 }
Richard Smithfddd3842011-12-30 21:15:51 +00005777 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005778 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5779 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005780 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005781 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005782
John McCall45d55e42010-05-07 21:00:08 +00005783 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005784 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005785 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005786 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005787 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005788 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5789 if (Info.noteFailure())
5790 EvaluateIgnoredValue(Info, E->getSubExpr());
5791 return Error(E);
5792 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005793 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005794 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005795 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005796 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005797 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005798 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005799 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005800 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005801 }
Richard Smithd62306a2011-11-10 06:34:14 +00005802 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005803 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005804 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005805 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005806 if (!Info.CurrentCall->This) {
5807 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005808 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005809 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005810 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005811 return false;
5812 }
Richard Smithd62306a2011-11-10 06:34:14 +00005813 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005814 // If we are inside a lambda's call operator, the 'this' expression refers
5815 // to the enclosing '*this' object (either by value or reference) which is
5816 // either copied into the closure object's field that represents the '*this'
5817 // or refers to '*this'.
5818 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5819 // Update 'Result' to refer to the data member/field of the closure object
5820 // that represents the '*this' capture.
5821 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00005822 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005823 return false;
5824 // If we captured '*this' by reference, replace the field with its referent.
5825 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5826 ->isPointerType()) {
5827 APValue RVal;
5828 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5829 RVal))
5830 return false;
5831
5832 Result.setFrom(Info.Ctx, RVal);
5833 }
5834 }
Richard Smithd62306a2011-11-10 06:34:14 +00005835 return true;
5836 }
John McCallc07a0c72011-02-17 10:25:35 +00005837
Eli Friedman449fe542009-03-23 04:56:01 +00005838 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005839};
Chris Lattner05706e882008-07-11 18:11:29 +00005840} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005841
George Burgess IVf9013bf2017-02-10 22:52:29 +00005842static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5843 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005844 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005845 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005846}
5847
John McCall45d55e42010-05-07 21:00:08 +00005848bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005849 if (E->getOpcode() != BO_Add &&
5850 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005851 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005852
Chris Lattner05706e882008-07-11 18:11:29 +00005853 const Expr *PExp = E->getLHS();
5854 const Expr *IExp = E->getRHS();
5855 if (IExp->getType()->isPointerType())
5856 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005857
George Burgess IVf9013bf2017-02-10 22:52:29 +00005858 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005859 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005860 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005861
John McCall45d55e42010-05-07 21:00:08 +00005862 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005863 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005864 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005865
Richard Smith96e0c102011-11-04 02:25:55 +00005866 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005867 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005868
Ted Kremenek28831752012-08-23 20:46:57 +00005869 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005870 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005871}
Eli Friedman9a156e52008-11-12 09:44:48 +00005872
John McCall45d55e42010-05-07 21:00:08 +00005873bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005874 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005875}
Mike Stump11289f42009-09-09 15:08:12 +00005876
Richard Smith81dfef92018-07-11 00:29:05 +00005877bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5878 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005879
Eli Friedman847a2bc2009-12-27 05:43:15 +00005880 switch (E->getCastKind()) {
5881 default:
5882 break;
5883
John McCalle3027922010-08-25 11:45:40 +00005884 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005885 case CK_CPointerToObjCPointerCast:
5886 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005887 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005888 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005889 if (!Visit(SubExpr))
5890 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005891 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5892 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5893 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005894 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00005895 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005896 if (SubExpr->getType()->isVoidPointerType())
5897 CCEDiag(E, diag::note_constexpr_invalid_cast)
5898 << 3 << SubExpr->getType();
5899 else
5900 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5901 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005902 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5903 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005904 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005905
Anders Carlsson18275092010-10-31 20:41:46 +00005906 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005907 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005908 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005909 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005910 if (!Result.Base && Result.Offset.isZero())
5911 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005912
Richard Smithd62306a2011-11-10 06:34:14 +00005913 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005914 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005915 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5916 castAs<PointerType>()->getPointeeType(),
5917 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005918
Richard Smith027bf112011-11-17 22:56:20 +00005919 case CK_BaseToDerived:
5920 if (!Visit(E->getSubExpr()))
5921 return false;
5922 if (!Result.Base && Result.Offset.isZero())
5923 return true;
5924 return HandleBaseToDerivedCast(Info, E, Result);
5925
Richard Smith0b0a0b62011-10-29 20:57:55 +00005926 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005927 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005928 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005929
John McCalle3027922010-08-25 11:45:40 +00005930 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005931 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5932
Richard Smith2e312c82012-03-03 22:46:17 +00005933 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005934 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005935 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005936
John McCall45d55e42010-05-07 21:00:08 +00005937 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005938 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5939 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005940 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005941 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005942 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00005943 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005944 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005945 return true;
5946 } else {
5947 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005948 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005949 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005950 }
5951 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005952
5953 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005954 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005955 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005956 return false;
5957 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005958 APValue &Value = createTemporary(SubExpr, false, Result,
5959 *Info.CurrentCall);
5960 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005961 return false;
5962 }
Richard Smith96e0c102011-11-04 02:25:55 +00005963 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005964 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5965 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005966 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005967 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005968 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005969 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005970 }
Richard Smithdd785442011-10-31 20:57:44 +00005971
John McCalle3027922010-08-25 11:45:40 +00005972 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005973 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005974
5975 case CK_LValueToRValue: {
5976 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005977 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005978 return false;
5979
5980 APValue RVal;
5981 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5982 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5983 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005984 return InvalidBaseOK &&
5985 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005986 return Success(RVal, E);
5987 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005988 }
5989
Richard Smith11562c52011-10-28 17:51:58 +00005990 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005991}
Chris Lattner05706e882008-07-11 18:11:29 +00005992
Richard Smith6822bd72018-10-26 19:26:45 +00005993static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
5994 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005995 // C++ [expr.alignof]p3:
5996 // When alignof is applied to a reference type, the result is the
5997 // alignment of the referenced type.
5998 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5999 T = Ref->getPointeeType();
6000
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00006001 if (T.getQualifiers().hasUnaligned())
6002 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00006003
6004 const bool AlignOfReturnsPreferred =
6005 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
6006
6007 // __alignof is defined to return the preferred alignment.
6008 // Before 8, clang returned the preferred alignment for alignof and _Alignof
6009 // as well.
6010 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
6011 return Info.Ctx.toCharUnitsFromBits(
6012 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6013 // alignof and _Alignof are defined to return the ABI alignment.
6014 else if (ExprKind == UETT_AlignOf)
6015 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
6016 else
6017 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00006018}
6019
Richard Smith6822bd72018-10-26 19:26:45 +00006020static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
6021 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006022 E = E->IgnoreParens();
6023
6024 // The kinds of expressions that we have special-case logic here for
6025 // should be kept up to date with the special checks for those
6026 // expressions in Sema.
6027
6028 // alignof decl is always accepted, even if it doesn't make sense: we default
6029 // to 1 in those cases.
6030 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6031 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6032 /*RefAsPointee*/true);
6033
6034 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6035 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6036 /*RefAsPointee*/true);
6037
Richard Smith6822bd72018-10-26 19:26:45 +00006038 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006039}
6040
George Burgess IVe3763372016-12-22 02:50:20 +00006041// To be clear: this happily visits unsupported builtins. Better name welcomed.
6042bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6043 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6044 return true;
6045
George Burgess IVf9013bf2017-02-10 22:52:29 +00006046 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00006047 return false;
6048
6049 Result.setInvalid(E);
6050 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006051 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00006052 return true;
6053}
6054
Peter Collingbournee9200682011-05-13 03:29:01 +00006055bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006056 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00006057 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00006058
Richard Smith6328cbd2016-11-16 00:57:23 +00006059 if (unsigned BuiltinOp = E->getBuiltinCallee())
6060 return VisitBuiltinCallExpr(E, BuiltinOp);
6061
George Burgess IVe3763372016-12-22 02:50:20 +00006062 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006063}
6064
6065bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6066 unsigned BuiltinOp) {
6067 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00006068 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006069 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006070 case Builtin::BI__builtin_assume_aligned: {
6071 // We need to be very careful here because: if the pointer does not have the
6072 // asserted alignment, then the behavior is undefined, and undefined
6073 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00006074 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00006075 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00006076
Hal Finkel0dd05d42014-10-03 17:18:37 +00006077 LValue OffsetResult(Result);
6078 APSInt Alignment;
6079 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6080 return false;
Richard Smith642a2362017-01-30 23:30:26 +00006081 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00006082
6083 if (E->getNumArgs() > 2) {
6084 APSInt Offset;
6085 if (!EvaluateInteger(E->getArg(2), Offset, Info))
6086 return false;
6087
Richard Smith642a2362017-01-30 23:30:26 +00006088 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006089 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6090 }
6091
6092 // If there is a base object, then it must have the correct alignment.
6093 if (OffsetResult.Base) {
6094 CharUnits BaseAlignment;
6095 if (const ValueDecl *VD =
6096 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6097 BaseAlignment = Info.Ctx.getDeclAlign(VD);
6098 } else {
Richard Smith6822bd72018-10-26 19:26:45 +00006099 BaseAlignment = GetAlignOfExpr(
6100 Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006101 }
6102
6103 if (BaseAlignment < Align) {
6104 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00006105 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00006106 CCEDiag(E->getArg(0),
6107 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00006108 << (unsigned)BaseAlignment.getQuantity()
6109 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006110 return false;
6111 }
6112 }
6113
6114 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006115 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006116 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006117
Richard Smith642a2362017-01-30 23:30:26 +00006118 (OffsetResult.Base
6119 ? CCEDiag(E->getArg(0),
6120 diag::note_constexpr_baa_insufficient_alignment) << 1
6121 : CCEDiag(E->getArg(0),
6122 diag::note_constexpr_baa_value_insufficient_alignment))
6123 << (int)OffsetResult.Offset.getQuantity()
6124 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006125 return false;
6126 }
6127
6128 return true;
6129 }
Eric Fiselier26187502018-12-14 21:11:28 +00006130 case Builtin::BI__builtin_launder:
6131 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00006132 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006133 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00006134 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006135 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00006136 if (Info.getLangOpts().CPlusPlus11)
6137 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6138 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00006139 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00006140 else
6141 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006142 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00006143 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006144 case Builtin::BI__builtin_wcschr:
6145 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006146 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006147 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00006148 if (!Visit(E->getArg(0)))
6149 return false;
6150 APSInt Desired;
6151 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6152 return false;
6153 uint64_t MaxLength = uint64_t(-1);
6154 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00006155 BuiltinOp != Builtin::BIwcschr &&
6156 BuiltinOp != Builtin::BI__builtin_strchr &&
6157 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00006158 APSInt N;
6159 if (!EvaluateInteger(E->getArg(2), N, Info))
6160 return false;
6161 MaxLength = N.getExtValue();
6162 }
Hubert Tong147b7432018-12-12 16:53:43 +00006163 // We cannot find the value if there are no candidates to match against.
6164 if (MaxLength == 0u)
6165 return ZeroInitialization(E);
6166 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
6167 Result.Designator.Invalid)
6168 return false;
6169 QualType CharTy = Result.Designator.getType(Info.Ctx);
6170 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
6171 BuiltinOp == Builtin::BI__builtin_memchr;
6172 assert(IsRawByte ||
6173 Info.Ctx.hasSameUnqualifiedType(
6174 CharTy, E->getArg(0)->getType()->getPointeeType()));
6175 // Pointers to const void may point to objects of incomplete type.
6176 if (IsRawByte && CharTy->isIncompleteType()) {
6177 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
6178 return false;
6179 }
6180 // Give up on byte-oriented matching against multibyte elements.
6181 // FIXME: We can compare the bytes in the correct order.
6182 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
6183 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00006184 // Figure out what value we're actually looking for (after converting to
6185 // the corresponding unsigned type if necessary).
6186 uint64_t DesiredVal;
6187 bool StopAtNull = false;
6188 switch (BuiltinOp) {
6189 case Builtin::BIstrchr:
6190 case Builtin::BI__builtin_strchr:
6191 // strchr compares directly to the passed integer, and therefore
6192 // always fails if given an int that is not a char.
6193 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6194 E->getArg(1)->getType(),
6195 Desired),
6196 Desired))
6197 return ZeroInitialization(E);
6198 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006199 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006200 case Builtin::BImemchr:
6201 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006202 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006203 // memchr compares by converting both sides to unsigned char. That's also
6204 // correct for strchr if we get this far (to cope with plain char being
6205 // unsigned in the strchr case).
6206 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6207 break;
Richard Smithe9507952016-11-12 01:39:56 +00006208
Richard Smith8110c9d2016-11-29 19:45:17 +00006209 case Builtin::BIwcschr:
6210 case Builtin::BI__builtin_wcschr:
6211 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006212 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006213 case Builtin::BIwmemchr:
6214 case Builtin::BI__builtin_wmemchr:
6215 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6216 DesiredVal = Desired.getZExtValue();
6217 break;
6218 }
Richard Smithe9507952016-11-12 01:39:56 +00006219
6220 for (; MaxLength; --MaxLength) {
6221 APValue Char;
6222 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6223 !Char.isInt())
6224 return false;
6225 if (Char.getInt().getZExtValue() == DesiredVal)
6226 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006227 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006228 break;
6229 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6230 return false;
6231 }
6232 // Not found: return nullptr.
6233 return ZeroInitialization(E);
6234 }
6235
Richard Smith06f71b52018-08-04 00:57:17 +00006236 case Builtin::BImemcpy:
6237 case Builtin::BImemmove:
6238 case Builtin::BIwmemcpy:
6239 case Builtin::BIwmemmove:
6240 if (Info.getLangOpts().CPlusPlus11)
6241 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6242 << /*isConstexpr*/0 << /*isConstructor*/0
6243 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6244 else
6245 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6246 LLVM_FALLTHROUGH;
6247 case Builtin::BI__builtin_memcpy:
6248 case Builtin::BI__builtin_memmove:
6249 case Builtin::BI__builtin_wmemcpy:
6250 case Builtin::BI__builtin_wmemmove: {
6251 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6252 BuiltinOp == Builtin::BIwmemmove ||
6253 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6254 BuiltinOp == Builtin::BI__builtin_wmemmove;
6255 bool Move = BuiltinOp == Builtin::BImemmove ||
6256 BuiltinOp == Builtin::BIwmemmove ||
6257 BuiltinOp == Builtin::BI__builtin_memmove ||
6258 BuiltinOp == Builtin::BI__builtin_wmemmove;
6259
6260 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00006261 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00006262 return false;
6263 LValue Dest = Result;
6264
6265 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00006266 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00006267 return false;
6268
6269 APSInt N;
6270 if (!EvaluateInteger(E->getArg(2), N, Info))
6271 return false;
6272 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6273
6274 // If the size is zero, we treat this as always being a valid no-op.
6275 // (Even if one of the src and dest pointers is null.)
6276 if (!N)
6277 return true;
6278
Richard Smith128719c2018-09-13 22:47:33 +00006279 // Otherwise, if either of the operands is null, we can't proceed. Don't
6280 // try to determine the type of the copied objects, because there aren't
6281 // any.
6282 if (!Src.Base || !Dest.Base) {
6283 APValue Val;
6284 (!Src.Base ? Src : Dest).moveInto(Val);
6285 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6286 << Move << WChar << !!Src.Base
6287 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6288 return false;
6289 }
6290 if (Src.Designator.Invalid || Dest.Designator.Invalid)
6291 return false;
6292
Richard Smith06f71b52018-08-04 00:57:17 +00006293 // We require that Src and Dest are both pointers to arrays of
6294 // trivially-copyable type. (For the wide version, the designator will be
6295 // invalid if the designated object is not a wchar_t.)
6296 QualType T = Dest.Designator.getType(Info.Ctx);
6297 QualType SrcT = Src.Designator.getType(Info.Ctx);
6298 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6299 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6300 return false;
6301 }
Petr Pavlued083f22018-10-04 09:25:44 +00006302 if (T->isIncompleteType()) {
6303 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6304 return false;
6305 }
Richard Smith06f71b52018-08-04 00:57:17 +00006306 if (!T.isTriviallyCopyableType(Info.Ctx)) {
6307 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6308 return false;
6309 }
6310
6311 // Figure out how many T's we're copying.
6312 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6313 if (!WChar) {
6314 uint64_t Remainder;
6315 llvm::APInt OrigN = N;
6316 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6317 if (Remainder) {
6318 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6319 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6320 << (unsigned)TSize;
6321 return false;
6322 }
6323 }
6324
6325 // Check that the copying will remain within the arrays, just so that we
6326 // can give a more meaningful diagnostic. This implicitly also checks that
6327 // N fits into 64 bits.
6328 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6329 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6330 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6331 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6332 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6333 << N.toString(10, /*Signed*/false);
6334 return false;
6335 }
6336 uint64_t NElems = N.getZExtValue();
6337 uint64_t NBytes = NElems * TSize;
6338
6339 // Check for overlap.
6340 int Direction = 1;
6341 if (HasSameBase(Src, Dest)) {
6342 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6343 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6344 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6345 // Dest is inside the source region.
6346 if (!Move) {
6347 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6348 return false;
6349 }
6350 // For memmove and friends, copy backwards.
6351 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6352 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6353 return false;
6354 Direction = -1;
6355 } else if (!Move && SrcOffset >= DestOffset &&
6356 SrcOffset - DestOffset < NBytes) {
6357 // Src is inside the destination region for memcpy: invalid.
6358 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6359 return false;
6360 }
6361 }
6362
6363 while (true) {
6364 APValue Val;
6365 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6366 !handleAssignment(Info, E, Dest, T, Val))
6367 return false;
6368 // Do not iterate past the last element; if we're copying backwards, that
6369 // might take us off the start of the array.
6370 if (--NElems == 0)
6371 return true;
6372 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6373 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6374 return false;
6375 }
6376 }
6377
Richard Smith6cbd65d2013-07-11 02:27:57 +00006378 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006379 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006380 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006381}
Chris Lattner05706e882008-07-11 18:11:29 +00006382
6383//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006384// Member Pointer Evaluation
6385//===----------------------------------------------------------------------===//
6386
6387namespace {
6388class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006389 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006390 MemberPtr &Result;
6391
6392 bool Success(const ValueDecl *D) {
6393 Result = MemberPtr(D);
6394 return true;
6395 }
6396public:
6397
6398 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6399 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6400
Richard Smith2e312c82012-03-03 22:46:17 +00006401 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006402 Result.setFrom(V);
6403 return true;
6404 }
Richard Smithfddd3842011-12-30 21:15:51 +00006405 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006406 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006407 }
6408
6409 bool VisitCastExpr(const CastExpr *E);
6410 bool VisitUnaryAddrOf(const UnaryOperator *E);
6411};
6412} // end anonymous namespace
6413
6414static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6415 EvalInfo &Info) {
6416 assert(E->isRValue() && E->getType()->isMemberPointerType());
6417 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6418}
6419
6420bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6421 switch (E->getCastKind()) {
6422 default:
6423 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6424
6425 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006426 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006427 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006428
6429 case CK_BaseToDerivedMemberPointer: {
6430 if (!Visit(E->getSubExpr()))
6431 return false;
6432 if (E->path_empty())
6433 return true;
6434 // Base-to-derived member pointer casts store the path in derived-to-base
6435 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6436 // the wrong end of the derived->base arc, so stagger the path by one class.
6437 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6438 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6439 PathI != PathE; ++PathI) {
6440 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6441 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6442 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006443 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006444 }
6445 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6446 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006447 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006448 return true;
6449 }
6450
6451 case CK_DerivedToBaseMemberPointer:
6452 if (!Visit(E->getSubExpr()))
6453 return false;
6454 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6455 PathE = E->path_end(); PathI != PathE; ++PathI) {
6456 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6457 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6458 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006459 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006460 }
6461 return true;
6462 }
6463}
6464
6465bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6466 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6467 // member can be formed.
6468 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6469}
6470
6471//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006472// Record Evaluation
6473//===----------------------------------------------------------------------===//
6474
6475namespace {
6476 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006477 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006478 const LValue &This;
6479 APValue &Result;
6480 public:
6481
6482 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6483 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6484
Richard Smith2e312c82012-03-03 22:46:17 +00006485 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006486 Result = V;
6487 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006488 }
Richard Smithb8348f52016-05-12 22:16:28 +00006489 bool ZeroInitialization(const Expr *E) {
6490 return ZeroInitialization(E, E->getType());
6491 }
6492 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006493
Richard Smith52a980a2015-08-28 02:43:42 +00006494 bool VisitCallExpr(const CallExpr *E) {
6495 return handleCallExpr(E, Result, &This);
6496 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006497 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006498 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006499 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6500 return VisitCXXConstructExpr(E, E->getType());
6501 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006502 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006503 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006504 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006505 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006506
6507 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006508 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006509}
Richard Smithd62306a2011-11-10 06:34:14 +00006510
Richard Smithfddd3842011-12-30 21:15:51 +00006511/// Perform zero-initialization on an object of non-union class type.
6512/// C++11 [dcl.init]p5:
6513/// To zero-initialize an object or reference of type T means:
6514/// [...]
6515/// -- if T is a (possibly cv-qualified) non-union class type,
6516/// each non-static data member and each base-class subobject is
6517/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006518static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6519 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006520 const LValue &This, APValue &Result) {
6521 assert(!RD->isUnion() && "Expected non-union class type");
6522 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6523 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006524 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006525
John McCalld7bca762012-05-01 00:38:49 +00006526 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006527 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6528
6529 if (CD) {
6530 unsigned Index = 0;
6531 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006532 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006533 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6534 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006535 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6536 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006537 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006538 Result.getStructBase(Index)))
6539 return false;
6540 }
6541 }
6542
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006543 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006544 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006545 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006546 continue;
6547
6548 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006549 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006550 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006551
David Blaikie2d7c57e2012-04-30 02:36:29 +00006552 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006553 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006554 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006555 return false;
6556 }
6557
6558 return true;
6559}
6560
Richard Smithb8348f52016-05-12 22:16:28 +00006561bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6562 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006563 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006564 if (RD->isUnion()) {
6565 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6566 // object's first non-static named data member is zero-initialized
6567 RecordDecl::field_iterator I = RD->field_begin();
6568 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006569 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006570 return true;
6571 }
6572
6573 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006574 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006575 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006576 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006577 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006578 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006579 }
6580
Richard Smith5d108602012-02-17 00:44:16 +00006581 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006582 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006583 return false;
6584 }
6585
Richard Smitha8105bc2012-01-06 16:39:00 +00006586 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006587}
6588
Richard Smithe97cbd72011-11-11 04:05:33 +00006589bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6590 switch (E->getCastKind()) {
6591 default:
6592 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6593
6594 case CK_ConstructorConversion:
6595 return Visit(E->getSubExpr());
6596
6597 case CK_DerivedToBase:
6598 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006599 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006600 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006601 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006602 if (!DerivedObject.isStruct())
6603 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006604
6605 // Derived-to-base rvalue conversion: just slice off the derived part.
6606 APValue *Value = &DerivedObject;
6607 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6608 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6609 PathE = E->path_end(); PathI != PathE; ++PathI) {
6610 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6611 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6612 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6613 RD = Base;
6614 }
6615 Result = *Value;
6616 return true;
6617 }
6618 }
6619}
6620
Richard Smithd62306a2011-11-10 06:34:14 +00006621bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006622 if (E->isTransparent())
6623 return Visit(E->getInit(0));
6624
Richard Smithd62306a2011-11-10 06:34:14 +00006625 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006626 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006627 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6628
6629 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006630 const FieldDecl *Field = E->getInitializedFieldInUnion();
6631 Result = APValue(Field);
6632 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006633 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006634
6635 // If the initializer list for a union does not contain any elements, the
6636 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006637 // FIXME: The element should be initialized from an initializer list.
6638 // Is this difference ever observable for initializer lists which
6639 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006640 ImplicitValueInitExpr VIE(Field->getType());
6641 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6642
Richard Smithd62306a2011-11-10 06:34:14 +00006643 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006644 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6645 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006646
6647 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6648 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6649 isa<CXXDefaultInitExpr>(InitExpr));
6650
Richard Smithb228a862012-02-15 02:18:13 +00006651 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006652 }
6653
Richard Smith872307e2016-03-08 22:17:41 +00006654 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006655 if (Result.isUninit())
6656 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6657 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006658 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006659 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006660
6661 // Initialize base classes.
6662 if (CXXRD) {
6663 for (const auto &Base : CXXRD->bases()) {
6664 assert(ElementNo < E->getNumInits() && "missing init for base class");
6665 const Expr *Init = E->getInit(ElementNo);
6666
6667 LValue Subobject = This;
6668 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6669 return false;
6670
6671 APValue &FieldVal = Result.getStructBase(ElementNo);
6672 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006673 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006674 return false;
6675 Success = false;
6676 }
6677 ++ElementNo;
6678 }
6679 }
6680
6681 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006682 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006683 // Anonymous bit-fields are not considered members of the class for
6684 // purposes of aggregate initialization.
6685 if (Field->isUnnamedBitfield())
6686 continue;
6687
6688 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006689
Richard Smith253c2a32012-01-27 01:14:48 +00006690 bool HaveInit = ElementNo < E->getNumInits();
6691
6692 // FIXME: Diagnostics here should point to the end of the initializer
6693 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006694 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006695 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006696 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006697
6698 // Perform an implicit value-initialization for members beyond the end of
6699 // the initializer list.
6700 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006701 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006702
Richard Smith852c9db2013-04-20 22:23:05 +00006703 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6704 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6705 isa<CXXDefaultInitExpr>(Init));
6706
Richard Smith49ca8aa2013-08-06 07:09:20 +00006707 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6708 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6709 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006710 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006711 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006712 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006713 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006714 }
6715 }
6716
Richard Smith253c2a32012-01-27 01:14:48 +00006717 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006718}
6719
Richard Smithb8348f52016-05-12 22:16:28 +00006720bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6721 QualType T) {
6722 // Note that E's type is not necessarily the type of our class here; we might
6723 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006724 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006725 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6726
Richard Smithfddd3842011-12-30 21:15:51 +00006727 bool ZeroInit = E->requiresZeroInitialization();
6728 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006729 // If we've already performed zero-initialization, we're already done.
6730 if (!Result.isUninit())
6731 return true;
6732
Richard Smithda3f4fd2014-03-05 23:32:50 +00006733 // We can get here in two different ways:
6734 // 1) We're performing value-initialization, and should zero-initialize
6735 // the object, or
6736 // 2) We're performing default-initialization of an object with a trivial
6737 // constexpr default constructor, in which case we should start the
6738 // lifetimes of all the base subobjects (there can be no data member
6739 // subobjects in this case) per [basic.life]p1.
6740 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006741 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006742 }
6743
Craig Topper36250ad2014-05-12 05:36:57 +00006744 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006745 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006746
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006747 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006748 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006749
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006750 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006751 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006752 if (const MaterializeTemporaryExpr *ME
6753 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6754 return Visit(ME->GetTemporaryExpr());
6755
Richard Smithb8348f52016-05-12 22:16:28 +00006756 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006757 return false;
6758
Craig Topper5fc8fc22014-08-27 06:28:36 +00006759 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006760 return HandleConstructorCall(E, This, Args,
6761 cast<CXXConstructorDecl>(Definition), Info,
6762 Result);
6763}
6764
6765bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6766 const CXXInheritedCtorInitExpr *E) {
6767 if (!Info.CurrentCall) {
6768 assert(Info.checkingPotentialConstantExpression());
6769 return false;
6770 }
6771
6772 const CXXConstructorDecl *FD = E->getConstructor();
6773 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6774 return false;
6775
6776 const FunctionDecl *Definition = nullptr;
6777 auto Body = FD->getBody(Definition);
6778
6779 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6780 return false;
6781
6782 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006783 cast<CXXConstructorDecl>(Definition), Info,
6784 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006785}
6786
Richard Smithcc1b96d2013-06-12 22:31:48 +00006787bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6788 const CXXStdInitializerListExpr *E) {
6789 const ConstantArrayType *ArrayType =
6790 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6791
6792 LValue Array;
6793 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6794 return false;
6795
6796 // Get a pointer to the first element of the array.
6797 Array.addArray(Info, E, ArrayType);
6798
6799 // FIXME: Perform the checks on the field types in SemaInit.
6800 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6801 RecordDecl::field_iterator Field = Record->field_begin();
6802 if (Field == Record->field_end())
6803 return Error(E);
6804
6805 // Start pointer.
6806 if (!Field->getType()->isPointerType() ||
6807 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6808 ArrayType->getElementType()))
6809 return Error(E);
6810
6811 // FIXME: What if the initializer_list type has base classes, etc?
6812 Result = APValue(APValue::UninitStruct(), 0, 2);
6813 Array.moveInto(Result.getStructField(0));
6814
6815 if (++Field == Record->field_end())
6816 return Error(E);
6817
6818 if (Field->getType()->isPointerType() &&
6819 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6820 ArrayType->getElementType())) {
6821 // End pointer.
6822 if (!HandleLValueArrayAdjustment(Info, E, Array,
6823 ArrayType->getElementType(),
6824 ArrayType->getSize().getZExtValue()))
6825 return false;
6826 Array.moveInto(Result.getStructField(1));
6827 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6828 // Length.
6829 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6830 else
6831 return Error(E);
6832
6833 if (++Field != Record->field_end())
6834 return Error(E);
6835
6836 return true;
6837}
6838
Faisal Valic72a08c2017-01-09 03:02:53 +00006839bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6840 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6841 if (ClosureClass->isInvalidDecl()) return false;
6842
6843 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00006844
Faisal Vali051e3a22017-02-16 04:12:21 +00006845 const size_t NumFields =
6846 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006847
6848 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6849 E->capture_init_end()) &&
6850 "The number of lambda capture initializers should equal the number of "
6851 "fields within the closure type");
6852
Faisal Vali051e3a22017-02-16 04:12:21 +00006853 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6854 // Iterate through all the lambda's closure object's fields and initialize
6855 // them.
6856 auto *CaptureInitIt = E->capture_init_begin();
6857 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6858 bool Success = true;
6859 for (const auto *Field : ClosureClass->fields()) {
6860 assert(CaptureInitIt != E->capture_init_end());
6861 // Get the initializer for this field
6862 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00006863
Faisal Vali051e3a22017-02-16 04:12:21 +00006864 // If there is no initializer, either this is a VLA or an error has
6865 // occurred.
6866 if (!CurFieldInit)
6867 return Error(E);
6868
6869 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6870 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6871 if (!Info.keepEvaluatingAfterFailure())
6872 return false;
6873 Success = false;
6874 }
6875 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006876 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006877 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006878}
6879
Richard Smithd62306a2011-11-10 06:34:14 +00006880static bool EvaluateRecord(const Expr *E, const LValue &This,
6881 APValue &Result, EvalInfo &Info) {
6882 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006883 "can't evaluate expression as a record rvalue");
6884 return RecordExprEvaluator(Info, This, Result).Visit(E);
6885}
6886
6887//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006888// Temporary Evaluation
6889//
6890// Temporaries are represented in the AST as rvalues, but generally behave like
6891// lvalues. The full-object of which the temporary is a subobject is implicitly
6892// materialized so that a reference can bind to it.
6893//===----------------------------------------------------------------------===//
6894namespace {
6895class TemporaryExprEvaluator
6896 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6897public:
6898 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006899 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006900
6901 /// Visit an expression which constructs the value of this temporary.
6902 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006903 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6904 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006905 }
6906
6907 bool VisitCastExpr(const CastExpr *E) {
6908 switch (E->getCastKind()) {
6909 default:
6910 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6911
6912 case CK_ConstructorConversion:
6913 return VisitConstructExpr(E->getSubExpr());
6914 }
6915 }
6916 bool VisitInitListExpr(const InitListExpr *E) {
6917 return VisitConstructExpr(E);
6918 }
6919 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6920 return VisitConstructExpr(E);
6921 }
6922 bool VisitCallExpr(const CallExpr *E) {
6923 return VisitConstructExpr(E);
6924 }
Richard Smith513955c2014-12-17 19:24:30 +00006925 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6926 return VisitConstructExpr(E);
6927 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006928 bool VisitLambdaExpr(const LambdaExpr *E) {
6929 return VisitConstructExpr(E);
6930 }
Richard Smith027bf112011-11-17 22:56:20 +00006931};
6932} // end anonymous namespace
6933
6934/// Evaluate an expression of record type as a temporary.
6935static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006936 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006937 return TemporaryExprEvaluator(Info, Result).Visit(E);
6938}
6939
6940//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006941// Vector Evaluation
6942//===----------------------------------------------------------------------===//
6943
6944namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006945 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006946 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006947 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006948 public:
Mike Stump11289f42009-09-09 15:08:12 +00006949
Richard Smith2d406342011-10-22 21:10:00 +00006950 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6951 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006952
Craig Topper9798b932015-09-29 04:30:05 +00006953 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006954 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6955 // FIXME: remove this APValue copy.
6956 Result = APValue(V.data(), V.size());
6957 return true;
6958 }
Richard Smith2e312c82012-03-03 22:46:17 +00006959 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006960 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006961 Result = V;
6962 return true;
6963 }
Richard Smithfddd3842011-12-30 21:15:51 +00006964 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006965
Richard Smith2d406342011-10-22 21:10:00 +00006966 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006967 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006968 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006969 bool VisitInitListExpr(const InitListExpr *E);
6970 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006971 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006972 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006973 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006974 };
6975} // end anonymous namespace
6976
6977static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006978 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006979 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006980}
6981
George Burgess IV533ff002015-12-11 00:23:35 +00006982bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006983 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006984 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006985
Richard Smith161f09a2011-12-06 22:44:34 +00006986 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006987 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006988
Eli Friedmanc757de22011-03-25 00:43:55 +00006989 switch (E->getCastKind()) {
6990 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006991 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006992 if (SETy->isIntegerType()) {
6993 APSInt IntResult;
6994 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006995 return false;
6996 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006997 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006998 APFloat FloatResult(0.0);
6999 if (!EvaluateFloat(SE, FloatResult, Info))
7000 return false;
7001 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00007002 } else {
Richard Smith2d406342011-10-22 21:10:00 +00007003 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007004 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00007005
7006 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00007007 SmallVector<APValue, 4> Elts(NElts, Val);
7008 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00007009 }
Eli Friedman803acb32011-12-22 03:51:45 +00007010 case CK_BitCast: {
7011 // Evaluate the operand into an APInt we can extract from.
7012 llvm::APInt SValInt;
7013 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
7014 return false;
7015 // Extract the elements
7016 QualType EltTy = VTy->getElementType();
7017 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
7018 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7019 SmallVector<APValue, 4> Elts;
7020 if (EltTy->isRealFloatingType()) {
7021 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00007022 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00007023 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00007024 FloatEltSize = 80;
7025 for (unsigned i = 0; i < NElts; i++) {
7026 llvm::APInt Elt;
7027 if (BigEndian)
7028 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
7029 else
7030 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00007031 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00007032 }
7033 } else if (EltTy->isIntegerType()) {
7034 for (unsigned i = 0; i < NElts; i++) {
7035 llvm::APInt Elt;
7036 if (BigEndian)
7037 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
7038 else
7039 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
7040 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
7041 }
7042 } else {
7043 return Error(E);
7044 }
7045 return Success(Elts, E);
7046 }
Eli Friedmanc757de22011-03-25 00:43:55 +00007047 default:
Richard Smith11562c52011-10-28 17:51:58 +00007048 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007049 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007050}
7051
Richard Smith2d406342011-10-22 21:10:00 +00007052bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007053VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007054 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007055 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00007056 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007057
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007058 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007059 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007060
Eli Friedmanb9c71292012-01-03 23:24:20 +00007061 // The number of initializers can be less than the number of
7062 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00007063 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00007064 // should be initialized with zeroes.
7065 unsigned CountInits = 0, CountElts = 0;
7066 while (CountElts < NumElements) {
7067 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00007068 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00007069 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00007070 APValue v;
7071 if (!EvaluateVector(E->getInit(CountInits), v, Info))
7072 return Error(E);
7073 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00007074 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00007075 Elements.push_back(v.getVectorElt(j));
7076 CountElts += vlen;
7077 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007078 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007079 if (CountInits < NumInits) {
7080 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007081 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007082 } else // trailing integer zero.
7083 sInt = Info.Ctx.MakeIntValue(0, EltTy);
7084 Elements.push_back(APValue(sInt));
7085 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007086 } else {
7087 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007088 if (CountInits < NumInits) {
7089 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007090 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007091 } else // trailing float zero.
7092 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7093 Elements.push_back(APValue(f));
7094 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00007095 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00007096 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007097 }
Richard Smith2d406342011-10-22 21:10:00 +00007098 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007099}
7100
Richard Smith2d406342011-10-22 21:10:00 +00007101bool
Richard Smithfddd3842011-12-30 21:15:51 +00007102VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007103 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00007104 QualType EltTy = VT->getElementType();
7105 APValue ZeroElement;
7106 if (EltTy->isIntegerType())
7107 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7108 else
7109 ZeroElement =
7110 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7111
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007112 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00007113 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007114}
7115
Richard Smith2d406342011-10-22 21:10:00 +00007116bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00007117 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007118 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007119}
7120
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007121//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00007122// Array Evaluation
7123//===----------------------------------------------------------------------===//
7124
7125namespace {
7126 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007127 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007128 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00007129 APValue &Result;
7130 public:
7131
Richard Smithd62306a2011-11-10 06:34:14 +00007132 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7133 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00007134
7135 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00007136 assert((V.isArray() || V.isLValue()) &&
7137 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00007138 Result = V;
7139 return true;
7140 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007141
Richard Smithfddd3842011-12-30 21:15:51 +00007142 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007143 const ConstantArrayType *CAT =
7144 Info.Ctx.getAsConstantArrayType(E->getType());
7145 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007146 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007147
7148 Result = APValue(APValue::UninitArray(), 0,
7149 CAT->getSize().getZExtValue());
7150 if (!Result.hasArrayFiller()) return true;
7151
Richard Smithfddd3842011-12-30 21:15:51 +00007152 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00007153 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007154 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00007155 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00007156 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00007157 }
7158
Richard Smith52a980a2015-08-28 02:43:42 +00007159 bool VisitCallExpr(const CallExpr *E) {
7160 return handleCallExpr(E, Result, &This);
7161 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007162 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00007163 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00007164 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00007165 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7166 const LValue &Subobject,
7167 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00007168 };
7169} // end anonymous namespace
7170
Richard Smithd62306a2011-11-10 06:34:14 +00007171static bool EvaluateArray(const Expr *E, const LValue &This,
7172 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00007173 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00007174 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007175}
7176
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007177// Return true iff the given array filler may depend on the element index.
7178static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7179 // For now, just whitelist non-class value-initialization and initialization
7180 // lists comprised of them.
7181 if (isa<ImplicitValueInitExpr>(FillerExpr))
7182 return false;
7183 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7184 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7185 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7186 return true;
7187 }
7188 return false;
7189 }
7190 return true;
7191}
7192
Richard Smithf3e9e432011-11-07 09:22:26 +00007193bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7194 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7195 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007196 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007197
Richard Smithca2cfbf2011-12-22 01:07:19 +00007198 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7199 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00007200 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00007201 LValue LV;
7202 if (!EvaluateLValue(E->getInit(0), LV, Info))
7203 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007204 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00007205 LV.moveInto(Val);
7206 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00007207 }
7208
Richard Smith253c2a32012-01-27 01:14:48 +00007209 bool Success = true;
7210
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007211 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7212 "zero-initialized array shouldn't have any initialized elts");
7213 APValue Filler;
7214 if (Result.isArray() && Result.hasArrayFiller())
7215 Filler = Result.getArrayFiller();
7216
Richard Smith9543c5e2013-04-22 14:44:29 +00007217 unsigned NumEltsToInit = E->getNumInits();
7218 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007219 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00007220
7221 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007222 // array element.
7223 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00007224 NumEltsToInit = NumElts;
7225
Nicola Zaghen3538b392018-05-15 13:30:56 +00007226 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7227 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007228
Richard Smith9543c5e2013-04-22 14:44:29 +00007229 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007230
7231 // If the array was previously zero-initialized, preserve the
7232 // zero-initialized values.
7233 if (!Filler.isUninit()) {
7234 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7235 Result.getArrayInitializedElt(I) = Filler;
7236 if (Result.hasArrayFiller())
7237 Result.getArrayFiller() = Filler;
7238 }
7239
Richard Smithd62306a2011-11-10 06:34:14 +00007240 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007241 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00007242 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7243 const Expr *Init =
7244 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00007245 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00007246 Info, Subobject, Init) ||
7247 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00007248 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007249 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00007250 return false;
7251 Success = false;
7252 }
Richard Smithd62306a2011-11-10 06:34:14 +00007253 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007254
Richard Smith9543c5e2013-04-22 14:44:29 +00007255 if (!Result.hasArrayFiller())
7256 return Success;
7257
7258 // If we get here, we have a trivial filler, which we can just evaluate
7259 // once and splat over the rest of the array elements.
7260 assert(FillerExpr && "no array filler for incomplete init list");
7261 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7262 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00007263}
7264
Richard Smith410306b2016-12-12 02:53:20 +00007265bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7266 if (E->getCommonExpr() &&
7267 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7268 Info, E->getCommonExpr()->getSourceExpr()))
7269 return false;
7270
7271 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7272
7273 uint64_t Elements = CAT->getSize().getZExtValue();
7274 Result = APValue(APValue::UninitArray(), Elements, Elements);
7275
7276 LValue Subobject = This;
7277 Subobject.addArray(Info, E, CAT);
7278
7279 bool Success = true;
7280 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7281 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7282 Info, Subobject, E->getSubExpr()) ||
7283 !HandleLValueArrayAdjustment(Info, E, Subobject,
7284 CAT->getElementType(), 1)) {
7285 if (!Info.noteFailure())
7286 return false;
7287 Success = false;
7288 }
7289 }
7290
7291 return Success;
7292}
7293
Richard Smith027bf112011-11-17 22:56:20 +00007294bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00007295 return VisitCXXConstructExpr(E, This, &Result, E->getType());
7296}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007297
Richard Smith9543c5e2013-04-22 14:44:29 +00007298bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7299 const LValue &Subobject,
7300 APValue *Value,
7301 QualType Type) {
7302 bool HadZeroInit = !Value->isUninit();
7303
7304 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7305 unsigned N = CAT->getSize().getZExtValue();
7306
7307 // Preserve the array filler if we had prior zero-initialization.
7308 APValue Filler =
7309 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7310 : APValue();
7311
7312 *Value = APValue(APValue::UninitArray(), N, N);
7313
7314 if (HadZeroInit)
7315 for (unsigned I = 0; I != N; ++I)
7316 Value->getArrayInitializedElt(I) = Filler;
7317
7318 // Initialize the elements.
7319 LValue ArrayElt = Subobject;
7320 ArrayElt.addArray(Info, E, CAT);
7321 for (unsigned I = 0; I != N; ++I)
7322 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7323 CAT->getElementType()) ||
7324 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7325 CAT->getElementType(), 1))
7326 return false;
7327
7328 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007329 }
Richard Smith027bf112011-11-17 22:56:20 +00007330
Richard Smith9543c5e2013-04-22 14:44:29 +00007331 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00007332 return Error(E);
7333
Richard Smithb8348f52016-05-12 22:16:28 +00007334 return RecordExprEvaluator(Info, Subobject, *Value)
7335 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00007336}
7337
Richard Smithf3e9e432011-11-07 09:22:26 +00007338//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007339// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007340//
7341// As a GNU extension, we support casting pointers to sufficiently-wide integer
7342// types and back in constant folding. Integer values are thus represented
7343// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00007344//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007345
7346namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007347class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007348 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00007349 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007350public:
Richard Smith2e312c82012-03-03 22:46:17 +00007351 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007352 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007353
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007354 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007355 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007356 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007357 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007358 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007359 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007360 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007361 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007362 return true;
7363 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007364 bool Success(const llvm::APSInt &SI, const Expr *E) {
7365 return Success(SI, E, Result);
7366 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007367
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007368 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007369 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007370 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007371 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007372 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007373 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007374 Result.getInt().setIsUnsigned(
7375 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007376 return true;
7377 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007378 bool Success(const llvm::APInt &I, const Expr *E) {
7379 return Success(I, E, Result);
7380 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007381
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007382 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007383 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007384 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007385 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007386 return true;
7387 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007388 bool Success(uint64_t Value, const Expr *E) {
7389 return Success(Value, E, Result);
7390 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007391
Ken Dyckdbc01912011-03-11 02:13:43 +00007392 bool Success(CharUnits Size, const Expr *E) {
7393 return Success(Size.getQuantity(), E);
7394 }
7395
Richard Smith2e312c82012-03-03 22:46:17 +00007396 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007397 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007398 Result = V;
7399 return true;
7400 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007401 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007402 }
Mike Stump11289f42009-09-09 15:08:12 +00007403
Richard Smithfddd3842011-12-30 21:15:51 +00007404 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007405
Peter Collingbournee9200682011-05-13 03:29:01 +00007406 //===--------------------------------------------------------------------===//
7407 // Visitor Methods
7408 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007409
Fangrui Song407659a2018-11-30 23:41:18 +00007410 bool VisitConstantExpr(const ConstantExpr *E);
7411
Chris Lattner7174bf32008-07-12 00:38:25 +00007412 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007413 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007414 }
7415 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007416 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007417 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007418
7419 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7420 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007421 if (CheckReferencedDecl(E, E->getDecl()))
7422 return true;
7423
7424 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007425 }
7426 bool VisitMemberExpr(const MemberExpr *E) {
7427 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007428 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007429 return true;
7430 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007431
7432 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007433 }
7434
Peter Collingbournee9200682011-05-13 03:29:01 +00007435 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007436 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007437 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007438 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007439 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007440
Peter Collingbournee9200682011-05-13 03:29:01 +00007441 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007442 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007443
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007444 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007445 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007446 }
Mike Stump11289f42009-09-09 15:08:12 +00007447
Ted Kremeneke65b0862012-03-06 20:05:56 +00007448 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7449 return Success(E->getValue(), E);
7450 }
Richard Smith410306b2016-12-12 02:53:20 +00007451
7452 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7453 if (Info.ArrayInitIndex == uint64_t(-1)) {
7454 // We were asked to evaluate this subexpression independent of the
7455 // enclosing ArrayInitLoopExpr. We can't do that.
7456 Info.FFDiag(E);
7457 return false;
7458 }
7459 return Success(Info.ArrayInitIndex, E);
7460 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007461
Richard Smith4ce706a2011-10-11 21:43:33 +00007462 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007463 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007464 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007465 }
7466
Douglas Gregor29c42f22012-02-24 07:38:34 +00007467 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7468 return Success(E->getValue(), E);
7469 }
7470
John Wiegley6242b6a2011-04-28 00:16:57 +00007471 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7472 return Success(E->getValue(), E);
7473 }
7474
John Wiegleyf9f65842011-04-25 06:54:41 +00007475 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7476 return Success(E->getValue(), E);
7477 }
7478
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007479 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007480 bool VisitUnaryImag(const UnaryOperator *E);
7481
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007482 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007483 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007484
Eli Friedman4e7a2412009-02-27 04:45:43 +00007485 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007486};
Leonard Chandb01c3a2018-06-20 17:19:40 +00007487
7488class FixedPointExprEvaluator
7489 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
7490 APValue &Result;
7491
7492 public:
7493 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
7494 : ExprEvaluatorBaseTy(info), Result(result) {}
7495
7496 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7497 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7498 assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
7499 "Invalid evaluation result.");
7500 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7501 "Invalid evaluation result.");
7502 Result = APValue(SI);
7503 return true;
7504 }
7505 bool Success(const llvm::APSInt &SI, const Expr *E) {
7506 return Success(SI, E, Result);
7507 }
7508
7509 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7510 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7511 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7512 "Invalid evaluation result.");
7513 Result = APValue(APSInt(I));
7514 Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
7515 return true;
7516 }
7517 bool Success(const llvm::APInt &I, const Expr *E) {
7518 return Success(I, E, Result);
7519 }
7520
7521 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7522 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7523 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7524 return true;
7525 }
7526 bool Success(uint64_t Value, const Expr *E) {
7527 return Success(Value, E, Result);
7528 }
7529
7530 bool Success(CharUnits Size, const Expr *E) {
7531 return Success(Size.getQuantity(), E);
7532 }
7533
7534 bool Success(const APValue &V, const Expr *E) {
7535 if (V.isLValue() || V.isAddrLabelDiff()) {
7536 Result = V;
7537 return true;
7538 }
7539 return Success(V.getInt(), E);
7540 }
7541
7542 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7543
7544 //===--------------------------------------------------------------------===//
7545 // Visitor Methods
7546 //===--------------------------------------------------------------------===//
7547
7548 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
7549 return Success(E->getValue(), E);
7550 }
7551
7552 bool VisitUnaryOperator(const UnaryOperator *E);
7553};
Chris Lattner05706e882008-07-11 18:11:29 +00007554} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007555
Richard Smith11562c52011-10-28 17:51:58 +00007556/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7557/// produce either the integer value or a pointer.
7558///
7559/// GCC has a heinous extension which folds casts between pointer types and
7560/// pointer-sized integral types. We support this by allowing the evaluation of
7561/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7562/// Some simple arithmetic on such values is supported (they are treated much
7563/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007564static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007565 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007566 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007567 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007568}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007569
Richard Smithf57d8cb2011-12-09 22:58:01 +00007570static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007571 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007572 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007573 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007574 if (!Val.isInt()) {
7575 // FIXME: It would be better to produce the diagnostic for casting
7576 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007577 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007578 return false;
7579 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007580 Result = Val.getInt();
7581 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007582}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007583
Richard Smithf57d8cb2011-12-09 22:58:01 +00007584/// Check whether the given declaration can be directly converted to an integral
7585/// rvalue. If not, no diagnostic is produced; there are other things we can
7586/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007587bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007588 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007589 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007590 // Check for signedness/width mismatches between E type and ECD value.
7591 bool SameSign = (ECD->getInitVal().isSigned()
7592 == E->getType()->isSignedIntegerOrEnumerationType());
7593 bool SameWidth = (ECD->getInitVal().getBitWidth()
7594 == Info.Ctx.getIntWidth(E->getType()));
7595 if (SameSign && SameWidth)
7596 return Success(ECD->getInitVal(), E);
7597 else {
7598 // Get rid of mismatch (otherwise Success assertions will fail)
7599 // by computing a new value matching the type of E.
7600 llvm::APSInt Val = ECD->getInitVal();
7601 if (!SameSign)
7602 Val.setIsSigned(!ECD->getInitVal().isSigned());
7603 if (!SameWidth)
7604 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7605 return Success(Val, E);
7606 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007607 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007608 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007609}
7610
Richard Smith08b682b2018-05-23 21:18:00 +00007611/// Values returned by __builtin_classify_type, chosen to match the values
7612/// produced by GCC's builtin.
7613enum class GCCTypeClass {
7614 None = -1,
7615 Void = 0,
7616 Integer = 1,
7617 // GCC reserves 2 for character types, but instead classifies them as
7618 // integers.
7619 Enum = 3,
7620 Bool = 4,
7621 Pointer = 5,
7622 // GCC reserves 6 for references, but appears to never use it (because
7623 // expressions never have reference type, presumably).
7624 PointerToDataMember = 7,
7625 RealFloat = 8,
7626 Complex = 9,
7627 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7628 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7629 // GCC claims to reserve 11 for pointers to member functions, but *actually*
7630 // uses 12 for that purpose, same as for a class or struct. Maybe it
7631 // internally implements a pointer to member as a struct? Who knows.
7632 PointerToMemberFunction = 12, // Not a bug, see above.
7633 ClassOrStruct = 12,
7634 Union = 13,
7635 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7636 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7637 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7638 // literals.
7639};
7640
Chris Lattner86ee2862008-10-06 06:40:35 +00007641/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7642/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00007643static GCCTypeClass
7644EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7645 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00007646
Richard Smith08b682b2018-05-23 21:18:00 +00007647 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007648 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7649
7650 switch (CanTy->getTypeClass()) {
7651#define TYPE(ID, BASE)
7652#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7653#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7654#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7655#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00007656 case Type::Auto:
7657 case Type::DeducedTemplateSpecialization:
7658 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007659
7660 case Type::Builtin:
7661 switch (BT->getKind()) {
7662#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00007663#define SIGNED_TYPE(ID, SINGLETON_ID) \
7664 case BuiltinType::ID: return GCCTypeClass::Integer;
7665#define FLOATING_TYPE(ID, SINGLETON_ID) \
7666 case BuiltinType::ID: return GCCTypeClass::RealFloat;
7667#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7668 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007669#include "clang/AST/BuiltinTypes.def"
7670 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00007671 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007672
7673 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00007674 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007675
Richard Smith08b682b2018-05-23 21:18:00 +00007676 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007677 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00007678 case BuiltinType::WChar_U:
7679 case BuiltinType::Char8:
7680 case BuiltinType::Char16:
7681 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007682 case BuiltinType::UShort:
7683 case BuiltinType::UInt:
7684 case BuiltinType::ULong:
7685 case BuiltinType::ULongLong:
7686 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00007687 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007688
Leonard Chanf921d852018-06-04 16:07:52 +00007689 case BuiltinType::UShortAccum:
7690 case BuiltinType::UAccum:
7691 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00007692 case BuiltinType::UShortFract:
7693 case BuiltinType::UFract:
7694 case BuiltinType::ULongFract:
7695 case BuiltinType::SatUShortAccum:
7696 case BuiltinType::SatUAccum:
7697 case BuiltinType::SatULongAccum:
7698 case BuiltinType::SatUShortFract:
7699 case BuiltinType::SatUFract:
7700 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00007701 return GCCTypeClass::None;
7702
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007703 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007704
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007705 case BuiltinType::ObjCId:
7706 case BuiltinType::ObjCClass:
7707 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007708#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7709 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007710#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00007711#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7712 case BuiltinType::Id:
7713#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007714 case BuiltinType::OCLSampler:
7715 case BuiltinType::OCLEvent:
7716 case BuiltinType::OCLClkEvent:
7717 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007718 case BuiltinType::OCLReserveID:
Richard Smith08b682b2018-05-23 21:18:00 +00007719 return GCCTypeClass::None;
7720
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007721 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00007722 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007723 };
Richard Smith08b682b2018-05-23 21:18:00 +00007724 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007725
7726 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00007727 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007728
7729 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007730 case Type::ConstantArray:
7731 case Type::VariableArray:
7732 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00007733 case Type::FunctionNoProto:
7734 case Type::FunctionProto:
7735 return GCCTypeClass::Pointer;
7736
7737 case Type::MemberPointer:
7738 return CanTy->isMemberDataPointerType()
7739 ? GCCTypeClass::PointerToDataMember
7740 : GCCTypeClass::PointerToMemberFunction;
7741
7742 case Type::Complex:
7743 return GCCTypeClass::Complex;
7744
7745 case Type::Record:
7746 return CanTy->isUnionType() ? GCCTypeClass::Union
7747 : GCCTypeClass::ClassOrStruct;
7748
7749 case Type::Atomic:
7750 // GCC classifies _Atomic T the same as T.
7751 return EvaluateBuiltinClassifyType(
7752 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007753
7754 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007755 case Type::Vector:
7756 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007757 case Type::ObjCObject:
7758 case Type::ObjCInterface:
7759 case Type::ObjCObjectPointer:
7760 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00007761 // GCC classifies vectors as None. We follow its lead and classify all
7762 // other types that don't fit into the regular classification the same way.
7763 return GCCTypeClass::None;
7764
7765 case Type::LValueReference:
7766 case Type::RValueReference:
7767 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007768 }
7769
Richard Smith08b682b2018-05-23 21:18:00 +00007770 llvm_unreachable("unexpected type class");
7771}
7772
7773/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7774/// as GCC.
7775static GCCTypeClass
7776EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7777 // If no argument was supplied, default to None. This isn't
7778 // ideal, however it is what gcc does.
7779 if (E->getNumArgs() == 0)
7780 return GCCTypeClass::None;
7781
7782 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7783 // being an ICE, but still folds it to a constant using the type of the first
7784 // argument.
7785 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00007786}
7787
Richard Smith5fab0c92011-12-28 19:48:30 +00007788/// EvaluateBuiltinConstantPForLValue - Determine the result of
7789/// __builtin_constant_p when applied to the given lvalue.
7790///
7791/// An lvalue is only "constant" if it is a pointer or reference to the first
7792/// character of a string literal.
7793template<typename LValue>
7794static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007795 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007796 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7797}
7798
7799/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7800/// GCC as we can manage.
7801static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7802 QualType ArgType = Arg->getType();
7803
7804 // __builtin_constant_p always has one operand. The rules which gcc follows
7805 // are not precisely documented, but are as follows:
7806 //
7807 // - If the operand is of integral, floating, complex or enumeration type,
7808 // and can be folded to a known value of that type, it returns 1.
7809 // - If the operand and can be folded to a pointer to the first character
7810 // of a string literal (or such a pointer cast to an integral type), it
7811 // returns 1.
7812 //
7813 // Otherwise, it returns 0.
7814 //
7815 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7816 // its support for this does not currently work.
7817 if (ArgType->isIntegralOrEnumerationType()) {
7818 Expr::EvalResult Result;
7819 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7820 return false;
7821
7822 APValue &V = Result.Val;
7823 if (V.getKind() == APValue::Int)
7824 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007825 if (V.getKind() == APValue::LValue)
7826 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007827 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7828 return Arg->isEvaluatable(Ctx);
7829 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7830 LValue LV;
7831 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007832 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007833 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7834 : EvaluatePointer(Arg, LV, Info)) &&
7835 !Status.HasSideEffects)
7836 return EvaluateBuiltinConstantPForLValue(LV);
7837 }
7838
7839 // Anything else isn't considered to be sufficiently constant.
7840 return false;
7841}
7842
John McCall95007602010-05-10 23:27:23 +00007843/// Retrieves the "underlying object type" of the given expression,
7844/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007845static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007846 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7847 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007848 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007849 } else if (const Expr *E = B.get<const Expr*>()) {
7850 if (isa<CompoundLiteralExpr>(E))
7851 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007852 }
7853
7854 return QualType();
7855}
7856
George Burgess IV3a03fab2015-09-04 21:28:13 +00007857/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007858/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007859/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007860/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7861///
7862/// Always returns an RValue with a pointer representation.
7863static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7864 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7865
7866 auto *NoParens = E->IgnoreParens();
7867 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007868 if (Cast == nullptr)
7869 return NoParens;
7870
7871 // We only conservatively allow a few kinds of casts, because this code is
7872 // inherently a simple solution that seeks to support the common case.
7873 auto CastKind = Cast->getCastKind();
7874 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7875 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007876 return NoParens;
7877
7878 auto *SubExpr = Cast->getSubExpr();
7879 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7880 return NoParens;
7881 return ignorePointerCastsAndParens(SubExpr);
7882}
7883
George Burgess IVa51c4072015-10-16 01:49:01 +00007884/// Checks to see if the given LValue's Designator is at the end of the LValue's
7885/// record layout. e.g.
7886/// struct { struct { int a, b; } fst, snd; } obj;
7887/// obj.fst // no
7888/// obj.snd // yes
7889/// obj.fst.a // no
7890/// obj.fst.b // no
7891/// obj.snd.a // no
7892/// obj.snd.b // yes
7893///
7894/// Please note: this function is specialized for how __builtin_object_size
7895/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007896///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007897/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7898/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007899static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7900 assert(!LVal.Designator.Invalid);
7901
George Burgess IV4168d752016-06-27 19:40:41 +00007902 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7903 const RecordDecl *Parent = FD->getParent();
7904 Invalid = Parent->isInvalidDecl();
7905 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007906 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007907 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007908 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7909 };
7910
7911 auto &Base = LVal.getLValueBase();
7912 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7913 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007914 bool Invalid;
7915 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7916 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007917 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007918 for (auto *FD : IFD->chain()) {
7919 bool Invalid;
7920 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7921 return Invalid;
7922 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007923 }
7924 }
7925
George Burgess IVe3763372016-12-22 02:50:20 +00007926 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007927 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007928 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007929 // If we don't know the array bound, conservatively assume we're looking at
7930 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007931 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007932 if (BaseType->isIncompleteArrayType())
7933 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7934 else
7935 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007936 }
7937
7938 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7939 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007940 if (BaseType->isArrayType()) {
7941 // Because __builtin_object_size treats arrays as objects, we can ignore
7942 // the index iff this is the last array in the Designator.
7943 if (I + 1 == E)
7944 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007945 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7946 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007947 if (Index + 1 != CAT->getSize())
7948 return false;
7949 BaseType = CAT->getElementType();
7950 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007951 const auto *CT = BaseType->castAs<ComplexType>();
7952 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007953 if (Index != 1)
7954 return false;
7955 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007956 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007957 bool Invalid;
7958 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7959 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007960 BaseType = FD->getType();
7961 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007962 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007963 return false;
7964 }
7965 }
7966 return true;
7967}
7968
George Burgess IVe3763372016-12-22 02:50:20 +00007969/// Tests to see if the LValue has a user-specified designator (that isn't
7970/// necessarily valid). Note that this always returns 'true' if the LValue has
7971/// an unsized array as its first designator entry, because there's currently no
7972/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007973static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007974 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007975 return false;
7976
George Burgess IVe3763372016-12-22 02:50:20 +00007977 if (!LVal.Designator.Entries.empty())
7978 return LVal.Designator.isMostDerivedAnUnsizedArray();
7979
George Burgess IVa51c4072015-10-16 01:49:01 +00007980 if (!LVal.InvalidBase)
7981 return true;
7982
George Burgess IVe3763372016-12-22 02:50:20 +00007983 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7984 // the LValueBase.
7985 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7986 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007987}
7988
George Burgess IVe3763372016-12-22 02:50:20 +00007989/// Attempts to detect a user writing into a piece of memory that's impossible
7990/// to figure out the size of by just using types.
7991static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7992 const SubobjectDesignator &Designator = LVal.Designator;
7993 // Notes:
7994 // - Users can only write off of the end when we have an invalid base. Invalid
7995 // bases imply we don't know where the memory came from.
7996 // - We used to be a bit more aggressive here; we'd only be conservative if
7997 // the array at the end was flexible, or if it had 0 or 1 elements. This
7998 // broke some common standard library extensions (PR30346), but was
7999 // otherwise seemingly fine. It may be useful to reintroduce this behavior
8000 // with some sort of whitelist. OTOH, it seems that GCC is always
8001 // conservative with the last element in structs (if it's an array), so our
8002 // current behavior is more compatible than a whitelisting approach would
8003 // be.
8004 return LVal.InvalidBase &&
8005 Designator.Entries.size() == Designator.MostDerivedPathLength &&
8006 Designator.MostDerivedIsArrayElement &&
8007 isDesignatorAtObjectEnd(Ctx, LVal);
8008}
8009
8010/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
8011/// Fails if the conversion would cause loss of precision.
8012static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
8013 CharUnits &Result) {
8014 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
8015 if (Int.ugt(CharUnitsMax))
8016 return false;
8017 Result = CharUnits::fromQuantity(Int.getZExtValue());
8018 return true;
8019}
8020
8021/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
8022/// determine how many bytes exist from the beginning of the object to either
8023/// the end of the current subobject, or the end of the object itself, depending
8024/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00008025///
George Burgess IVe3763372016-12-22 02:50:20 +00008026/// If this returns false, the value of Result is undefined.
8027static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
8028 unsigned Type, const LValue &LVal,
8029 CharUnits &EndOffset) {
8030 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008031
George Burgess IV7fb7e362017-01-03 23:35:19 +00008032 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
8033 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
8034 return false;
8035 return HandleSizeof(Info, ExprLoc, Ty, Result);
8036 };
8037
George Burgess IVe3763372016-12-22 02:50:20 +00008038 // We want to evaluate the size of the entire object. This is a valid fallback
8039 // for when Type=1 and the designator is invalid, because we're asked for an
8040 // upper-bound.
8041 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
8042 // Type=3 wants a lower bound, so we can't fall back to this.
8043 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00008044 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00008045
8046 llvm::APInt APEndOffset;
8047 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8048 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8049 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8050
8051 if (LVal.InvalidBase)
8052 return false;
8053
8054 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00008055 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00008056 }
8057
George Burgess IVe3763372016-12-22 02:50:20 +00008058 // We want to evaluate the size of a subobject.
8059 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008060
8061 // The following is a moderately common idiom in C:
8062 //
8063 // struct Foo { int a; char c[1]; };
8064 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8065 // strcpy(&F->c[0], Bar);
8066 //
George Burgess IVe3763372016-12-22 02:50:20 +00008067 // In order to not break too much legacy code, we need to support it.
8068 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8069 // If we can resolve this to an alloc_size call, we can hand that back,
8070 // because we know for certain how many bytes there are to write to.
8071 llvm::APInt APEndOffset;
8072 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8073 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8074 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8075
8076 // If we cannot determine the size of the initial allocation, then we can't
8077 // given an accurate upper-bound. However, we are still able to give
8078 // conservative lower-bounds for Type=3.
8079 if (Type == 1)
8080 return false;
8081 }
8082
8083 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00008084 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008085 return false;
8086
George Burgess IVe3763372016-12-22 02:50:20 +00008087 // According to the GCC documentation, we want the size of the subobject
8088 // denoted by the pointer. But that's not quite right -- what we actually
8089 // want is the size of the immediately-enclosing array, if there is one.
8090 int64_t ElemsRemaining;
8091 if (Designator.MostDerivedIsArrayElement &&
8092 Designator.Entries.size() == Designator.MostDerivedPathLength) {
8093 uint64_t ArraySize = Designator.getMostDerivedArraySize();
8094 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
8095 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8096 } else {
8097 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8098 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008099
George Burgess IVe3763372016-12-22 02:50:20 +00008100 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8101 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008102}
8103
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008104/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00008105/// returns true and stores the result in @p Size.
8106///
8107/// If @p WasError is non-null, this will report whether the failure to evaluate
8108/// is to be treated as an Error in IntExprEvaluator.
8109static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8110 EvalInfo &Info, uint64_t &Size) {
8111 // Determine the denoted object.
8112 LValue LVal;
8113 {
8114 // The operand of __builtin_object_size is never evaluated for side-effects.
8115 // If there are any, but we can determine the pointed-to object anyway, then
8116 // ignore the side-effects.
8117 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00008118 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00008119
8120 if (E->isGLValue()) {
8121 // It's possible for us to be given GLValues if we're called via
8122 // Expr::tryEvaluateObjectSize.
8123 APValue RVal;
8124 if (!EvaluateAsRValue(Info, E, RVal))
8125 return false;
8126 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00008127 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8128 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00008129 return false;
8130 }
8131
8132 // If we point to before the start of the object, there are no accessible
8133 // bytes.
8134 if (LVal.getLValueOffset().isNegative()) {
8135 Size = 0;
8136 return true;
8137 }
8138
8139 CharUnits EndOffset;
8140 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8141 return false;
8142
8143 // If we've fallen outside of the end offset, just pretend there's nothing to
8144 // write to/read from.
8145 if (EndOffset <= LVal.getLValueOffset())
8146 Size = 0;
8147 else
8148 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8149 return true;
John McCall95007602010-05-10 23:27:23 +00008150}
8151
Fangrui Song407659a2018-11-30 23:41:18 +00008152bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
8153 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
8154 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
8155}
8156
Peter Collingbournee9200682011-05-13 03:29:01 +00008157bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00008158 if (unsigned BuiltinOp = E->getBuiltinCallee())
8159 return VisitBuiltinCallExpr(E, BuiltinOp);
8160
8161 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8162}
8163
8164bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8165 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00008166 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008167 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00008168 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00008169
8170 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00008171 // The type was checked when we built the expression.
8172 unsigned Type =
8173 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8174 assert(Type <= 3 && "unexpected type");
8175
George Burgess IVe3763372016-12-22 02:50:20 +00008176 uint64_t Size;
8177 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8178 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00008179
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008180 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00008181 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00008182
Richard Smith01ade172012-05-23 04:13:20 +00008183 // Expression had no side effects, but we couldn't statically determine the
8184 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008185 switch (Info.EvalMode) {
8186 case EvalInfo::EM_ConstantExpression:
8187 case EvalInfo::EM_PotentialConstantExpression:
8188 case EvalInfo::EM_ConstantFold:
8189 case EvalInfo::EM_EvaluateForOverflow:
8190 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008191 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008192 return Error(E);
8193 case EvalInfo::EM_ConstantExpressionUnevaluated:
8194 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008195 // Reduce it to a constant now.
8196 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008197 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00008198
8199 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00008200 }
8201
Tim Northover314fbfa2018-11-02 13:14:11 +00008202 case Builtin::BI__builtin_os_log_format_buffer_size: {
8203 analyze_os_log::OSLogBufferLayout Layout;
8204 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
8205 return Success(Layout.size().getQuantity(), E);
8206 }
8207
Benjamin Kramera801f4a2012-10-06 14:42:22 +00008208 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00008209 case Builtin::BI__builtin_bswap32:
8210 case Builtin::BI__builtin_bswap64: {
8211 APSInt Val;
8212 if (!EvaluateInteger(E->getArg(0), Val, Info))
8213 return false;
8214
8215 return Success(Val.byteSwap(), E);
8216 }
8217
Richard Smith8889a3d2013-06-13 06:26:32 +00008218 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00008219 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00008220
Craig Topperf95a6d92018-08-08 22:31:12 +00008221 case Builtin::BI__builtin_clrsb:
8222 case Builtin::BI__builtin_clrsbl:
8223 case Builtin::BI__builtin_clrsbll: {
8224 APSInt Val;
8225 if (!EvaluateInteger(E->getArg(0), Val, Info))
8226 return false;
8227
8228 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8229 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008230
Richard Smith80b3c8e2013-06-13 05:04:16 +00008231 case Builtin::BI__builtin_clz:
8232 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008233 case Builtin::BI__builtin_clzll:
8234 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008235 APSInt Val;
8236 if (!EvaluateInteger(E->getArg(0), Val, Info))
8237 return false;
8238 if (!Val)
8239 return Error(E);
8240
8241 return Success(Val.countLeadingZeros(), E);
8242 }
8243
Fangrui Song407659a2018-11-30 23:41:18 +00008244 case Builtin::BI__builtin_constant_p: {
8245 auto Arg = E->getArg(0);
8246 if (EvaluateBuiltinConstantP(Info.Ctx, Arg))
8247 return Success(true, E);
8248 auto ArgTy = Arg->IgnoreImplicit()->getType();
8249 if (!Info.InConstantContext && !Arg->HasSideEffects(Info.Ctx) &&
8250 !ArgTy->isAggregateType() && !ArgTy->isPointerType()) {
8251 // We can delay calculation of __builtin_constant_p until after
8252 // inlining. Note: This diagnostic won't be shown to the user.
8253 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Bill Wendling2a81f662018-12-01 08:29:36 +00008254 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00008255 }
8256 return Success(false, E);
8257 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008258
Richard Smith80b3c8e2013-06-13 05:04:16 +00008259 case Builtin::BI__builtin_ctz:
8260 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008261 case Builtin::BI__builtin_ctzll:
8262 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008263 APSInt Val;
8264 if (!EvaluateInteger(E->getArg(0), Val, Info))
8265 return false;
8266 if (!Val)
8267 return Error(E);
8268
8269 return Success(Val.countTrailingZeros(), E);
8270 }
8271
Richard Smith8889a3d2013-06-13 06:26:32 +00008272 case Builtin::BI__builtin_eh_return_data_regno: {
8273 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8274 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8275 return Success(Operand, E);
8276 }
8277
8278 case Builtin::BI__builtin_expect:
8279 return Visit(E->getArg(0));
8280
8281 case Builtin::BI__builtin_ffs:
8282 case Builtin::BI__builtin_ffsl:
8283 case Builtin::BI__builtin_ffsll: {
8284 APSInt Val;
8285 if (!EvaluateInteger(E->getArg(0), Val, Info))
8286 return false;
8287
8288 unsigned N = Val.countTrailingZeros();
8289 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8290 }
8291
8292 case Builtin::BI__builtin_fpclassify: {
8293 APFloat Val(0.0);
8294 if (!EvaluateFloat(E->getArg(5), Val, Info))
8295 return false;
8296 unsigned Arg;
8297 switch (Val.getCategory()) {
8298 case APFloat::fcNaN: Arg = 0; break;
8299 case APFloat::fcInfinity: Arg = 1; break;
8300 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8301 case APFloat::fcZero: Arg = 4; break;
8302 }
8303 return Visit(E->getArg(Arg));
8304 }
8305
8306 case Builtin::BI__builtin_isinf_sign: {
8307 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00008308 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00008309 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8310 }
8311
Richard Smithea3019d2013-10-15 19:07:14 +00008312 case Builtin::BI__builtin_isinf: {
8313 APFloat Val(0.0);
8314 return EvaluateFloat(E->getArg(0), Val, Info) &&
8315 Success(Val.isInfinity() ? 1 : 0, E);
8316 }
8317
8318 case Builtin::BI__builtin_isfinite: {
8319 APFloat Val(0.0);
8320 return EvaluateFloat(E->getArg(0), Val, Info) &&
8321 Success(Val.isFinite() ? 1 : 0, E);
8322 }
8323
8324 case Builtin::BI__builtin_isnan: {
8325 APFloat Val(0.0);
8326 return EvaluateFloat(E->getArg(0), Val, Info) &&
8327 Success(Val.isNaN() ? 1 : 0, E);
8328 }
8329
8330 case Builtin::BI__builtin_isnormal: {
8331 APFloat Val(0.0);
8332 return EvaluateFloat(E->getArg(0), Val, Info) &&
8333 Success(Val.isNormal() ? 1 : 0, E);
8334 }
8335
Richard Smith8889a3d2013-06-13 06:26:32 +00008336 case Builtin::BI__builtin_parity:
8337 case Builtin::BI__builtin_parityl:
8338 case Builtin::BI__builtin_parityll: {
8339 APSInt Val;
8340 if (!EvaluateInteger(E->getArg(0), Val, Info))
8341 return false;
8342
8343 return Success(Val.countPopulation() % 2, E);
8344 }
8345
Richard Smith80b3c8e2013-06-13 05:04:16 +00008346 case Builtin::BI__builtin_popcount:
8347 case Builtin::BI__builtin_popcountl:
8348 case Builtin::BI__builtin_popcountll: {
8349 APSInt Val;
8350 if (!EvaluateInteger(E->getArg(0), Val, Info))
8351 return false;
8352
8353 return Success(Val.countPopulation(), E);
8354 }
8355
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008356 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00008357 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00008358 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008359 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008360 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00008361 << /*isConstexpr*/0 << /*isConstructor*/0
8362 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00008363 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00008364 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008365 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008366 case Builtin::BI__builtin_strlen:
8367 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00008368 // As an extension, we support __builtin_strlen() as a constant expression,
8369 // and support folding strlen() to a constant.
8370 LValue String;
8371 if (!EvaluatePointer(E->getArg(0), String, Info))
8372 return false;
8373
Richard Smith8110c9d2016-11-29 19:45:17 +00008374 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8375
Richard Smithe6c19f22013-11-15 02:10:04 +00008376 // Fast path: if it's a string literal, search the string value.
8377 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8378 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008379 // The string literal may have embedded null characters. Find the first
8380 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00008381 StringRef Str = S->getBytes();
8382 int64_t Off = String.Offset.getQuantity();
8383 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008384 S->getCharByteWidth() == 1 &&
8385 // FIXME: Add fast-path for wchar_t too.
8386 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00008387 Str = Str.substr(Off);
8388
8389 StringRef::size_type Pos = Str.find(0);
8390 if (Pos != StringRef::npos)
8391 Str = Str.substr(0, Pos);
8392
8393 return Success(Str.size(), E);
8394 }
8395
8396 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008397 }
Richard Smithe6c19f22013-11-15 02:10:04 +00008398
8399 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00008400 for (uint64_t Strlen = 0; /**/; ++Strlen) {
8401 APValue Char;
8402 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8403 !Char.isInt())
8404 return false;
8405 if (!Char.getInt())
8406 return Success(Strlen, E);
8407 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8408 return false;
8409 }
8410 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008411
Richard Smithe151bab2016-11-11 23:43:35 +00008412 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008413 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008414 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008415 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008416 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008417 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008418 // A call to strlen is not a constant expression.
8419 if (Info.getLangOpts().CPlusPlus11)
8420 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8421 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00008422 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00008423 else
8424 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008425 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00008426 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008427 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008428 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008429 case Builtin::BI__builtin_wcsncmp:
8430 case Builtin::BI__builtin_memcmp:
8431 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00008432 LValue String1, String2;
8433 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8434 !EvaluatePointer(E->getArg(1), String2, Info))
8435 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00008436
Richard Smithe151bab2016-11-11 23:43:35 +00008437 uint64_t MaxLength = uint64_t(-1);
8438 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008439 BuiltinOp != Builtin::BIwcscmp &&
8440 BuiltinOp != Builtin::BI__builtin_strcmp &&
8441 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00008442 APSInt N;
8443 if (!EvaluateInteger(E->getArg(2), N, Info))
8444 return false;
8445 MaxLength = N.getExtValue();
8446 }
Hubert Tong147b7432018-12-12 16:53:43 +00008447
8448 // Empty substrings compare equal by definition.
8449 if (MaxLength == 0u)
8450 return Success(0, E);
8451
8452 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8453 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8454 String1.Designator.Invalid || String2.Designator.Invalid)
8455 return false;
8456
8457 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
8458 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
8459
8460 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
8461 BuiltinOp == Builtin::BI__builtin_memcmp;
8462
8463 assert(IsRawByte ||
8464 (Info.Ctx.hasSameUnqualifiedType(
8465 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
8466 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
8467
8468 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
8469 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
8470 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
8471 Char1.isInt() && Char2.isInt();
8472 };
8473 const auto &AdvanceElems = [&] {
8474 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
8475 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
8476 };
8477
8478 if (IsRawByte) {
8479 uint64_t BytesRemaining = MaxLength;
8480 // Pointers to const void may point to objects of incomplete type.
8481 if (CharTy1->isIncompleteType()) {
8482 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
8483 return false;
8484 }
8485 if (CharTy2->isIncompleteType()) {
8486 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
8487 return false;
8488 }
8489 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
8490 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
8491 // Give up on comparing between elements with disparate widths.
8492 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
8493 return false;
8494 uint64_t BytesPerElement = CharTy1Size.getQuantity();
8495 assert(BytesRemaining && "BytesRemaining should not be zero: the "
8496 "following loop considers at least one element");
8497 while (true) {
8498 APValue Char1, Char2;
8499 if (!ReadCurElems(Char1, Char2))
8500 return false;
8501 // We have compatible in-memory widths, but a possible type and
8502 // (for `bool`) internal representation mismatch.
8503 // Assuming two's complement representation, including 0 for `false` and
8504 // 1 for `true`, we can check an appropriate number of elements for
8505 // equality even if they are not byte-sized.
8506 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
8507 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
8508 if (Char1InMem.ne(Char2InMem)) {
8509 // If the elements are byte-sized, then we can produce a three-way
8510 // comparison result in a straightforward manner.
8511 if (BytesPerElement == 1u) {
8512 // memcmp always compares unsigned chars.
8513 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
8514 }
8515 // The result is byte-order sensitive, and we have multibyte elements.
8516 // FIXME: We can compare the remaining bytes in the correct order.
8517 return false;
8518 }
8519 if (!AdvanceElems())
8520 return false;
8521 if (BytesRemaining <= BytesPerElement)
8522 break;
8523 BytesRemaining -= BytesPerElement;
8524 }
8525 // Enough elements are equal to account for the memcmp limit.
8526 return Success(0, E);
8527 }
8528
Richard Smithe151bab2016-11-11 23:43:35 +00008529 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008530 BuiltinOp != Builtin::BIwmemcmp &&
8531 BuiltinOp != Builtin::BI__builtin_memcmp &&
8532 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00008533 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8534 BuiltinOp == Builtin::BIwcsncmp ||
8535 BuiltinOp == Builtin::BIwmemcmp ||
8536 BuiltinOp == Builtin::BI__builtin_wcscmp ||
8537 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8538 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00008539
Richard Smithe151bab2016-11-11 23:43:35 +00008540 for (; MaxLength; --MaxLength) {
8541 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +00008542 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +00008543 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00008544 if (Char1.getInt() != Char2.getInt()) {
8545 if (IsWide) // wmemcmp compares with wchar_t signedness.
8546 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8547 // memcmp always compares unsigned chars.
8548 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8549 }
Richard Smithe151bab2016-11-11 23:43:35 +00008550 if (StopAtNull && !Char1.getInt())
8551 return Success(0, E);
8552 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +00008553 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +00008554 return false;
8555 }
8556 // We hit the strncmp / memcmp limit.
8557 return Success(0, E);
8558 }
8559
Richard Smith01ba47d2012-04-13 00:45:38 +00008560 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00008561 case Builtin::BI__atomic_is_lock_free:
8562 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00008563 APSInt SizeVal;
8564 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8565 return false;
8566
8567 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8568 // of two less than the maximum inline atomic width, we know it is
8569 // lock-free. If the size isn't a power of two, or greater than the
8570 // maximum alignment where we promote atomics, we know it is not lock-free
8571 // (at least not in the sense of atomic_is_lock_free). Otherwise,
8572 // the answer can only be determined at runtime; for example, 16-byte
8573 // atomics have lock-free implementations on some, but not all,
8574 // x86-64 processors.
8575
8576 // Check power-of-two.
8577 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00008578 if (Size.isPowerOfTwo()) {
8579 // Check against inlining width.
8580 unsigned InlineWidthBits =
8581 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8582 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8583 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8584 Size == CharUnits::One() ||
8585 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8586 Expr::NPC_NeverValueDependent))
8587 // OK, we will inline appropriately-aligned operations of this size,
8588 // and _Atomic(T) is appropriately-aligned.
8589 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008590
Richard Smith01ba47d2012-04-13 00:45:38 +00008591 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8592 castAs<PointerType>()->getPointeeType();
8593 if (!PointeeType->isIncompleteType() &&
8594 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8595 // OK, we will inline operations on this object.
8596 return Success(1, E);
8597 }
8598 }
8599 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008600
Richard Smith01ba47d2012-04-13 00:45:38 +00008601 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8602 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008603 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008604 case Builtin::BIomp_is_initial_device:
8605 // We can decide statically which value the runtime would return if called.
8606 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00008607 case Builtin::BI__builtin_add_overflow:
8608 case Builtin::BI__builtin_sub_overflow:
8609 case Builtin::BI__builtin_mul_overflow:
8610 case Builtin::BI__builtin_sadd_overflow:
8611 case Builtin::BI__builtin_uadd_overflow:
8612 case Builtin::BI__builtin_uaddl_overflow:
8613 case Builtin::BI__builtin_uaddll_overflow:
8614 case Builtin::BI__builtin_usub_overflow:
8615 case Builtin::BI__builtin_usubl_overflow:
8616 case Builtin::BI__builtin_usubll_overflow:
8617 case Builtin::BI__builtin_umul_overflow:
8618 case Builtin::BI__builtin_umull_overflow:
8619 case Builtin::BI__builtin_umulll_overflow:
8620 case Builtin::BI__builtin_saddl_overflow:
8621 case Builtin::BI__builtin_saddll_overflow:
8622 case Builtin::BI__builtin_ssub_overflow:
8623 case Builtin::BI__builtin_ssubl_overflow:
8624 case Builtin::BI__builtin_ssubll_overflow:
8625 case Builtin::BI__builtin_smul_overflow:
8626 case Builtin::BI__builtin_smull_overflow:
8627 case Builtin::BI__builtin_smulll_overflow: {
8628 LValue ResultLValue;
8629 APSInt LHS, RHS;
8630
8631 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
8632 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
8633 !EvaluateInteger(E->getArg(1), RHS, Info) ||
8634 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
8635 return false;
8636
8637 APSInt Result;
8638 bool DidOverflow = false;
8639
8640 // If the types don't have to match, enlarge all 3 to the largest of them.
8641 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8642 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8643 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8644 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
8645 ResultType->isSignedIntegerOrEnumerationType();
8646 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
8647 ResultType->isSignedIntegerOrEnumerationType();
8648 uint64_t LHSSize = LHS.getBitWidth();
8649 uint64_t RHSSize = RHS.getBitWidth();
8650 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
8651 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
8652
8653 // Add an additional bit if the signedness isn't uniformly agreed to. We
8654 // could do this ONLY if there is a signed and an unsigned that both have
8655 // MaxBits, but the code to check that is pretty nasty. The issue will be
8656 // caught in the shrink-to-result later anyway.
8657 if (IsSigned && !AllSigned)
8658 ++MaxBits;
8659
8660 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
8661 !IsSigned);
8662 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
8663 !IsSigned);
8664 Result = APSInt(MaxBits, !IsSigned);
8665 }
8666
8667 // Find largest int.
8668 switch (BuiltinOp) {
8669 default:
8670 llvm_unreachable("Invalid value for BuiltinOp");
8671 case Builtin::BI__builtin_add_overflow:
8672 case Builtin::BI__builtin_sadd_overflow:
8673 case Builtin::BI__builtin_saddl_overflow:
8674 case Builtin::BI__builtin_saddll_overflow:
8675 case Builtin::BI__builtin_uadd_overflow:
8676 case Builtin::BI__builtin_uaddl_overflow:
8677 case Builtin::BI__builtin_uaddll_overflow:
8678 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
8679 : LHS.uadd_ov(RHS, DidOverflow);
8680 break;
8681 case Builtin::BI__builtin_sub_overflow:
8682 case Builtin::BI__builtin_ssub_overflow:
8683 case Builtin::BI__builtin_ssubl_overflow:
8684 case Builtin::BI__builtin_ssubll_overflow:
8685 case Builtin::BI__builtin_usub_overflow:
8686 case Builtin::BI__builtin_usubl_overflow:
8687 case Builtin::BI__builtin_usubll_overflow:
8688 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
8689 : LHS.usub_ov(RHS, DidOverflow);
8690 break;
8691 case Builtin::BI__builtin_mul_overflow:
8692 case Builtin::BI__builtin_smul_overflow:
8693 case Builtin::BI__builtin_smull_overflow:
8694 case Builtin::BI__builtin_smulll_overflow:
8695 case Builtin::BI__builtin_umul_overflow:
8696 case Builtin::BI__builtin_umull_overflow:
8697 case Builtin::BI__builtin_umulll_overflow:
8698 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
8699 : LHS.umul_ov(RHS, DidOverflow);
8700 break;
8701 }
8702
8703 // In the case where multiple sizes are allowed, truncate and see if
8704 // the values are the same.
8705 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8706 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8707 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8708 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
8709 // since it will give us the behavior of a TruncOrSelf in the case where
8710 // its parameter <= its size. We previously set Result to be at least the
8711 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
8712 // will work exactly like TruncOrSelf.
8713 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
8714 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
8715
8716 if (!APSInt::isSameValue(Temp, Result))
8717 DidOverflow = true;
8718 Result = Temp;
8719 }
8720
8721 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +00008722 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
8723 return false;
Erich Keane00958272018-06-13 20:43:27 +00008724 return Success(DidOverflow, E);
8725 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008726 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008727}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008728
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008729/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +00008730/// object referred to by the lvalue.
8731static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8732 const LValue &LV) {
8733 // A null pointer can be viewed as being "past the end" but we don't
8734 // choose to look at it that way here.
8735 if (!LV.getLValueBase())
8736 return false;
8737
8738 // If the designator is valid and refers to a subobject, we're not pointing
8739 // past the end.
8740 if (!LV.getLValueDesignator().Invalid &&
8741 !LV.getLValueDesignator().isOnePastTheEnd())
8742 return false;
8743
David Majnemerc378ca52015-08-29 08:32:55 +00008744 // A pointer to an incomplete type might be past-the-end if the type's size is
8745 // zero. We cannot tell because the type is incomplete.
8746 QualType Ty = getType(LV.getLValueBase());
8747 if (Ty->isIncompleteType())
8748 return true;
8749
Richard Smithd20f1e62014-10-21 23:01:04 +00008750 // We're a past-the-end pointer if we point to the byte after the object,
8751 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008752 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008753 return LV.getLValueOffset() == Size;
8754}
8755
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008756namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008757
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008758/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008759///
8760/// We use a data recursive algorithm for binary operators so that we are able
8761/// to handle extreme cases of chained binary operators without causing stack
8762/// overflow.
8763class DataRecursiveIntBinOpEvaluator {
8764 struct EvalResult {
8765 APValue Val;
8766 bool Failed;
8767
8768 EvalResult() : Failed(false) { }
8769
8770 void swap(EvalResult &RHS) {
8771 Val.swap(RHS.Val);
8772 Failed = RHS.Failed;
8773 RHS.Failed = false;
8774 }
8775 };
8776
8777 struct Job {
8778 const Expr *E;
8779 EvalResult LHSResult; // meaningful only for binary operator expression.
8780 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008781
David Blaikie73726062015-08-12 23:09:24 +00008782 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008783 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008784
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008785 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008786 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008787 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008788
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008789 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008790 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008791 };
8792
8793 SmallVector<Job, 16> Queue;
8794
8795 IntExprEvaluator &IntEval;
8796 EvalInfo &Info;
8797 APValue &FinalResult;
8798
8799public:
8800 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8801 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8802
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008803 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008804 /// data recursively.
8805 /// We handle binary operators that are comma, logical, or that have operands
8806 /// with integral or enumeration type.
8807 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008808 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8809 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +00008810 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008811 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008812 }
8813
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008814 bool Traverse(const BinaryOperator *E) {
8815 enqueue(E);
8816 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008817 while (!Queue.empty())
8818 process(PrevResult);
8819
8820 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008821
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008822 FinalResult.swap(PrevResult.Val);
8823 return true;
8824 }
8825
8826private:
8827 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8828 return IntEval.Success(Value, E, Result);
8829 }
8830 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8831 return IntEval.Success(Value, E, Result);
8832 }
8833 bool Error(const Expr *E) {
8834 return IntEval.Error(E);
8835 }
8836 bool Error(const Expr *E, diag::kind D) {
8837 return IntEval.Error(E, D);
8838 }
8839
8840 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8841 return Info.CCEDiag(E, D);
8842 }
8843
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008844 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008845 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008846 bool &SuppressRHSDiags);
8847
8848 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8849 const BinaryOperator *E, APValue &Result);
8850
8851 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8852 Result.Failed = !Evaluate(Result.Val, Info, E);
8853 if (Result.Failed)
8854 Result.Val = APValue();
8855 }
8856
Richard Trieuba4d0872012-03-21 23:30:30 +00008857 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008858
8859 void enqueue(const Expr *E) {
8860 E = E->IgnoreParens();
8861 Queue.resize(Queue.size()+1);
8862 Queue.back().E = E;
8863 Queue.back().Kind = Job::AnyExprKind;
8864 }
8865};
8866
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008867}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008868
8869bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008870 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008871 bool &SuppressRHSDiags) {
8872 if (E->getOpcode() == BO_Comma) {
8873 // Ignore LHS but note if we could not evaluate it.
8874 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008875 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008876 return true;
8877 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008878
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008879 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008880 bool LHSAsBool;
8881 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008882 // We were able to evaluate the LHS, see if we can get away with not
8883 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008884 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8885 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008886 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008887 }
8888 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008889 LHSResult.Failed = true;
8890
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008891 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008892 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008893 if (!Info.noteSideEffect())
8894 return false;
8895
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008896 // We can't evaluate the LHS; however, sometimes the result
8897 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8898 // Don't ignore RHS and suppress diagnostics from this arm.
8899 SuppressRHSDiags = true;
8900 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008901
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008902 return true;
8903 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008904
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008905 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8906 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008907
George Burgess IVa145e252016-05-25 22:38:36 +00008908 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008909 return false; // Ignore RHS;
8910
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008911 return true;
8912}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008913
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008914static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8915 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008916 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8917 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8918 // offsets.
8919 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8920 CharUnits &Offset = LVal.getLValueOffset();
8921 uint64_t Offset64 = Offset.getQuantity();
8922 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8923 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8924 : Offset64 + Index64);
8925}
8926
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008927bool DataRecursiveIntBinOpEvaluator::
8928 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8929 const BinaryOperator *E, APValue &Result) {
8930 if (E->getOpcode() == BO_Comma) {
8931 if (RHSResult.Failed)
8932 return false;
8933 Result = RHSResult.Val;
8934 return true;
8935 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008936
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008937 if (E->isLogicalOp()) {
8938 bool lhsResult, rhsResult;
8939 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8940 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +00008941
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008942 if (LHSIsOK) {
8943 if (RHSIsOK) {
8944 if (E->getOpcode() == BO_LOr)
8945 return Success(lhsResult || rhsResult, E, Result);
8946 else
8947 return Success(lhsResult && rhsResult, E, Result);
8948 }
8949 } else {
8950 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008951 // We can't evaluate the LHS; however, sometimes the result
8952 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8953 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008954 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008955 }
8956 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008957
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008958 return false;
8959 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008960
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008961 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8962 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +00008963
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008964 if (LHSResult.Failed || RHSResult.Failed)
8965 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008966
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008967 const APValue &LHSVal = LHSResult.Val;
8968 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +00008969
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008970 // Handle cases like (unsigned long)&a + 4.
8971 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8972 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008973 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008974 return true;
8975 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008976
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008977 // Handle cases like 4 + (unsigned long)&a
8978 if (E->getOpcode() == BO_Add &&
8979 RHSVal.isLValue() && LHSVal.isInt()) {
8980 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008981 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008982 return true;
8983 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008984
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008985 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8986 // Handle (intptr_t)&&A - (intptr_t)&&B.
8987 if (!LHSVal.getLValueOffset().isZero() ||
8988 !RHSVal.getLValueOffset().isZero())
8989 return false;
8990 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8991 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8992 if (!LHSExpr || !RHSExpr)
8993 return false;
8994 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8995 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8996 if (!LHSAddrExpr || !RHSAddrExpr)
8997 return false;
8998 // Make sure both labels come from the same function.
8999 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9000 RHSAddrExpr->getLabel()->getDeclContext())
9001 return false;
9002 Result = APValue(LHSAddrExpr, RHSAddrExpr);
9003 return true;
9004 }
Richard Smith43e77732013-05-07 04:50:00 +00009005
9006 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009007 if (!LHSVal.isInt() || !RHSVal.isInt())
9008 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00009009
9010 // Set up the width and signedness manually, in case it can't be deduced
9011 // from the operation we're performing.
9012 // FIXME: Don't do this in the cases where we can deduce it.
9013 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
9014 E->getType()->isUnsignedIntegerOrEnumerationType());
9015 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
9016 RHSVal.getInt(), Value))
9017 return false;
9018 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009019}
9020
Richard Trieuba4d0872012-03-21 23:30:30 +00009021void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009022 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +00009023
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009024 switch (job.Kind) {
9025 case Job::AnyExprKind: {
9026 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
9027 if (shouldEnqueue(Bop)) {
9028 job.Kind = Job::BinOpKind;
9029 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009030 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009031 }
9032 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009033
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009034 EvaluateExpr(job.E, Result);
9035 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009036 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009037 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009038
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009039 case Job::BinOpKind: {
9040 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009041 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009042 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009043 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009044 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009045 }
9046 if (SuppressRHSDiags)
9047 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009048 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009049 job.Kind = Job::BinOpVisitedLHSKind;
9050 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009051 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009052 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009053
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009054 case Job::BinOpVisitedLHSKind: {
9055 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9056 EvalResult RHS;
9057 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00009058 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009059 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009060 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009061 }
9062 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009063
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009064 llvm_unreachable("Invalid Job::Kind!");
9065}
9066
George Burgess IV8c892b52016-05-25 22:31:54 +00009067namespace {
9068/// Used when we determine that we should fail, but can keep evaluating prior to
9069/// noting that we had a failure.
9070class DelayedNoteFailureRAII {
9071 EvalInfo &Info;
9072 bool NoteFailure;
9073
9074public:
9075 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
9076 : Info(Info), NoteFailure(NoteFailure) {}
9077 ~DelayedNoteFailureRAII() {
9078 if (NoteFailure) {
9079 bool ContinueAfterFailure = Info.noteFailure();
9080 (void)ContinueAfterFailure;
9081 assert(ContinueAfterFailure &&
9082 "Shouldn't have kept evaluating on failure.");
9083 }
9084 }
9085};
9086}
9087
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009088template <class SuccessCB, class AfterCB>
9089static bool
9090EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
9091 SuccessCB &&Success, AfterCB &&DoAfter) {
9092 assert(E->isComparisonOp() && "expected comparison operator");
9093 assert((E->getOpcode() == BO_Cmp ||
9094 E->getType()->isIntegralOrEnumerationType()) &&
9095 "unsupported binary expression evaluation");
9096 auto Error = [&](const Expr *E) {
9097 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9098 return false;
9099 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009100
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009101 using CCR = ComparisonCategoryResult;
9102 bool IsRelational = E->isRelationalOp();
9103 bool IsEquality = E->isEqualityOp();
9104 if (E->getOpcode() == BO_Cmp) {
9105 const ComparisonCategoryInfo &CmpInfo =
9106 Info.Ctx.CompCategories.getInfoForType(E->getType());
9107 IsRelational = CmpInfo.isOrdered();
9108 IsEquality = CmpInfo.isEquality();
9109 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00009110
Anders Carlssonacc79812008-11-16 07:17:21 +00009111 QualType LHSTy = E->getLHS()->getType();
9112 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009113
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009114 if (LHSTy->isIntegralOrEnumerationType() &&
9115 RHSTy->isIntegralOrEnumerationType()) {
9116 APSInt LHS, RHS;
9117 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
9118 if (!LHSOK && !Info.noteFailure())
9119 return false;
9120 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
9121 return false;
9122 if (LHS < RHS)
9123 return Success(CCR::Less, E);
9124 if (LHS > RHS)
9125 return Success(CCR::Greater, E);
9126 return Success(CCR::Equal, E);
9127 }
9128
Chandler Carruthb29a7432014-10-11 11:03:30 +00009129 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009130 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00009131 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00009132 if (E->isAssignmentOp()) {
9133 LValue LV;
9134 EvaluateLValue(E->getLHS(), LV, Info);
9135 LHSOK = false;
9136 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00009137 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
9138 if (LHSOK) {
9139 LHS.makeComplexFloat();
9140 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
9141 }
9142 } else {
9143 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
9144 }
George Burgess IVa145e252016-05-25 22:38:36 +00009145 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009146 return false;
9147
Chandler Carruthb29a7432014-10-11 11:03:30 +00009148 if (E->getRHS()->getType()->isRealFloatingType()) {
9149 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
9150 return false;
9151 RHS.makeComplexFloat();
9152 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
9153 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009154 return false;
9155
9156 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00009157 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009158 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00009159 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009160 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009161 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9162 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009163 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009164 assert(IsEquality && "invalid complex comparison");
9165 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
9166 LHS.getComplexIntImag() == RHS.getComplexIntImag();
9167 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009168 }
9169 }
Mike Stump11289f42009-09-09 15:08:12 +00009170
Anders Carlssonacc79812008-11-16 07:17:21 +00009171 if (LHSTy->isRealFloatingType() &&
9172 RHSTy->isRealFloatingType()) {
9173 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00009174
Richard Smith253c2a32012-01-27 01:14:48 +00009175 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009176 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00009177 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009178
Richard Smith253c2a32012-01-27 01:14:48 +00009179 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00009180 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009181
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009182 assert(E->isComparisonOp() && "Invalid binary operator!");
9183 auto GetCmpRes = [&]() {
9184 switch (LHS.compare(RHS)) {
9185 case APFloat::cmpEqual:
9186 return CCR::Equal;
9187 case APFloat::cmpLessThan:
9188 return CCR::Less;
9189 case APFloat::cmpGreaterThan:
9190 return CCR::Greater;
9191 case APFloat::cmpUnordered:
9192 return CCR::Unordered;
9193 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +00009194 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009195 };
9196 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +00009197 }
Mike Stump11289f42009-09-09 15:08:12 +00009198
Eli Friedmana38da572009-04-28 19:17:36 +00009199 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009200 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +00009201
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009202 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9203 if (!LHSOK && !Info.noteFailure())
9204 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009205
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009206 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9207 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009208
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009209 // Reject differing bases from the normal codepath; we special-case
9210 // comparisons to null.
9211 if (!HasSameBase(LHSValue, RHSValue)) {
9212 // Inequalities and subtractions between unrelated pointers have
9213 // unspecified or undefined behavior.
9214 if (!IsEquality)
9215 return Error(E);
9216 // A constant address may compare equal to the address of a symbol.
9217 // The one exception is that address of an object cannot compare equal
9218 // to a null pointer constant.
9219 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9220 (!RHSValue.Base && !RHSValue.Offset.isZero()))
9221 return Error(E);
9222 // It's implementation-defined whether distinct literals will have
9223 // distinct addresses. In clang, the result of such a comparison is
9224 // unspecified, so it is not a constant expression. However, we do know
9225 // that the address of a literal will be non-null.
9226 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9227 LHSValue.Base && RHSValue.Base)
9228 return Error(E);
9229 // We can't tell whether weak symbols will end up pointing to the same
9230 // object.
9231 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9232 return Error(E);
9233 // We can't compare the address of the start of one object with the
9234 // past-the-end address of another object, per C++ DR1652.
9235 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9236 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9237 (RHSValue.Base && RHSValue.Offset.isZero() &&
9238 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9239 return Error(E);
9240 // We can't tell whether an object is at the same address as another
9241 // zero sized object.
9242 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9243 (LHSValue.Base && isZeroSized(RHSValue)))
9244 return Error(E);
9245 return Success(CCR::Nonequal, E);
9246 }
Eli Friedman64004332009-03-23 04:38:34 +00009247
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009248 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9249 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +00009250
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009251 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9252 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +00009253
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009254 // C++11 [expr.rel]p3:
9255 // Pointers to void (after pointer conversions) can be compared, with a
9256 // result defined as follows: If both pointers represent the same
9257 // address or are both the null pointer value, the result is true if the
9258 // operator is <= or >= and false otherwise; otherwise the result is
9259 // unspecified.
9260 // We interpret this as applying to pointers to *cv* void.
9261 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9262 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +00009263
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009264 // C++11 [expr.rel]p2:
9265 // - If two pointers point to non-static data members of the same object,
9266 // or to subobjects or array elements fo such members, recursively, the
9267 // pointer to the later declared member compares greater provided the
9268 // two members have the same access control and provided their class is
9269 // not a union.
9270 // [...]
9271 // - Otherwise pointer comparisons are unspecified.
9272 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9273 bool WasArrayIndex;
9274 unsigned Mismatch = FindDesignatorMismatch(
9275 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9276 // At the point where the designators diverge, the comparison has a
9277 // specified value if:
9278 // - we are comparing array indices
9279 // - we are comparing fields of a union, or fields with the same access
9280 // Otherwise, the result is unspecified and thus the comparison is not a
9281 // constant expression.
9282 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9283 Mismatch < RHSDesignator.Entries.size()) {
9284 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9285 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9286 if (!LF && !RF)
9287 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9288 else if (!LF)
9289 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009290 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9291 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009292 else if (!RF)
9293 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009294 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9295 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009296 else if (!LF->getParent()->isUnion() &&
9297 LF->getAccess() != RF->getAccess())
9298 Info.CCEDiag(E,
9299 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009300 << LF << LF->getAccess() << RF << RF->getAccess()
9301 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +00009302 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009303 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009304
9305 // The comparison here must be unsigned, and performed with the same
9306 // width as the pointer.
9307 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9308 uint64_t CompareLHS = LHSOffset.getQuantity();
9309 uint64_t CompareRHS = RHSOffset.getQuantity();
9310 assert(PtrSize <= 64 && "Unexpected pointer width");
9311 uint64_t Mask = ~0ULL >> (64 - PtrSize);
9312 CompareLHS &= Mask;
9313 CompareRHS &= Mask;
9314
9315 // If there is a base and this is a relational operator, we can only
9316 // compare pointers within the object in question; otherwise, the result
9317 // depends on where the object is located in memory.
9318 if (!LHSValue.Base.isNull() && IsRelational) {
9319 QualType BaseTy = getType(LHSValue.Base);
9320 if (BaseTy->isIncompleteType())
9321 return Error(E);
9322 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9323 uint64_t OffsetLimit = Size.getQuantity();
9324 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9325 return Error(E);
9326 }
9327
9328 if (CompareLHS < CompareRHS)
9329 return Success(CCR::Less, E);
9330 if (CompareLHS > CompareRHS)
9331 return Success(CCR::Greater, E);
9332 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009333 }
Richard Smith7bb00672012-02-01 01:42:44 +00009334
9335 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009336 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +00009337 assert(RHSTy->isMemberPointerType() && "invalid comparison");
9338
9339 MemberPtr LHSValue, RHSValue;
9340
9341 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009342 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00009343 return false;
9344
9345 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9346 return false;
9347
9348 // C++11 [expr.eq]p2:
9349 // If both operands are null, they compare equal. Otherwise if only one is
9350 // null, they compare unequal.
9351 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9352 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009353 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009354 }
9355
9356 // Otherwise if either is a pointer to a virtual member function, the
9357 // result is unspecified.
9358 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9359 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009360 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009361 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9362 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009363 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009364
9365 // Otherwise they compare equal if and only if they would refer to the
9366 // same member of the same most derived object or the same subobject if
9367 // they were dereferenced with a hypothetical object of the associated
9368 // class type.
9369 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009370 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009371 }
9372
Richard Smithab44d9b2012-02-14 22:35:28 +00009373 if (LHSTy->isNullPtrType()) {
9374 assert(E->isComparisonOp() && "unexpected nullptr operation");
9375 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9376 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9377 // are compared, the result is true of the operator is <=, >= or ==, and
9378 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009379 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +00009380 }
9381
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009382 return DoAfter();
9383}
9384
9385bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
9386 if (!CheckLiteralType(Info, E))
9387 return false;
9388
9389 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9390 const BinaryOperator *E) {
9391 // Evaluation succeeded. Lookup the information for the comparison category
9392 // type and fetch the VarDecl for the result.
9393 const ComparisonCategoryInfo &CmpInfo =
9394 Info.Ctx.CompCategories.getInfoForType(E->getType());
9395 const VarDecl *VD =
9396 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
9397 // Check and evaluate the result as a constant expression.
9398 LValue LV;
9399 LV.set(VD);
9400 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9401 return false;
9402 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9403 };
9404 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9405 return ExprEvaluatorBaseTy::VisitBinCmp(E);
9406 });
9407}
9408
9409bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9410 // We don't call noteFailure immediately because the assignment happens after
9411 // we evaluate LHS and RHS.
9412 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
9413 return Error(E);
9414
9415 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
9416 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
9417 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
9418
9419 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
9420 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009421 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009422
9423 if (E->isComparisonOp()) {
9424 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
9425 // comparisons and then translating the result.
9426 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9427 const BinaryOperator *E) {
9428 using CCR = ComparisonCategoryResult;
9429 bool IsEqual = ResKind == CCR::Equal,
9430 IsLess = ResKind == CCR::Less,
9431 IsGreater = ResKind == CCR::Greater;
9432 auto Op = E->getOpcode();
9433 switch (Op) {
9434 default:
9435 llvm_unreachable("unsupported binary operator");
9436 case BO_EQ:
9437 case BO_NE:
9438 return Success(IsEqual == (Op == BO_EQ), E);
9439 case BO_LT: return Success(IsLess, E);
9440 case BO_GT: return Success(IsGreater, E);
9441 case BO_LE: return Success(IsEqual || IsLess, E);
9442 case BO_GE: return Success(IsEqual || IsGreater, E);
9443 }
9444 };
9445 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9446 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9447 });
9448 }
9449
9450 QualType LHSTy = E->getLHS()->getType();
9451 QualType RHSTy = E->getRHS()->getType();
9452
9453 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
9454 E->getOpcode() == BO_Sub) {
9455 LValue LHSValue, RHSValue;
9456
9457 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9458 if (!LHSOK && !Info.noteFailure())
9459 return false;
9460
9461 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9462 return false;
9463
9464 // Reject differing bases from the normal codepath; we special-case
9465 // comparisons to null.
9466 if (!HasSameBase(LHSValue, RHSValue)) {
9467 // Handle &&A - &&B.
9468 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
9469 return Error(E);
9470 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
9471 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
9472 if (!LHSExpr || !RHSExpr)
9473 return Error(E);
9474 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9475 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9476 if (!LHSAddrExpr || !RHSAddrExpr)
9477 return Error(E);
9478 // Make sure both labels come from the same function.
9479 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9480 RHSAddrExpr->getLabel()->getDeclContext())
9481 return Error(E);
9482 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
9483 }
9484 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9485 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9486
9487 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9488 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9489
9490 // C++11 [expr.add]p6:
9491 // Unless both pointers point to elements of the same array object, or
9492 // one past the last element of the array object, the behavior is
9493 // undefined.
9494 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
9495 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
9496 RHSDesignator))
9497 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
9498
9499 QualType Type = E->getLHS()->getType();
9500 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
9501
9502 CharUnits ElementSize;
9503 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
9504 return false;
9505
9506 // As an extension, a type may have zero size (empty struct or union in
9507 // C, array of zero length). Pointer subtraction in such cases has
9508 // undefined behavior, so is not constant.
9509 if (ElementSize.isZero()) {
9510 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
9511 << ElementType;
9512 return false;
9513 }
9514
9515 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
9516 // and produce incorrect results when it overflows. Such behavior
9517 // appears to be non-conforming, but is common, so perhaps we should
9518 // assume the standard intended for such cases to be undefined behavior
9519 // and check for them.
9520
9521 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
9522 // overflow in the final conversion to ptrdiff_t.
9523 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
9524 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
9525 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
9526 false);
9527 APSInt TrueResult = (LHS - RHS) / ElemSize;
9528 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
9529
9530 if (Result.extend(65) != TrueResult &&
9531 !HandleOverflow(Info, E, TrueResult, E->getType()))
9532 return false;
9533 return Success(Result, E);
9534 }
9535
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009536 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00009537}
9538
Peter Collingbournee190dee2011-03-11 19:24:49 +00009539/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
9540/// a result as the expression's type.
9541bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
9542 const UnaryExprOrTypeTraitExpr *E) {
9543 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +00009544 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +00009545 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00009546 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +00009547 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
9548 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009549 else
Richard Smith6822bd72018-10-26 19:26:45 +00009550 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
9551 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009552 }
Eli Friedman64004332009-03-23 04:38:34 +00009553
Peter Collingbournee190dee2011-03-11 19:24:49 +00009554 case UETT_VecStep: {
9555 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00009556
Peter Collingbournee190dee2011-03-11 19:24:49 +00009557 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00009558 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00009559
Peter Collingbournee190dee2011-03-11 19:24:49 +00009560 // The vec_step built-in functions that take a 3-component
9561 // vector return 4. (OpenCL 1.1 spec 6.11.12)
9562 if (n == 3)
9563 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00009564
Peter Collingbournee190dee2011-03-11 19:24:49 +00009565 return Success(n, E);
9566 } else
9567 return Success(1, E);
9568 }
9569
9570 case UETT_SizeOf: {
9571 QualType SrcTy = E->getTypeOfArgument();
9572 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9573 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00009574 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9575 SrcTy = Ref->getPointeeType();
9576
Richard Smithd62306a2011-11-10 06:34:14 +00009577 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00009578 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00009579 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00009580 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009581 }
Alexey Bataev00396512015-07-02 03:40:19 +00009582 case UETT_OpenMPRequiredSimdAlign:
9583 assert(E->isArgumentType());
9584 return Success(
9585 Info.Ctx.toCharUnitsFromBits(
9586 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9587 .getQuantity(),
9588 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009589 }
9590
9591 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00009592}
9593
Peter Collingbournee9200682011-05-13 03:29:01 +00009594bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009595 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00009596 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00009597 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009598 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00009599 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00009600 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00009601 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00009602 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00009603 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00009604 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00009605 APSInt IdxResult;
9606 if (!EvaluateInteger(Idx, IdxResult, Info))
9607 return false;
9608 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9609 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009610 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009611 CurrentType = AT->getElementType();
9612 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9613 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00009614 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00009615 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009616
James Y Knight7281c352015-12-29 22:31:18 +00009617 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00009618 FieldDecl *MemberDecl = ON.getField();
9619 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009620 if (!RT)
9621 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009622 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009623 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00009624 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00009625 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00009626 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00009627 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00009628 CurrentType = MemberDecl->getType().getNonReferenceType();
9629 break;
9630 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009631
James Y Knight7281c352015-12-29 22:31:18 +00009632 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00009633 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00009634
James Y Knight7281c352015-12-29 22:31:18 +00009635 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00009636 CXXBaseSpecifier *BaseSpec = ON.getBase();
9637 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00009638 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009639
9640 // Find the layout of the class whose base we are looking into.
9641 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009642 if (!RT)
9643 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009644 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009645 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00009646 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9647
9648 // Find the base class itself.
9649 CurrentType = BaseSpec->getType();
9650 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9651 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009652 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +00009653
Douglas Gregord1702062010-04-29 00:18:15 +00009654 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00009655 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00009656 break;
9657 }
Douglas Gregor882211c2010-04-28 22:16:22 +00009658 }
9659 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009660 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009661}
9662
Chris Lattnere13042c2008-07-11 19:10:17 +00009663bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009664 switch (E->getOpcode()) {
9665 default:
9666 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9667 // See C99 6.6p3.
9668 return Error(E);
9669 case UO_Extension:
9670 // FIXME: Should extension allow i-c-e extension expressions in its scope?
9671 // If so, we could clear the diagnostic ID.
9672 return Visit(E->getSubExpr());
9673 case UO_Plus:
9674 // The result is just the value.
9675 return Visit(E->getSubExpr());
9676 case UO_Minus: {
9677 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00009678 return false;
9679 if (!Result.isInt()) return Error(E);
9680 const APSInt &Value = Result.getInt();
9681 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9682 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9683 E->getType()))
9684 return false;
Richard Smithfe800032012-01-31 04:08:20 +00009685 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009686 }
9687 case UO_Not: {
9688 if (!Visit(E->getSubExpr()))
9689 return false;
9690 if (!Result.isInt()) return Error(E);
9691 return Success(~Result.getInt(), E);
9692 }
9693 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00009694 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00009695 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00009696 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009697 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00009698 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009699 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009700}
Mike Stump11289f42009-09-09 15:08:12 +00009701
Chris Lattner477c4be2008-07-12 01:15:53 +00009702/// HandleCast - This is used to evaluate implicit or explicit casts where the
9703/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00009704bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9705 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009706 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00009707 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009708
Eli Friedmanc757de22011-03-25 00:43:55 +00009709 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00009710 case CK_BaseToDerived:
9711 case CK_DerivedToBase:
9712 case CK_UncheckedDerivedToBase:
9713 case CK_Dynamic:
9714 case CK_ToUnion:
9715 case CK_ArrayToPointerDecay:
9716 case CK_FunctionToPointerDecay:
9717 case CK_NullToPointer:
9718 case CK_NullToMemberPointer:
9719 case CK_BaseToDerivedMemberPointer:
9720 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00009721 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00009722 case CK_ConstructorConversion:
9723 case CK_IntegralToPointer:
9724 case CK_ToVoid:
9725 case CK_VectorSplat:
9726 case CK_IntegralToFloating:
9727 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009728 case CK_CPointerToObjCPointerCast:
9729 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009730 case CK_AnyPointerToBlockPointerCast:
9731 case CK_ObjCObjectLValueCast:
9732 case CK_FloatingRealToComplex:
9733 case CK_FloatingComplexToReal:
9734 case CK_FloatingComplexCast:
9735 case CK_FloatingComplexToIntegralComplex:
9736 case CK_IntegralRealToComplex:
9737 case CK_IntegralComplexCast:
9738 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00009739 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +00009740 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +00009741 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009742 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009743 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00009744 case CK_FixedPointCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009745 llvm_unreachable("invalid cast kind for integral value");
9746
Eli Friedman9faf2f92011-03-25 19:07:11 +00009747 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009748 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009749 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00009750 case CK_ARCProduceObject:
9751 case CK_ARCConsumeObject:
9752 case CK_ARCReclaimReturnedObject:
9753 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009754 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009755 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009756
Richard Smith4ef685b2012-01-17 21:17:26 +00009757 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00009758 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009759 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009760 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009761 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009762
9763 case CK_MemberPointerToBoolean:
9764 case CK_PointerToBoolean:
9765 case CK_IntegralToBoolean:
9766 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009767 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009768 case CK_FloatingComplexToBoolean:
9769 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009770 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009771 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009772 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009773 uint64_t IntResult = BoolResult;
9774 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9775 IntResult = (uint64_t)-1;
9776 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009777 }
9778
Leonard Chanb4ba4672018-10-23 17:55:35 +00009779 case CK_FixedPointToBoolean: {
9780 // Unsigned padding does not affect this.
9781 APValue Val;
9782 if (!Evaluate(Val, Info, SubExpr))
9783 return false;
9784 return Success(Val.getInt().getBoolValue(), E);
9785 }
9786
Eli Friedmanc757de22011-03-25 00:43:55 +00009787 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009788 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009789 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009790
Eli Friedman742421e2009-02-20 01:15:07 +00009791 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009792 // Allow casts of address-of-label differences if they are no-ops
9793 // or narrowing. (The narrowing case isn't actually guaranteed to
9794 // be constant-evaluatable except in some narrow cases which are hard
9795 // to detect here. We let it through on the assumption the user knows
9796 // what they are doing.)
9797 if (Result.isAddrLabelDiff())
9798 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009799 // Only allow casts of lvalues if they are lossless.
9800 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9801 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009802
Richard Smith911e1422012-01-30 22:27:01 +00009803 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9804 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009805 }
Mike Stump11289f42009-09-09 15:08:12 +00009806
Eli Friedmanc757de22011-03-25 00:43:55 +00009807 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009808 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9809
John McCall45d55e42010-05-07 21:00:08 +00009810 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009811 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009812 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009813
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009814 if (LV.getLValueBase()) {
9815 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009816 // FIXME: Allow a larger integer size than the pointer size, and allow
9817 // narrowing back down to pointer width in subsequent integral casts.
9818 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009819 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009820 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009821
Richard Smithcf74da72011-11-16 07:18:12 +00009822 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009823 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009824 return true;
9825 }
9826
Yaxun Liu402804b2016-12-15 08:09:08 +00009827 uint64_t V;
9828 if (LV.isNullPointer())
9829 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9830 else
9831 V = LV.getLValueOffset().getQuantity();
9832
9833 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009834 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009835 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009836
Eli Friedmanc757de22011-03-25 00:43:55 +00009837 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009838 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009839 if (!EvaluateComplex(SubExpr, C, Info))
9840 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009841 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009842 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009843
Eli Friedmanc757de22011-03-25 00:43:55 +00009844 case CK_FloatingToIntegral: {
9845 APFloat F(0.0);
9846 if (!EvaluateFloat(SubExpr, F, Info))
9847 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009848
Richard Smith357362d2011-12-13 06:39:58 +00009849 APSInt Value;
9850 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9851 return false;
9852 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009853 }
9854 }
Mike Stump11289f42009-09-09 15:08:12 +00009855
Eli Friedmanc757de22011-03-25 00:43:55 +00009856 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009857}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009858
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009859bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9860 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009861 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009862 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9863 return false;
9864 if (!LV.isComplexInt())
9865 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009866 return Success(LV.getComplexIntReal(), E);
9867 }
9868
9869 return Visit(E->getSubExpr());
9870}
9871
Eli Friedman4e7a2412009-02-27 04:45:43 +00009872bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009873 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009874 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009875 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9876 return false;
9877 if (!LV.isComplexInt())
9878 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009879 return Success(LV.getComplexIntImag(), E);
9880 }
9881
Richard Smith4a678122011-10-24 18:44:57 +00009882 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009883 return Success(0, E);
9884}
9885
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009886bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9887 return Success(E->getPackLength(), E);
9888}
9889
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009890bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9891 return Success(E->getValue(), E);
9892}
9893
Leonard Chandb01c3a2018-06-20 17:19:40 +00009894bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9895 switch (E->getOpcode()) {
9896 default:
9897 // Invalid unary operators
9898 return Error(E);
9899 case UO_Plus:
9900 // The result is just the value.
9901 return Visit(E->getSubExpr());
9902 case UO_Minus: {
9903 if (!Visit(E->getSubExpr())) return false;
9904 if (!Result.isInt()) return Error(E);
9905 const APSInt &Value = Result.getInt();
9906 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
9907 SmallString<64> S;
9908 FixedPointValueToString(S, Value,
Leonard Chanc03642e2018-08-06 16:05:08 +00009909 Info.Ctx.getTypeInfo(E->getType()).Width);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009910 Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
9911 if (Info.noteUndefinedBehavior()) return false;
9912 }
9913 return Success(-Value, E);
9914 }
9915 case UO_LNot: {
9916 bool bres;
9917 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9918 return false;
9919 return Success(!bres, E);
9920 }
9921 }
9922}
9923
Chris Lattner05706e882008-07-11 18:11:29 +00009924//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009925// Float Evaluation
9926//===----------------------------------------------------------------------===//
9927
9928namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009929class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009930 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009931 APFloat &Result;
9932public:
9933 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009934 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009935
Richard Smith2e312c82012-03-03 22:46:17 +00009936 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009937 Result = V.getFloat();
9938 return true;
9939 }
Eli Friedman24c01542008-08-22 00:06:13 +00009940
Richard Smithfddd3842011-12-30 21:15:51 +00009941 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009942 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9943 return true;
9944 }
9945
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009946 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009947
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009948 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009949 bool VisitBinaryOperator(const BinaryOperator *E);
9950 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009951 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009952
John McCallb1fb0d32010-05-07 22:08:54 +00009953 bool VisitUnaryReal(const UnaryOperator *E);
9954 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009955
Richard Smithfddd3842011-12-30 21:15:51 +00009956 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009957};
9958} // end anonymous namespace
9959
9960static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009961 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009962 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009963}
9964
Jay Foad39c79802011-01-12 09:06:06 +00009965static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009966 QualType ResultTy,
9967 const Expr *Arg,
9968 bool SNaN,
9969 llvm::APFloat &Result) {
9970 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9971 if (!S) return false;
9972
9973 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9974
9975 llvm::APInt fill;
9976
9977 // Treat empty strings as if they were zero.
9978 if (S->getString().empty())
9979 fill = llvm::APInt(32, 0);
9980 else if (S->getString().getAsInteger(0, fill))
9981 return false;
9982
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009983 if (Context.getTargetInfo().isNan2008()) {
9984 if (SNaN)
9985 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9986 else
9987 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9988 } else {
9989 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9990 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9991 // a different encoding to what became a standard in 2008, and for pre-
9992 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9993 // sNaN. This is now known as "legacy NaN" encoding.
9994 if (SNaN)
9995 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9996 else
9997 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9998 }
9999
John McCall16291492010-02-28 13:00:19 +000010000 return true;
10001}
10002
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010003bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000010004 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010005 default:
10006 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10007
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010008 case Builtin::BI__builtin_huge_val:
10009 case Builtin::BI__builtin_huge_valf:
10010 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010011 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010012 case Builtin::BI__builtin_inf:
10013 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010014 case Builtin::BI__builtin_infl:
10015 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010016 const llvm::fltSemantics &Sem =
10017 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000010018 Result = llvm::APFloat::getInf(Sem);
10019 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010020 }
Mike Stump11289f42009-09-09 15:08:12 +000010021
John McCall16291492010-02-28 13:00:19 +000010022 case Builtin::BI__builtin_nans:
10023 case Builtin::BI__builtin_nansf:
10024 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010025 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010026 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10027 true, Result))
10028 return Error(E);
10029 return true;
John McCall16291492010-02-28 13:00:19 +000010030
Chris Lattner0b7282e2008-10-06 06:31:58 +000010031 case Builtin::BI__builtin_nan:
10032 case Builtin::BI__builtin_nanf:
10033 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010034 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000010035 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000010036 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000010037 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10038 false, Result))
10039 return Error(E);
10040 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010041
10042 case Builtin::BI__builtin_fabs:
10043 case Builtin::BI__builtin_fabsf:
10044 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010045 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010046 if (!EvaluateFloat(E->getArg(0), Result, Info))
10047 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010048
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010049 if (Result.isNegative())
10050 Result.changeSign();
10051 return true;
10052
Richard Smith8889a3d2013-06-13 06:26:32 +000010053 // FIXME: Builtin::BI__builtin_powi
10054 // FIXME: Builtin::BI__builtin_powif
10055 // FIXME: Builtin::BI__builtin_powil
10056
Mike Stump11289f42009-09-09 15:08:12 +000010057 case Builtin::BI__builtin_copysign:
10058 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010059 case Builtin::BI__builtin_copysignl:
10060 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010061 APFloat RHS(0.);
10062 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
10063 !EvaluateFloat(E->getArg(1), RHS, Info))
10064 return false;
10065 Result.copySign(RHS);
10066 return true;
10067 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010068 }
10069}
10070
John McCallb1fb0d32010-05-07 22:08:54 +000010071bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000010072 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10073 ComplexValue CV;
10074 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10075 return false;
10076 Result = CV.FloatReal;
10077 return true;
10078 }
10079
10080 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000010081}
10082
10083bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000010084 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10085 ComplexValue CV;
10086 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10087 return false;
10088 Result = CV.FloatImag;
10089 return true;
10090 }
10091
Richard Smith4a678122011-10-24 18:44:57 +000010092 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000010093 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
10094 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000010095 return true;
10096}
10097
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010098bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010099 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010100 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000010101 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000010102 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000010103 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000010104 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
10105 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010106 Result.changeSign();
10107 return true;
10108 }
10109}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010110
Eli Friedman24c01542008-08-22 00:06:13 +000010111bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000010112 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10113 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000010114
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010115 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000010116 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010117 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000010118 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000010119 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
10120 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000010121}
10122
10123bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
10124 Result = E->getValue();
10125 return true;
10126}
10127
Peter Collingbournee9200682011-05-13 03:29:01 +000010128bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
10129 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000010130
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010131 switch (E->getCastKind()) {
10132 default:
Richard Smith11562c52011-10-28 17:51:58 +000010133 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010134
10135 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010136 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000010137 return EvaluateInteger(SubExpr, IntResult, Info) &&
10138 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
10139 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000010140 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010141
10142 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010143 if (!Visit(SubExpr))
10144 return false;
Richard Smith357362d2011-12-13 06:39:58 +000010145 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
10146 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000010147 }
John McCalld7646252010-11-14 08:17:51 +000010148
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010149 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000010150 ComplexValue V;
10151 if (!EvaluateComplex(SubExpr, V, Info))
10152 return false;
10153 Result = V.getComplexFloatReal();
10154 return true;
10155 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010156 }
Eli Friedman9a156e52008-11-12 09:44:48 +000010157}
10158
Eli Friedman24c01542008-08-22 00:06:13 +000010159//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010160// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000010161//===----------------------------------------------------------------------===//
10162
10163namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000010164class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010165 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000010166 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000010167
Anders Carlsson537969c2008-11-16 20:27:53 +000010168public:
John McCall93d91dc2010-05-07 17:22:02 +000010169 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000010170 : ExprEvaluatorBaseTy(info), Result(Result) {}
10171
Richard Smith2e312c82012-03-03 22:46:17 +000010172 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010173 Result.setFrom(V);
10174 return true;
10175 }
Mike Stump11289f42009-09-09 15:08:12 +000010176
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010177 bool ZeroInitialization(const Expr *E);
10178
Anders Carlsson537969c2008-11-16 20:27:53 +000010179 //===--------------------------------------------------------------------===//
10180 // Visitor Methods
10181 //===--------------------------------------------------------------------===//
10182
Peter Collingbournee9200682011-05-13 03:29:01 +000010183 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000010184 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000010185 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010186 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010187 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010188};
10189} // end anonymous namespace
10190
John McCall93d91dc2010-05-07 17:22:02 +000010191static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
10192 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000010193 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010194 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010195}
10196
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010197bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000010198 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010199 if (ElemTy->isRealFloatingType()) {
10200 Result.makeComplexFloat();
10201 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10202 Result.FloatReal = Zero;
10203 Result.FloatImag = Zero;
10204 } else {
10205 Result.makeComplexInt();
10206 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10207 Result.IntReal = Zero;
10208 Result.IntImag = Zero;
10209 }
10210 return true;
10211}
10212
Peter Collingbournee9200682011-05-13 03:29:01 +000010213bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10214 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010215
10216 if (SubExpr->getType()->isRealFloatingType()) {
10217 Result.makeComplexFloat();
10218 APFloat &Imag = Result.FloatImag;
10219 if (!EvaluateFloat(SubExpr, Imag, Info))
10220 return false;
10221
10222 Result.FloatReal = APFloat(Imag.getSemantics());
10223 return true;
10224 } else {
10225 assert(SubExpr->getType()->isIntegerType() &&
10226 "Unexpected imaginary literal.");
10227
10228 Result.makeComplexInt();
10229 APSInt &Imag = Result.IntImag;
10230 if (!EvaluateInteger(SubExpr, Imag, Info))
10231 return false;
10232
10233 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10234 return true;
10235 }
10236}
10237
Peter Collingbournee9200682011-05-13 03:29:01 +000010238bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010239
John McCallfcef3cf2010-12-14 17:51:41 +000010240 switch (E->getCastKind()) {
10241 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010242 case CK_BaseToDerived:
10243 case CK_DerivedToBase:
10244 case CK_UncheckedDerivedToBase:
10245 case CK_Dynamic:
10246 case CK_ToUnion:
10247 case CK_ArrayToPointerDecay:
10248 case CK_FunctionToPointerDecay:
10249 case CK_NullToPointer:
10250 case CK_NullToMemberPointer:
10251 case CK_BaseToDerivedMemberPointer:
10252 case CK_DerivedToBaseMemberPointer:
10253 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000010254 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000010255 case CK_ConstructorConversion:
10256 case CK_IntegralToPointer:
10257 case CK_PointerToIntegral:
10258 case CK_PointerToBoolean:
10259 case CK_ToVoid:
10260 case CK_VectorSplat:
10261 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000010262 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000010263 case CK_IntegralToBoolean:
10264 case CK_IntegralToFloating:
10265 case CK_FloatingToIntegral:
10266 case CK_FloatingToBoolean:
10267 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000010268 case CK_CPointerToObjCPointerCast:
10269 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010270 case CK_AnyPointerToBlockPointerCast:
10271 case CK_ObjCObjectLValueCast:
10272 case CK_FloatingComplexToReal:
10273 case CK_FloatingComplexToBoolean:
10274 case CK_IntegralComplexToReal:
10275 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000010276 case CK_ARCProduceObject:
10277 case CK_ARCConsumeObject:
10278 case CK_ARCReclaimReturnedObject:
10279 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000010280 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000010281 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000010282 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000010283 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000010284 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000010285 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000010286 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000010287 case CK_FixedPointToBoolean:
John McCallfcef3cf2010-12-14 17:51:41 +000010288 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000010289
John McCallfcef3cf2010-12-14 17:51:41 +000010290 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010291 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000010292 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +000010293 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010294
10295 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000010296 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010297 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010298 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010299
10300 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010301 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000010302 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010303 return false;
10304
John McCallfcef3cf2010-12-14 17:51:41 +000010305 Result.makeComplexFloat();
10306 Result.FloatImag = APFloat(Real.getSemantics());
10307 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010308 }
10309
John McCallfcef3cf2010-12-14 17:51:41 +000010310 case CK_FloatingComplexCast: {
10311 if (!Visit(E->getSubExpr()))
10312 return false;
10313
10314 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10315 QualType From
10316 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10317
Richard Smith357362d2011-12-13 06:39:58 +000010318 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
10319 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010320 }
10321
10322 case CK_FloatingComplexToIntegralComplex: {
10323 if (!Visit(E->getSubExpr()))
10324 return false;
10325
10326 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10327 QualType From
10328 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10329 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000010330 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
10331 To, Result.IntReal) &&
10332 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
10333 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010334 }
10335
10336 case CK_IntegralRealToComplex: {
10337 APSInt &Real = Result.IntReal;
10338 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
10339 return false;
10340
10341 Result.makeComplexInt();
10342 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
10343 return true;
10344 }
10345
10346 case CK_IntegralComplexCast: {
10347 if (!Visit(E->getSubExpr()))
10348 return false;
10349
10350 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10351 QualType From
10352 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10353
Richard Smith911e1422012-01-30 22:27:01 +000010354 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
10355 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010356 return true;
10357 }
10358
10359 case CK_IntegralComplexToFloatingComplex: {
10360 if (!Visit(E->getSubExpr()))
10361 return false;
10362
Ted Kremenek28831752012-08-23 20:46:57 +000010363 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010364 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000010365 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010366 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000010367 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
10368 To, Result.FloatReal) &&
10369 HandleIntToFloatCast(Info, E, From, Result.IntImag,
10370 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010371 }
10372 }
10373
10374 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010375}
10376
John McCall93d91dc2010-05-07 17:22:02 +000010377bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000010378 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000010379 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10380
Chandler Carrutha216cad2014-10-11 00:57:18 +000010381 // Track whether the LHS or RHS is real at the type system level. When this is
10382 // the case we can simplify our evaluation strategy.
10383 bool LHSReal = false, RHSReal = false;
10384
10385 bool LHSOK;
10386 if (E->getLHS()->getType()->isRealFloatingType()) {
10387 LHSReal = true;
10388 APFloat &Real = Result.FloatReal;
10389 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
10390 if (LHSOK) {
10391 Result.makeComplexFloat();
10392 Result.FloatImag = APFloat(Real.getSemantics());
10393 }
10394 } else {
10395 LHSOK = Visit(E->getLHS());
10396 }
George Burgess IVa145e252016-05-25 22:38:36 +000010397 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000010398 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010399
John McCall93d91dc2010-05-07 17:22:02 +000010400 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010401 if (E->getRHS()->getType()->isRealFloatingType()) {
10402 RHSReal = true;
10403 APFloat &Real = RHS.FloatReal;
10404 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
10405 return false;
10406 RHS.makeComplexFloat();
10407 RHS.FloatImag = APFloat(Real.getSemantics());
10408 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000010409 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010410
Chandler Carrutha216cad2014-10-11 00:57:18 +000010411 assert(!(LHSReal && RHSReal) &&
10412 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010413 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010414 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000010415 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010416 if (Result.isComplexFloat()) {
10417 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
10418 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010419 if (LHSReal)
10420 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10421 else if (!RHSReal)
10422 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
10423 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010424 } else {
10425 Result.getComplexIntReal() += RHS.getComplexIntReal();
10426 Result.getComplexIntImag() += RHS.getComplexIntImag();
10427 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010428 break;
John McCalle3027922010-08-25 11:45:40 +000010429 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010430 if (Result.isComplexFloat()) {
10431 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
10432 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010433 if (LHSReal) {
10434 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10435 Result.getComplexFloatImag().changeSign();
10436 } else if (!RHSReal) {
10437 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
10438 APFloat::rmNearestTiesToEven);
10439 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010440 } else {
10441 Result.getComplexIntReal() -= RHS.getComplexIntReal();
10442 Result.getComplexIntImag() -= RHS.getComplexIntImag();
10443 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010444 break;
John McCalle3027922010-08-25 11:45:40 +000010445 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010446 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010447 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000010448 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010449 // following naming scheme:
10450 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000010451 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010452 APFloat &A = LHS.getComplexFloatReal();
10453 APFloat &B = LHS.getComplexFloatImag();
10454 APFloat &C = RHS.getComplexFloatReal();
10455 APFloat &D = RHS.getComplexFloatImag();
10456 APFloat &ResR = Result.getComplexFloatReal();
10457 APFloat &ResI = Result.getComplexFloatImag();
10458 if (LHSReal) {
10459 assert(!RHSReal && "Cannot have two real operands for a complex op!");
10460 ResR = A * C;
10461 ResI = A * D;
10462 } else if (RHSReal) {
10463 ResR = C * A;
10464 ResI = C * B;
10465 } else {
10466 // In the fully general case, we need to handle NaNs and infinities
10467 // robustly.
10468 APFloat AC = A * C;
10469 APFloat BD = B * D;
10470 APFloat AD = A * D;
10471 APFloat BC = B * C;
10472 ResR = AC - BD;
10473 ResI = AD + BC;
10474 if (ResR.isNaN() && ResI.isNaN()) {
10475 bool Recalc = false;
10476 if (A.isInfinity() || B.isInfinity()) {
10477 A = APFloat::copySign(
10478 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10479 B = APFloat::copySign(
10480 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10481 if (C.isNaN())
10482 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10483 if (D.isNaN())
10484 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10485 Recalc = true;
10486 }
10487 if (C.isInfinity() || D.isInfinity()) {
10488 C = APFloat::copySign(
10489 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10490 D = APFloat::copySign(
10491 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10492 if (A.isNaN())
10493 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10494 if (B.isNaN())
10495 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10496 Recalc = true;
10497 }
10498 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
10499 AD.isInfinity() || BC.isInfinity())) {
10500 if (A.isNaN())
10501 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10502 if (B.isNaN())
10503 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10504 if (C.isNaN())
10505 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10506 if (D.isNaN())
10507 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10508 Recalc = true;
10509 }
10510 if (Recalc) {
10511 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
10512 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
10513 }
10514 }
10515 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010516 } else {
John McCall93d91dc2010-05-07 17:22:02 +000010517 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000010518 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010519 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
10520 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000010521 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010522 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
10523 LHS.getComplexIntImag() * RHS.getComplexIntReal());
10524 }
10525 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010526 case BO_Div:
10527 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010528 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000010529 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010530 // following naming scheme:
10531 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010532 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010533 APFloat &A = LHS.getComplexFloatReal();
10534 APFloat &B = LHS.getComplexFloatImag();
10535 APFloat &C = RHS.getComplexFloatReal();
10536 APFloat &D = RHS.getComplexFloatImag();
10537 APFloat &ResR = Result.getComplexFloatReal();
10538 APFloat &ResI = Result.getComplexFloatImag();
10539 if (RHSReal) {
10540 ResR = A / C;
10541 ResI = B / C;
10542 } else {
10543 if (LHSReal) {
10544 // No real optimizations we can do here, stub out with zero.
10545 B = APFloat::getZero(A.getSemantics());
10546 }
10547 int DenomLogB = 0;
10548 APFloat MaxCD = maxnum(abs(C), abs(D));
10549 if (MaxCD.isFinite()) {
10550 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000010551 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
10552 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010553 }
10554 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000010555 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
10556 APFloat::rmNearestTiesToEven);
10557 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
10558 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010559 if (ResR.isNaN() && ResI.isNaN()) {
10560 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
10561 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
10562 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
10563 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
10564 D.isFinite()) {
10565 A = APFloat::copySign(
10566 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10567 B = APFloat::copySign(
10568 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10569 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
10570 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
10571 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
10572 C = APFloat::copySign(
10573 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10574 D = APFloat::copySign(
10575 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10576 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
10577 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
10578 }
10579 }
10580 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010581 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010582 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
10583 return Error(E, diag::note_expr_divide_by_zero);
10584
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010585 ComplexValue LHS = Result;
10586 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
10587 RHS.getComplexIntImag() * RHS.getComplexIntImag();
10588 Result.getComplexIntReal() =
10589 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10590 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10591 Result.getComplexIntImag() =
10592 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10593 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10594 }
10595 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010596 }
10597
John McCall93d91dc2010-05-07 17:22:02 +000010598 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010599}
10600
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010601bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10602 // Get the operand value into 'Result'.
10603 if (!Visit(E->getSubExpr()))
10604 return false;
10605
10606 switch (E->getOpcode()) {
10607 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010608 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010609 case UO_Extension:
10610 return true;
10611 case UO_Plus:
10612 // The result is always just the subexpr.
10613 return true;
10614 case UO_Minus:
10615 if (Result.isComplexFloat()) {
10616 Result.getComplexFloatReal().changeSign();
10617 Result.getComplexFloatImag().changeSign();
10618 }
10619 else {
10620 Result.getComplexIntReal() = -Result.getComplexIntReal();
10621 Result.getComplexIntImag() = -Result.getComplexIntImag();
10622 }
10623 return true;
10624 case UO_Not:
10625 if (Result.isComplexFloat())
10626 Result.getComplexFloatImag().changeSign();
10627 else
10628 Result.getComplexIntImag() = -Result.getComplexIntImag();
10629 return true;
10630 }
10631}
10632
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010633bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10634 if (E->getNumInits() == 2) {
10635 if (E->getType()->isComplexType()) {
10636 Result.makeComplexFloat();
10637 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10638 return false;
10639 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10640 return false;
10641 } else {
10642 Result.makeComplexInt();
10643 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10644 return false;
10645 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10646 return false;
10647 }
10648 return true;
10649 }
10650 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10651}
10652
Anders Carlsson537969c2008-11-16 20:27:53 +000010653//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000010654// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10655// implicit conversion.
10656//===----------------------------------------------------------------------===//
10657
10658namespace {
10659class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000010660 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010661 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000010662 APValue &Result;
10663public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010664 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10665 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000010666
10667 bool Success(const APValue &V, const Expr *E) {
10668 Result = V;
10669 return true;
10670 }
10671
10672 bool ZeroInitialization(const Expr *E) {
10673 ImplicitValueInitExpr VIE(
10674 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010675 // For atomic-qualified class (and array) types in C++, initialize the
10676 // _Atomic-wrapped subobject directly, in-place.
10677 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10678 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000010679 }
10680
10681 bool VisitCastExpr(const CastExpr *E) {
10682 switch (E->getCastKind()) {
10683 default:
10684 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10685 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010686 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10687 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000010688 }
10689 }
10690};
10691} // end anonymous namespace
10692
Richard Smith64cb9ca2017-02-22 22:09:50 +000010693static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10694 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000010695 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010696 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000010697}
10698
10699//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000010700// Void expression evaluation, primarily for a cast to void on the LHS of a
10701// comma operator
10702//===----------------------------------------------------------------------===//
10703
10704namespace {
10705class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010706 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000010707public:
10708 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10709
Richard Smith2e312c82012-03-03 22:46:17 +000010710 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000010711
Richard Smith7cd577b2017-08-17 19:35:50 +000010712 bool ZeroInitialization(const Expr *E) { return true; }
10713
Richard Smith42d3af92011-12-07 00:43:50 +000010714 bool VisitCastExpr(const CastExpr *E) {
10715 switch (E->getCastKind()) {
10716 default:
10717 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10718 case CK_ToVoid:
10719 VisitIgnoredValue(E->getSubExpr());
10720 return true;
10721 }
10722 }
Hal Finkela8443c32014-07-17 14:49:58 +000010723
10724 bool VisitCallExpr(const CallExpr *E) {
10725 switch (E->getBuiltinCallee()) {
10726 default:
10727 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10728 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000010729 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000010730 // The argument is not evaluated!
10731 return true;
10732 }
10733 }
Richard Smith42d3af92011-12-07 00:43:50 +000010734};
10735} // end anonymous namespace
10736
10737static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10738 assert(E->isRValue() && E->getType()->isVoidType());
10739 return VoidExprEvaluator(Info).Visit(E);
10740}
10741
10742//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000010743// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000010744//===----------------------------------------------------------------------===//
10745
Richard Smith2e312c82012-03-03 22:46:17 +000010746static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000010747 // In C, function designators are not lvalues, but we evaluate them as if they
10748 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000010749 QualType T = E->getType();
10750 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000010751 LValue LV;
10752 if (!EvaluateLValue(E, LV, Info))
10753 return false;
10754 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010755 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010756 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000010757 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010758 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010759 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010760 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010761 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000010762 LValue LV;
10763 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010764 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010765 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010766 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000010767 llvm::APFloat F(0.0);
10768 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010769 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000010770 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000010771 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000010772 ComplexValue C;
10773 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010774 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010775 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010776 } else if (T->isFixedPointType()) {
10777 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010778 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000010779 MemberPtr P;
10780 if (!EvaluateMemberPointer(E, P, Info))
10781 return false;
10782 P.moveInto(Result);
10783 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000010784 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010785 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010786 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010787 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000010788 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010789 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010790 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010791 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010792 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010793 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000010794 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010795 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010796 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010797 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010798 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000010799 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000010800 if (!EvaluateVoid(E, Info))
10801 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010802 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010803 QualType Unqual = T.getAtomicUnqualifiedType();
10804 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10805 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010806 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010807 if (!EvaluateAtomic(E, &LV, Value, Info))
10808 return false;
10809 } else {
10810 if (!EvaluateAtomic(E, nullptr, Result, Info))
10811 return false;
10812 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010813 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010814 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010815 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010816 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010817 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010818 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010819 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010820
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010821 return true;
10822}
10823
Richard Smithb228a862012-02-15 02:18:13 +000010824/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10825/// cases, the in-place evaluation is essential, since later initializers for
10826/// an object can indirectly refer to subobjects which were initialized earlier.
10827static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010828 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010829 assert(!E->isValueDependent());
10830
Richard Smith7525ff62013-05-09 07:14:00 +000010831 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010832 return false;
10833
10834 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010835 // Evaluate arrays and record types in-place, so that later initializers can
10836 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010837 QualType T = E->getType();
10838 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010839 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010840 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010841 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010842 else if (T->isAtomicType()) {
10843 QualType Unqual = T.getAtomicUnqualifiedType();
10844 if (Unqual->isArrayType() || Unqual->isRecordType())
10845 return EvaluateAtomic(E, &This, Result, Info);
10846 }
Richard Smithed5165f2011-11-04 05:33:44 +000010847 }
10848
10849 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010850 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010851}
10852
Richard Smithf57d8cb2011-12-09 22:58:01 +000010853/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10854/// lvalue-to-rvalue cast if it is an lvalue.
10855static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010856 if (E->getType().isNull())
10857 return false;
10858
Nick Lewyckyc190f962017-05-02 01:06:16 +000010859 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010860 return false;
10861
Richard Smith2e312c82012-03-03 22:46:17 +000010862 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010863 return false;
10864
10865 if (E->isGLValue()) {
10866 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010867 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010868 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010869 return false;
10870 }
10871
Richard Smith2e312c82012-03-03 22:46:17 +000010872 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010873 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010874}
Richard Smith11562c52011-10-28 17:51:58 +000010875
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010876static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010877 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010878 // Fast-path evaluations of integer literals, since we sometimes see files
10879 // containing vast quantities of these.
10880 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10881 Result.Val = APValue(APSInt(L->getValue(),
10882 L->getType()->isUnsignedIntegerType()));
10883 IsConst = true;
10884 return true;
10885 }
James Dennett0492ef02014-03-14 17:44:10 +000010886
10887 // This case should be rare, but we need to check it before we check on
10888 // the type below.
10889 if (Exp->getType().isNull()) {
10890 IsConst = false;
10891 return true;
10892 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010893
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010894 // FIXME: Evaluating values of large array and record types can cause
10895 // performance problems. Only do so in C++11 for now.
10896 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10897 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010898 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010899 IsConst = false;
10900 return true;
10901 }
10902 return false;
10903}
10904
Fangrui Song407659a2018-11-30 23:41:18 +000010905static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10906 Expr::SideEffectsKind SEK) {
10907 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10908 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10909}
10910
10911static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
10912 const ASTContext &Ctx, EvalInfo &Info) {
10913 bool IsConst;
10914 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
10915 return IsConst;
10916
10917 return EvaluateAsRValue(Info, E, Result.Val);
10918}
10919
10920static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
10921 const ASTContext &Ctx,
10922 Expr::SideEffectsKind AllowSideEffects,
10923 EvalInfo &Info) {
10924 if (!E->getType()->isIntegralOrEnumerationType())
10925 return false;
10926
10927 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
10928 !ExprResult.Val.isInt() ||
10929 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10930 return false;
10931
10932 return true;
10933}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010934
Richard Smith7b553f12011-10-29 00:50:52 +000010935/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010936/// any crazy technique (that has nothing to do with language standards) that
10937/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010938/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10939/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000010940bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
10941 bool InConstantContext) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010942 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000010943 Info.InConstantContext = InConstantContext;
10944 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000010945}
10946
Jay Foad39c79802011-01-12 09:06:06 +000010947bool Expr::EvaluateAsBooleanCondition(bool &Result,
10948 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010949 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010950 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010951 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010952}
10953
Fangrui Song407659a2018-11-30 23:41:18 +000010954bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Richard Smith5fab0c92011-12-28 19:48:30 +000010955 SideEffectsKind AllowSideEffects) const {
Fangrui Song407659a2018-11-30 23:41:18 +000010956 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
10957 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000010958}
10959
Richard Trieube234c32016-04-21 21:04:55 +000010960bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10961 SideEffectsKind AllowSideEffects) const {
10962 if (!getType()->isRealFloatingType())
10963 return false;
10964
10965 EvalResult ExprResult;
10966 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000010967 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000010968 return false;
10969
10970 Result = ExprResult.Val.getFloat();
10971 return true;
10972}
10973
Jay Foad39c79802011-01-12 09:06:06 +000010974bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010975 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010976
John McCall45d55e42010-05-07 21:00:08 +000010977 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010978 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10979 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000010980 Ctx.getLValueReferenceType(getType()), LV,
10981 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000010982 return false;
10983
Richard Smith2e312c82012-03-03 22:46:17 +000010984 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010985 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010986}
10987
Reid Kleckner1a840d22018-05-10 18:57:35 +000010988bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
10989 const ASTContext &Ctx) const {
10990 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
10991 EvalInfo Info(Ctx, Result, EM);
10992 if (!::Evaluate(Result.Val, Info, this))
10993 return false;
10994
10995 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
10996 Usage);
10997}
10998
Richard Smithd0b4dd62011-12-19 06:19:21 +000010999bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
11000 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011001 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000011002 // FIXME: Evaluating initializers for large array and record types can cause
11003 // performance problems. Only do so in C++11 for now.
11004 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011005 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000011006 return false;
11007
Richard Smithd0b4dd62011-12-19 06:19:21 +000011008 Expr::EvalStatus EStatus;
11009 EStatus.Diag = &Notes;
11010
Richard Smith0c6124b2015-12-03 01:36:22 +000011011 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
11012 ? EvalInfo::EM_ConstantExpression
11013 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000011014 InitInfo.setEvaluatingDecl(VD, Value);
Fangrui Song407659a2018-11-30 23:41:18 +000011015 InitInfo.InConstantContext = true;
Richard Smithd0b4dd62011-12-19 06:19:21 +000011016
11017 LValue LVal;
11018 LVal.set(VD);
11019
Richard Smithfddd3842011-12-30 21:15:51 +000011020 // C++11 [basic.start.init]p2:
11021 // Variables with static storage duration or thread storage duration shall be
11022 // zero-initialized before any other initialization takes place.
11023 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011024 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000011025 !VD->getType()->isReferenceType()) {
11026 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000011027 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000011028 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000011029 return false;
11030 }
11031
Richard Smith7525ff62013-05-09 07:14:00 +000011032 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
11033 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000011034 EStatus.HasSideEffects)
11035 return false;
11036
11037 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
11038 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000011039}
11040
Richard Smith7b553f12011-10-29 00:50:52 +000011041/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
11042/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000011043bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000011044 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000011045 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000011046 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000011047}
Anders Carlsson59689ed2008-11-22 21:04:56 +000011048
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000011049APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011050 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Fangrui Song407659a2018-11-30 23:41:18 +000011051 EvalResult EVResult;
11052 EVResult.Diag = Diag;
11053 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
11054 Info.InConstantContext = true;
11055
11056 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000011057 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000011058 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000011059 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000011060
Fangrui Song407659a2018-11-30 23:41:18 +000011061 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000011062}
John McCall864e3962010-05-07 05:32:02 +000011063
David Bolvansky3b6ae572018-10-18 20:49:06 +000011064APSInt Expr::EvaluateKnownConstIntCheckOverflow(
11065 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Fangrui Song407659a2018-11-30 23:41:18 +000011066 EvalResult EVResult;
11067 EVResult.Diag = Diag;
11068 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11069 Info.InConstantContext = true;
11070
11071 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000011072 (void)Result;
11073 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000011074 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000011075
Fangrui Song407659a2018-11-30 23:41:18 +000011076 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000011077}
11078
Richard Smithe9ff7702013-11-05 22:23:30 +000011079void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011080 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000011081 EvalResult EVResult;
11082 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
11083 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11084 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011085 }
11086}
11087
Richard Smithe6c01442013-06-05 00:46:14 +000011088bool Expr::EvalResult::isGlobalLValue() const {
11089 assert(Val.isLValue());
11090 return IsGlobalLValue(Val.getLValueBase());
11091}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000011092
11093
John McCall864e3962010-05-07 05:32:02 +000011094/// isIntegerConstantExpr - this recursive routine will test if an expression is
11095/// an integer constant expression.
11096
11097/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
11098/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000011099
11100// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000011101// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
11102// and a (possibly null) SourceLocation indicating the location of the problem.
11103//
John McCall864e3962010-05-07 05:32:02 +000011104// Note that to reduce code duplication, this helper does no evaluation
11105// itself; the caller checks whether the expression is evaluatable, and
11106// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000011107// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000011108
Dan Gohman28ade552010-07-26 21:25:24 +000011109namespace {
11110
Richard Smith9e575da2012-12-28 13:25:52 +000011111enum ICEKind {
11112 /// This expression is an ICE.
11113 IK_ICE,
11114 /// This expression is not an ICE, but if it isn't evaluated, it's
11115 /// a legal subexpression for an ICE. This return value is used to handle
11116 /// the comma operator in C99 mode, and non-constant subexpressions.
11117 IK_ICEIfUnevaluated,
11118 /// This expression is not an ICE, and is not a legal subexpression for one.
11119 IK_NotICE
11120};
11121
John McCall864e3962010-05-07 05:32:02 +000011122struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000011123 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000011124 SourceLocation Loc;
11125
Richard Smith9e575da2012-12-28 13:25:52 +000011126 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000011127};
11128
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011129}
Dan Gohman28ade552010-07-26 21:25:24 +000011130
Richard Smith9e575da2012-12-28 13:25:52 +000011131static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
11132
11133static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000011134
Craig Toppera31a8822013-08-22 07:09:37 +000011135static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000011136 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000011137 Expr::EvalStatus Status;
11138 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11139
11140 Info.InConstantContext = true;
11141 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000011142 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011143 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000011144
John McCall864e3962010-05-07 05:32:02 +000011145 return NoDiag();
11146}
11147
Craig Toppera31a8822013-08-22 07:09:37 +000011148static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000011149 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000011150 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011151 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011152
11153 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000011154#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000011155#define STMT(Node, Base) case Expr::Node##Class:
11156#define EXPR(Node, Base)
11157#include "clang/AST/StmtNodes.inc"
11158 case Expr::PredefinedExprClass:
11159 case Expr::FloatingLiteralClass:
11160 case Expr::ImaginaryLiteralClass:
11161 case Expr::StringLiteralClass:
11162 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011163 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000011164 case Expr::MemberExprClass:
11165 case Expr::CompoundAssignOperatorClass:
11166 case Expr::CompoundLiteralExprClass:
11167 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000011168 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000011169 case Expr::ArrayInitLoopExprClass:
11170 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000011171 case Expr::NoInitExprClass:
11172 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000011173 case Expr::ImplicitValueInitExprClass:
11174 case Expr::ParenListExprClass:
11175 case Expr::VAArgExprClass:
11176 case Expr::AddrLabelExprClass:
11177 case Expr::StmtExprClass:
11178 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000011179 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000011180 case Expr::CXXDynamicCastExprClass:
11181 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000011182 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000011183 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000011184 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011185 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000011186 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011187 case Expr::CXXThisExprClass:
11188 case Expr::CXXThrowExprClass:
11189 case Expr::CXXNewExprClass:
11190 case Expr::CXXDeleteExprClass:
11191 case Expr::CXXPseudoDestructorExprClass:
11192 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000011193 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000011194 case Expr::DependentScopeDeclRefExprClass:
11195 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000011196 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000011197 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000011198 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000011199 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000011200 case Expr::CXXTemporaryObjectExprClass:
11201 case Expr::CXXUnresolvedConstructExprClass:
11202 case Expr::CXXDependentScopeMemberExprClass:
11203 case Expr::UnresolvedMemberExprClass:
11204 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000011205 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011206 case Expr::ObjCArrayLiteralClass:
11207 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011208 case Expr::ObjCEncodeExprClass:
11209 case Expr::ObjCMessageExprClass:
11210 case Expr::ObjCSelectorExprClass:
11211 case Expr::ObjCProtocolExprClass:
11212 case Expr::ObjCIvarRefExprClass:
11213 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011214 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000011215 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000011216 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000011217 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000011218 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000011219 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000011220 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000011221 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000011222 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000011223 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000011224 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000011225 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000011226 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000011227 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000011228 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000011229 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000011230 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000011231 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011232 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000011233 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011234 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011235 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000011236
Richard Smithf137f932014-01-25 20:50:08 +000011237 case Expr::InitListExprClass: {
11238 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
11239 // form "T x = { a };" is equivalent to "T x = a;".
11240 // Unless we're initializing a reference, T is a scalar as it is known to be
11241 // of integral or enumeration type.
11242 if (E->isRValue())
11243 if (cast<InitListExpr>(E)->getNumInits() == 1)
11244 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011245 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000011246 }
11247
Douglas Gregor820ba7b2011-01-04 17:33:58 +000011248 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000011249 case Expr::GNUNullExprClass:
11250 // GCC considers the GNU __null value to be an integral constant expression.
11251 return NoDiag();
11252
John McCall7c454bb2011-07-15 05:09:51 +000011253 case Expr::SubstNonTypeTemplateParmExprClass:
11254 return
11255 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
11256
Bill Wendling7c44da22018-10-31 03:48:47 +000011257 case Expr::ConstantExprClass:
11258 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
11259
John McCall864e3962010-05-07 05:32:02 +000011260 case Expr::ParenExprClass:
11261 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000011262 case Expr::GenericSelectionExprClass:
11263 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011264 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000011265 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011266 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011267 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000011268 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000011269 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000011270 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000011271 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000011272 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000011273 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011274 return NoDiag();
11275 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000011276 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000011277 // C99 6.6/3 allows function calls within unevaluated subexpressions of
11278 // constant expressions, but they can never be ICEs because an ICE cannot
11279 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000011280 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000011281 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000011282 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011283 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011284 }
Richard Smith6365c912012-02-24 22:12:32 +000011285 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011286 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
11287 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000011288 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011289 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000011290 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000011291 // Parameter variables are never constants. Without this check,
11292 // getAnyInitializer() can find a default argument, which leads
11293 // to chaos.
11294 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000011295 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011296
11297 // C++ 7.1.5.1p2
11298 // A variable of non-volatile const-qualified integral or enumeration
11299 // type initialized by an ICE can be used in ICEs.
11300 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000011301 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000011302 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000011303
Richard Smithd0b4dd62011-12-19 06:19:21 +000011304 const VarDecl *VD;
11305 // Look for a declaration of this variable that has an initializer, and
11306 // check whether it is an ICE.
11307 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
11308 return NoDiag();
11309 else
Richard Smith9e575da2012-12-28 13:25:52 +000011310 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011311 }
11312 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011313 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000011314 }
John McCall864e3962010-05-07 05:32:02 +000011315 case Expr::UnaryOperatorClass: {
11316 const UnaryOperator *Exp = cast<UnaryOperator>(E);
11317 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011318 case UO_PostInc:
11319 case UO_PostDec:
11320 case UO_PreInc:
11321 case UO_PreDec:
11322 case UO_AddrOf:
11323 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000011324 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000011325 // C99 6.6/3 allows increment and decrement within unevaluated
11326 // subexpressions of constant expressions, but they can never be ICEs
11327 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011328 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000011329 case UO_Extension:
11330 case UO_LNot:
11331 case UO_Plus:
11332 case UO_Minus:
11333 case UO_Not:
11334 case UO_Real:
11335 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000011336 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011337 }
Reid Klecknere540d972018-11-01 17:51:48 +000011338 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000011339 }
11340 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000011341 // Note that per C99, offsetof must be an ICE. And AFAIK, using
11342 // EvaluateAsRValue matches the proposed gcc behavior for cases like
11343 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
11344 // compliance: we should warn earlier for offsetof expressions with
11345 // array subscripts that aren't ICEs, and if the array subscripts
11346 // are ICEs, the value of the offsetof must be an integer constant.
11347 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011348 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000011349 case Expr::UnaryExprOrTypeTraitExprClass: {
11350 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
11351 if ((Exp->getKind() == UETT_SizeOf) &&
11352 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011353 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011354 return NoDiag();
11355 }
11356 case Expr::BinaryOperatorClass: {
11357 const BinaryOperator *Exp = cast<BinaryOperator>(E);
11358 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011359 case BO_PtrMemD:
11360 case BO_PtrMemI:
11361 case BO_Assign:
11362 case BO_MulAssign:
11363 case BO_DivAssign:
11364 case BO_RemAssign:
11365 case BO_AddAssign:
11366 case BO_SubAssign:
11367 case BO_ShlAssign:
11368 case BO_ShrAssign:
11369 case BO_AndAssign:
11370 case BO_XorAssign:
11371 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000011372 // C99 6.6/3 allows assignments within unevaluated subexpressions of
11373 // constant expressions, but they can never be ICEs because an ICE cannot
11374 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011375 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011376
John McCalle3027922010-08-25 11:45:40 +000011377 case BO_Mul:
11378 case BO_Div:
11379 case BO_Rem:
11380 case BO_Add:
11381 case BO_Sub:
11382 case BO_Shl:
11383 case BO_Shr:
11384 case BO_LT:
11385 case BO_GT:
11386 case BO_LE:
11387 case BO_GE:
11388 case BO_EQ:
11389 case BO_NE:
11390 case BO_And:
11391 case BO_Xor:
11392 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011393 case BO_Comma:
11394 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000011395 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11396 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000011397 if (Exp->getOpcode() == BO_Div ||
11398 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000011399 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000011400 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000011401 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000011402 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011403 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011404 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011405 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000011406 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011407 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011408 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011409 }
11410 }
11411 }
John McCalle3027922010-08-25 11:45:40 +000011412 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011413 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000011414 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
11415 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000011416 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011417 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011418 } else {
11419 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011420 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011421 }
11422 }
Richard Smith9e575da2012-12-28 13:25:52 +000011423 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011424 }
John McCalle3027922010-08-25 11:45:40 +000011425 case BO_LAnd:
11426 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000011427 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11428 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011429 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000011430 // Rare case where the RHS has a comma "side-effect"; we need
11431 // to actually check the condition to see whether the side
11432 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000011433 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000011434 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000011435 return RHSResult;
11436 return NoDiag();
11437 }
11438
Richard Smith9e575da2012-12-28 13:25:52 +000011439 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011440 }
11441 }
Reid Klecknere540d972018-11-01 17:51:48 +000011442 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000011443 }
11444 case Expr::ImplicitCastExprClass:
11445 case Expr::CStyleCastExprClass:
11446 case Expr::CXXFunctionalCastExprClass:
11447 case Expr::CXXStaticCastExprClass:
11448 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000011449 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000011450 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011451 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000011452 if (isa<ExplicitCastExpr>(E)) {
11453 if (const FloatingLiteral *FL
11454 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
11455 unsigned DestWidth = Ctx.getIntWidth(E->getType());
11456 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
11457 APSInt IgnoredVal(DestWidth, !DestSigned);
11458 bool Ignored;
11459 // If the value does not fit in the destination type, the behavior is
11460 // undefined, so we are not required to treat it as a constant
11461 // expression.
11462 if (FL->getValue().convertToInteger(IgnoredVal,
11463 llvm::APFloat::rmTowardZero,
11464 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011465 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000011466 return NoDiag();
11467 }
11468 }
Eli Friedman76d4e432011-09-29 21:49:34 +000011469 switch (cast<CastExpr>(E)->getCastKind()) {
11470 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011471 case CK_AtomicToNonAtomic:
11472 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000011473 case CK_NoOp:
11474 case CK_IntegralToBoolean:
11475 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000011476 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000011477 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011478 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000011479 }
John McCall864e3962010-05-07 05:32:02 +000011480 }
John McCallc07a0c72011-02-17 10:25:35 +000011481 case Expr::BinaryConditionalOperatorClass: {
11482 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
11483 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011484 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000011485 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011486 if (FalseResult.Kind == IK_NotICE) return FalseResult;
11487 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
11488 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000011489 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000011490 return FalseResult;
11491 }
John McCall864e3962010-05-07 05:32:02 +000011492 case Expr::ConditionalOperatorClass: {
11493 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
11494 // If the condition (ignoring parens) is a __builtin_constant_p call,
11495 // then only the true side is actually considered in an integer constant
11496 // expression, and it is fully evaluated. This is an important GNU
11497 // extension. See GCC PR38377 for discussion.
11498 if (const CallExpr *CallCE
11499 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000011500 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000011501 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011502 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011503 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011504 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011505
Richard Smithf57d8cb2011-12-09 22:58:01 +000011506 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
11507 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011508
Richard Smith9e575da2012-12-28 13:25:52 +000011509 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011510 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011511 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011512 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011513 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000011514 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011515 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000011516 return NoDiag();
11517 // Rare case where the diagnostics depend on which side is evaluated
11518 // Note that if we get here, CondResult is 0, and at least one of
11519 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000011520 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000011521 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000011522 return TrueResult;
11523 }
11524 case Expr::CXXDefaultArgExprClass:
11525 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000011526 case Expr::CXXDefaultInitExprClass:
11527 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011528 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000011529 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011530 }
11531 }
11532
David Blaikiee4d798f2012-01-20 21:50:17 +000011533 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000011534}
11535
Richard Smithf57d8cb2011-12-09 22:58:01 +000011536/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000011537static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011538 const Expr *E,
11539 llvm::APSInt *Value,
11540 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000011541 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011542 if (Loc) *Loc = E->getExprLoc();
11543 return false;
11544 }
11545
Richard Smith66e05fe2012-01-18 05:21:49 +000011546 APValue Result;
11547 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000011548 return false;
11549
Richard Smith98710fc2014-11-13 23:03:19 +000011550 if (!Result.isInt()) {
11551 if (Loc) *Loc = E->getExprLoc();
11552 return false;
11553 }
11554
Richard Smith66e05fe2012-01-18 05:21:49 +000011555 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000011556 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011557}
11558
Craig Toppera31a8822013-08-22 07:09:37 +000011559bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
11560 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011561 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000011562 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011563
Richard Smith9e575da2012-12-28 13:25:52 +000011564 ICEDiag D = CheckICE(this, Ctx);
11565 if (D.Kind != IK_ICE) {
11566 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000011567 return false;
11568 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011569 return true;
11570}
11571
Craig Toppera31a8822013-08-22 07:09:37 +000011572bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011573 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011574 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011575 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
11576
11577 if (!isIntegerConstantExpr(Ctx, Loc))
11578 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000011579
Richard Smith5c40f092015-12-04 03:00:44 +000011580 // The only possible side-effects here are due to UB discovered in the
11581 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
11582 // required to treat the expression as an ICE, so we produce the folded
11583 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000011584 EvalResult ExprResult;
11585 Expr::EvalStatus Status;
11586 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
11587 Info.InConstantContext = true;
11588
11589 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000011590 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000011591
11592 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000011593 return true;
11594}
Richard Smith66e05fe2012-01-18 05:21:49 +000011595
Craig Toppera31a8822013-08-22 07:09:37 +000011596bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000011597 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000011598}
11599
Craig Toppera31a8822013-08-22 07:09:37 +000011600bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000011601 SourceLocation *Loc) const {
11602 // We support this checking in C++98 mode in order to diagnose compatibility
11603 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011604 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000011605
Richard Smith98a0a492012-02-14 21:38:30 +000011606 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000011607 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011608 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000011609 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000011610 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000011611
11612 APValue Scratch;
11613 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
11614
11615 if (!Diags.empty()) {
11616 IsConstExpr = false;
11617 if (Loc) *Loc = Diags[0].first;
11618 } else if (!IsConstExpr) {
11619 // FIXME: This shouldn't happen.
11620 if (Loc) *Loc = getExprLoc();
11621 }
11622
11623 return IsConstExpr;
11624}
Richard Smith253c2a32012-01-27 01:14:48 +000011625
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011626bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
11627 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000011628 ArrayRef<const Expr*> Args,
11629 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011630 Expr::EvalStatus Status;
11631 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
11632
George Burgess IV177399e2017-01-09 04:12:14 +000011633 LValue ThisVal;
11634 const LValue *ThisPtr = nullptr;
11635 if (This) {
11636#ifndef NDEBUG
11637 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11638 assert(MD && "Don't provide `this` for non-methods.");
11639 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11640#endif
11641 if (EvaluateObjectArgument(Info, This, ThisVal))
11642 ThisPtr = &ThisVal;
11643 if (Info.EvalStatus.HasSideEffects)
11644 return false;
11645 }
11646
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011647 ArgVector ArgValues(Args.size());
11648 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11649 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000011650 if ((*I)->isValueDependent() ||
11651 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011652 // If evaluation fails, throw away the argument entirely.
11653 ArgValues[I - Args.begin()] = APValue();
11654 if (Info.EvalStatus.HasSideEffects)
11655 return false;
11656 }
11657
11658 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000011659 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011660 ArgValues.data());
11661 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11662}
11663
Richard Smith253c2a32012-01-27 01:14:48 +000011664bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011665 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000011666 PartialDiagnosticAt> &Diags) {
11667 // FIXME: It would be useful to check constexpr function templates, but at the
11668 // moment the constant expression evaluator cannot cope with the non-rigorous
11669 // ASTs which we build for dependent expressions.
11670 if (FD->isDependentContext())
11671 return true;
11672
11673 Expr::EvalStatus Status;
11674 Status.Diag = &Diags;
11675
Richard Smith6d4c6582013-11-05 22:18:15 +000011676 EvalInfo Info(FD->getASTContext(), Status,
11677 EvalInfo::EM_PotentialConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000011678 Info.InConstantContext = true;
Richard Smith253c2a32012-01-27 01:14:48 +000011679
11680 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000011681 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000011682
Richard Smith7525ff62013-05-09 07:14:00 +000011683 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000011684 // is a temporary being used as the 'this' pointer.
11685 LValue This;
11686 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011687 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000011688
Richard Smith253c2a32012-01-27 01:14:48 +000011689 ArrayRef<const Expr*> Args;
11690
Richard Smith2e312c82012-03-03 22:46:17 +000011691 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000011692 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11693 // Evaluate the call as a constant initializer, to allow the construction
11694 // of objects of non-literal types.
11695 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000011696 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11697 } else {
11698 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000011699 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000011700 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000011701 }
Richard Smith253c2a32012-01-27 01:14:48 +000011702
11703 return Diags.empty();
11704}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011705
11706bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11707 const FunctionDecl *FD,
11708 SmallVectorImpl<
11709 PartialDiagnosticAt> &Diags) {
11710 Expr::EvalStatus Status;
11711 Status.Diag = &Diags;
11712
11713 EvalInfo Info(FD->getASTContext(), Status,
11714 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
11715
11716 // Fabricate a call stack frame to give the arguments a plausible cover story.
11717 ArrayRef<const Expr*> Args;
11718 ArgVector ArgValues(0);
11719 bool Success = EvaluateArgs(Args, ArgValues, Info);
11720 (void)Success;
11721 assert(Success &&
11722 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000011723 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011724
11725 APValue ResultScratch;
11726 Evaluate(ResultScratch, Info, E);
11727 return Diags.empty();
11728}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011729
11730bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11731 unsigned Type) const {
11732 if (!getType()->isPointerType())
11733 return false;
11734
11735 Expr::EvalStatus Status;
11736 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000011737 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011738}