blob: df80cb4f94402f195cbf8013facd92f6af6f82b6 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson7a241ba2008-07-03 04:20:39 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
Richard Smith253c2a32012-01-27 01:14:48 +000011// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000025// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000027//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000033//===----------------------------------------------------------------------===//
34
Nandor Licker950b70d2019-09-13 09:46:16 +000035#include <cstring>
36#include <functional>
37#include "Interp/Context.h"
38#include "Interp/Frame.h"
39#include "Interp/State.h"
Anders Carlsson7a241ba2008-07-03 04:20:39 +000040#include "clang/AST/APValue.h"
41#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000042#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000043#include "clang/AST/ASTLambda.h"
Nandor Licker7bd0a782019-08-29 21:57:47 +000044#include "clang/AST/CXXInheritance.h"
Ken Dyck40775002010-01-11 17:06:35 +000045#include "clang/AST/CharUnits.h"
Eric Fiselier708afb52019-05-16 21:04:15 +000046#include "clang/AST/CurrentSourceLocExprScope.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "clang/AST/Expr.h"
Tim Northover314fbfa2018-11-02 13:14:11 +000048#include "clang/AST/OSLog.h"
Nandor Licker950b70d2019-09-13 09:46:16 +000049#include "clang/AST/OptionalDiagnostic.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000050#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000051#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000052#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000053#include "clang/Basic/Builtins.h"
Leonard Chand3f3e162019-01-18 21:04:25 +000054#include "clang/Basic/FixedPoint.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000055#include "clang/Basic/TargetInfo.h"
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000056#include "llvm/ADT/Optional.h"
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000057#include "llvm/ADT/SmallBitVector.h"
Fangrui Song407659a2018-11-30 23:41:18 +000058#include "llvm/Support/SaveAndRestore.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000059#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000060
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000061#define DEBUG_TYPE "exprconstant"
62
Anders Carlsson7a241ba2008-07-03 04:20:39 +000063using namespace clang;
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000064using llvm::APInt;
Chris Lattner05706e882008-07-11 18:11:29 +000065using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000066using llvm::APFloat;
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000067using llvm::Optional;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000068
John McCall93d91dc2010-05-07 17:22:02 +000069namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000070 struct LValue;
Nandor Licker950b70d2019-09-13 09:46:16 +000071 class CallStackFrame;
72 class EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000073
Eric Fiselier708afb52019-05-16 21:04:15 +000074 using SourceLocExprScopeGuard =
75 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
76
Richard Smithb228a862012-02-15 02:18:13 +000077 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000078 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000079 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000080 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000081 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000082 //
83 // extern int arr[]; void f() { extern int arr[3]; };
84 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000085 //
86 // For now, we take the array bound from the most recent declaration.
87 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
88 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
89 QualType T = Redecl->getType();
90 if (!T->isIncompleteArrayType())
91 return T;
92 }
93 return D->getType();
94 }
Richard Smith84401042013-06-03 05:03:02 +000095
Mikael Holmen3b6b2e32019-05-20 11:38:33 +000096 if (B.is<TypeInfoLValue>())
Richard Smithee0ce3022019-05-17 07:06:46 +000097 return B.getTypeInfoType();
98
Richard Smithda1b4342019-09-27 01:26:47 +000099 if (B.is<DynamicAllocLValue>())
100 return B.getDynamicAllocType();
101
Richard Smith84401042013-06-03 05:03:02 +0000102 const Expr *Base = B.get<const Expr*>();
103
104 // For a materialized temporary, the type of the temporary we materialized
105 // may not be the type of the expression.
106 if (const MaterializeTemporaryExpr *MTE =
107 dyn_cast<MaterializeTemporaryExpr>(Base)) {
108 SmallVector<const Expr *, 2> CommaLHSs;
109 SmallVector<SubobjectAdjustment, 2> Adjustments;
Tykerb0561b32019-11-17 11:41:55 +0100110 const Expr *Temp = MTE->getSubExpr();
Richard Smith84401042013-06-03 05:03:02 +0000111 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
112 Adjustments);
113 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +0000114 // for it directly. Otherwise use the type after adjustment.
115 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +0000116 return Inner->getType();
117 }
118
119 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000120 }
121
Richard Smithd62306a2011-11-10 06:34:14 +0000122 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000123 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000124 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000125 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000126 }
127 /// Get an LValue path entry, which is known to not be an array index, as a
128 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000129 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000130 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000131 }
132 /// Determine whether this LValue path entry for a base class names a virtual
133 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000134 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000135 return E.getAsBaseOrMember().getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000136 }
137
Richard Smith457226e2019-09-23 03:48:44 +0000138 /// Given an expression, determine the type used to store the result of
139 /// evaluating that expression.
Richard Smith57694402019-10-08 23:37:49 +0000140 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
Richard Smith457226e2019-09-23 03:48:44 +0000141 if (E->isRValue())
142 return E->getType();
143 return Ctx.getLValueReferenceType(E->getType());
144 }
145
George Burgess IVe3763372016-12-22 02:50:20 +0000146 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
147 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
148 const FunctionDecl *Callee = CE->getDirectCallee();
149 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
150 }
151
152 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
153 /// This will look through a single cast.
154 ///
155 /// Returns null if we couldn't unwrap a function with alloc_size.
156 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
157 if (!E->getType()->isPointerType())
158 return nullptr;
159
160 E = E->IgnoreParens();
161 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000162 // probably be a cast of some kind. In exotic cases, we might also see a
163 // top-level ExprWithCleanups. Ignore them either way.
Bill Wendling7c44da22018-10-31 03:48:47 +0000164 if (const auto *FE = dyn_cast<FullExpr>(E))
165 E = FE->getSubExpr()->IgnoreParens();
George Burgess IV47638762018-03-07 04:52:34 +0000166
George Burgess IVe3763372016-12-22 02:50:20 +0000167 if (const auto *Cast = dyn_cast<CastExpr>(E))
168 E = Cast->getSubExpr()->IgnoreParens();
169
170 if (const auto *CE = dyn_cast<CallExpr>(E))
171 return getAllocSizeAttr(CE) ? CE : nullptr;
172 return nullptr;
173 }
174
175 /// Determines whether or not the given Base contains a call to a function
176 /// with the alloc_size attribute.
177 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
178 const auto *E = Base.dyn_cast<const Expr *>();
179 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
180 }
181
Richard Smith6f4f0f12017-10-20 22:56:25 +0000182 /// The bound to claim that an array of unknown bound has.
183 /// The value in MostDerivedArraySize is undefined in this case. So, set it
184 /// to an arbitrary value that's likely to loudly break things if it's used.
185 static const uint64_t AssumedSizeForUnsizedArray =
186 std::numeric_limits<uint64_t>::max() / 2;
187
George Burgess IVe3763372016-12-22 02:50:20 +0000188 /// Determines if an LValue with the given LValueBase will have an unsized
189 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000190 /// Find the path length and type of the most-derived subobject in the given
191 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000192 static unsigned
193 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
194 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000195 uint64_t &ArraySize, QualType &Type, bool &IsArray,
196 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000197 // This only accepts LValueBases from APValues, and APValues don't support
198 // arrays that lack size info.
199 assert(!isBaseAnAllocSizeCall(Base) &&
200 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000201 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000202 Type = getType(Base);
203
Richard Smith80815602011-11-07 05:07:52 +0000204 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000205 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000206 const ArrayType *AT = Ctx.getAsArrayType(Type);
207 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000208 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000209 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000210
211 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
212 ArraySize = CAT->getSize().getZExtValue();
213 } else {
214 assert(I == 0 && "unexpected unsized array designator");
215 FirstEntryIsUnsizedArray = true;
216 ArraySize = AssumedSizeForUnsizedArray;
217 }
Richard Smith66c96992012-02-18 22:04:06 +0000218 } else if (Type->isAnyComplexType()) {
219 const ComplexType *CT = Type->castAs<ComplexType>();
220 Type = CT->getElementType();
221 ArraySize = 2;
222 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000223 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000224 } else if (const FieldDecl *FD = getAsField(Path[I])) {
225 Type = FD->getType();
226 ArraySize = 0;
227 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000228 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000229 } else {
Richard Smith80815602011-11-07 05:07:52 +0000230 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000231 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000232 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000233 }
Richard Smith80815602011-11-07 05:07:52 +0000234 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000235 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000236 }
237
Richard Smith96e0c102011-11-04 02:25:55 +0000238 /// A path from a glvalue to a subobject of that glvalue.
239 struct SubobjectDesignator {
240 /// True if the subobject was named in a manner not supported by C++11. Such
241 /// lvalues can still be folded, but they are not core constant expressions
242 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000243 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000244
Richard Smitha8105bc2012-01-06 16:39:00 +0000245 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000246 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000247
Daniel Jasperffdee092017-05-02 19:21:42 +0000248 /// Indicator of whether the first entry is an unsized array.
249 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000250
George Burgess IVa51c4072015-10-16 01:49:01 +0000251 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000252 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000253
Richard Smitha8105bc2012-01-06 16:39:00 +0000254 /// The length of the path to the most-derived object of which this is a
255 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000256 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000257
George Burgess IVa51c4072015-10-16 01:49:01 +0000258 /// The size of the array of which the most-derived object is an element.
259 /// This will always be 0 if the most-derived object is not an array
260 /// element. 0 is not an indicator of whether or not the most-derived object
261 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000262 ///
263 /// If the current array is an unsized array, the value of this is
264 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 uint64_t MostDerivedArraySize;
266
267 /// The type of the most derived object referred to by this address.
268 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000269
Richard Smith80815602011-11-07 05:07:52 +0000270 typedef APValue::LValuePathEntry PathEntry;
271
Richard Smith96e0c102011-11-04 02:25:55 +0000272 /// The entries on the path from the glvalue to the designated subobject.
273 SmallVector<PathEntry, 8> Entries;
274
Richard Smitha8105bc2012-01-06 16:39:00 +0000275 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000276
Richard Smitha8105bc2012-01-06 16:39:00 +0000277 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000278 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000279 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000280 MostDerivedPathLength(0), MostDerivedArraySize(0),
281 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000282
283 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000284 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000285 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000286 MostDerivedPathLength(0), MostDerivedArraySize(0) {
287 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000288 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000289 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000290 ArrayRef<PathEntry> VEntries = V.getLValuePath();
291 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000292 if (V.getLValueBase()) {
293 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000294 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000295 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000296 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000297 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000298 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000299 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000300 }
Richard Smith80815602011-11-07 05:07:52 +0000301 }
302 }
303
Richard Smith31c69a32019-05-21 23:15:20 +0000304 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
305 unsigned NewLength) {
306 if (Invalid)
307 return;
308
309 assert(Base && "cannot truncate path for null pointer");
310 assert(NewLength <= Entries.size() && "not a truncation");
311
312 if (NewLength == Entries.size())
313 return;
314 Entries.resize(NewLength);
315
316 bool IsArray = false;
317 bool FirstIsUnsizedArray = false;
318 MostDerivedPathLength = findMostDerivedSubobject(
319 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
320 FirstIsUnsizedArray);
321 MostDerivedIsArrayElement = IsArray;
322 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
323 }
324
Richard Smith96e0c102011-11-04 02:25:55 +0000325 void setInvalid() {
326 Invalid = true;
327 Entries.clear();
328 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000329
George Burgess IVe3763372016-12-22 02:50:20 +0000330 /// Determine whether the most derived subobject is an array without a
331 /// known bound.
332 bool isMostDerivedAnUnsizedArray() const {
333 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000334 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000335 }
336
337 /// Determine what the most derived array's size is. Results in an assertion
338 /// failure if the most derived array lacks a size.
339 uint64_t getMostDerivedArraySize() const {
340 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
341 return MostDerivedArraySize;
342 }
343
Richard Smitha8105bc2012-01-06 16:39:00 +0000344 /// Determine whether this is a one-past-the-end pointer.
345 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000346 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000347 if (IsOnePastTheEnd)
348 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000349 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smith5b5e27a2019-05-10 20:05:31 +0000350 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
351 MostDerivedArraySize)
Richard Smitha8105bc2012-01-06 16:39:00 +0000352 return true;
353 return false;
354 }
355
Richard Smith06f71b52018-08-04 00:57:17 +0000356 /// Get the range of valid index adjustments in the form
357 /// {maximum value that can be subtracted from this pointer,
358 /// maximum value that can be added to this pointer}
359 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
360 if (Invalid || isMostDerivedAnUnsizedArray())
361 return {0, 0};
362
363 // [expr.add]p4: For the purposes of these operators, a pointer to a
364 // nonarray object behaves the same as a pointer to the first element of
365 // an array of length one with the type of the object as its element type.
366 bool IsArray = MostDerivedPathLength == Entries.size() &&
367 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000368 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
369 : (uint64_t)IsOnePastTheEnd;
Richard Smith06f71b52018-08-04 00:57:17 +0000370 uint64_t ArraySize =
371 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
372 return {ArrayIndex, ArraySize - ArrayIndex};
373 }
374
Richard Smitha8105bc2012-01-06 16:39:00 +0000375 /// Check that this refers to a valid subobject.
376 bool isValidSubobject() const {
377 if (Invalid)
378 return false;
379 return !isOnePastTheEnd();
380 }
381 /// Check that this refers to a valid subobject, and if not, produce a
382 /// relevant diagnostic and set the designator as invalid.
383 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
384
Richard Smith06f71b52018-08-04 00:57:17 +0000385 /// Get the type of the designated object.
386 QualType getType(ASTContext &Ctx) const {
387 assert(!Invalid && "invalid designator has no subobject type");
388 return MostDerivedPathLength == Entries.size()
389 ? MostDerivedType
390 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
391 }
392
Richard Smitha8105bc2012-01-06 16:39:00 +0000393 /// Update this designator to refer to the first element within this array.
394 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000395 Entries.push_back(PathEntry::ArrayIndex(0));
Richard Smitha8105bc2012-01-06 16:39:00 +0000396
397 // This is a most-derived object.
398 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000399 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000400 MostDerivedArraySize = CAT->getSize().getZExtValue();
401 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000402 }
George Burgess IVe3763372016-12-22 02:50:20 +0000403 /// Update this designator to refer to the first element within the array of
404 /// elements of type T. This is an array of unknown size.
405 void addUnsizedArrayUnchecked(QualType ElemTy) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000406 Entries.push_back(PathEntry::ArrayIndex(0));
George Burgess IVe3763372016-12-22 02:50:20 +0000407
408 MostDerivedType = ElemTy;
409 MostDerivedIsArrayElement = true;
410 // The value in MostDerivedArraySize is undefined in this case. So, set it
411 // to an arbitrary value that's likely to loudly break things if it's
412 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000413 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000414 MostDerivedPathLength = Entries.size();
415 }
Richard Smith96e0c102011-11-04 02:25:55 +0000416 /// Update this designator to refer to the given base or member of this
417 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000418 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000419 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
Richard Smitha8105bc2012-01-06 16:39:00 +0000420
421 // If this isn't a base class, it's a new most-derived object.
422 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
423 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000424 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000425 MostDerivedArraySize = 0;
426 MostDerivedPathLength = Entries.size();
427 }
Richard Smith96e0c102011-11-04 02:25:55 +0000428 }
Richard Smith66c96992012-02-18 22:04:06 +0000429 /// Update this designator to refer to the given complex component.
430 void addComplexUnchecked(QualType EltTy, bool Imag) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000431 Entries.push_back(PathEntry::ArrayIndex(Imag));
Richard Smith66c96992012-02-18 22:04:06 +0000432
433 // This is technically a most-derived object, though in practice this
434 // is unlikely to matter.
435 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000436 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000437 MostDerivedArraySize = 2;
438 MostDerivedPathLength = Entries.size();
439 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000440 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000441 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
442 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000443 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000444 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
445 if (Invalid || !N) return;
446 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
447 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000448 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000449 // Can't verify -- trust that the user is doing the right thing (or if
450 // not, trust that the caller will catch the bad behavior).
451 // FIXME: Should we reject if this overflows, at least?
Richard Smith5b5e27a2019-05-10 20:05:31 +0000452 Entries.back() = PathEntry::ArrayIndex(
453 Entries.back().getAsArrayIndex() + TruncatedN);
Daniel Jasperffdee092017-05-02 19:21:42 +0000454 return;
455 }
456
457 // [expr.add]p4: For the purposes of these operators, a pointer to a
458 // nonarray object behaves the same as a pointer to the first element of
459 // an array of length one with the type of the object as its element type.
460 bool IsArray = MostDerivedPathLength == Entries.size() &&
461 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000462 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
463 : (uint64_t)IsOnePastTheEnd;
Daniel Jasperffdee092017-05-02 19:21:42 +0000464 uint64_t ArraySize =
465 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
466
467 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
468 // Calculate the actual index in a wide enough type, so we can include
469 // it in the note.
470 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
471 (llvm::APInt&)N += ArrayIndex;
472 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
473 diagnosePointerArithmetic(Info, E, N);
474 setInvalid();
475 return;
476 }
477
478 ArrayIndex += TruncatedN;
479 assert(ArrayIndex <= ArraySize &&
480 "bounds check succeeded for out-of-bounds index");
481
482 if (IsArray)
Richard Smith5b5e27a2019-05-10 20:05:31 +0000483 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
Daniel Jasperffdee092017-05-02 19:21:42 +0000484 else
485 IsOnePastTheEnd = (ArrayIndex != 0);
486 }
Richard Smith96e0c102011-11-04 02:25:55 +0000487 };
488
Richard Smith254a73d2011-10-28 22:34:42 +0000489 /// A stack frame in the constexpr call stack.
Nandor Licker950b70d2019-09-13 09:46:16 +0000490 class CallStackFrame : public interp::Frame {
491 public:
Richard Smith254a73d2011-10-28 22:34:42 +0000492 EvalInfo &Info;
493
494 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000495 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000496
Richard Smithf6f003a2011-12-16 19:06:07 +0000497 /// Callee - The function which was called.
498 const FunctionDecl *Callee;
499
Richard Smithd62306a2011-11-10 06:34:14 +0000500 /// This - The binding for the this pointer in this call, if any.
501 const LValue *This;
502
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000503 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000504 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000505 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000506
Eric Fiselier708afb52019-05-16 21:04:15 +0000507 /// Source location information about the default argument or default
508 /// initializer expression we're evaluating, if any.
509 CurrentSourceLocExprScope CurSourceLocExprScope;
510
Eli Friedman4830ec82012-06-25 21:21:08 +0000511 // Note that we intentionally use std::map here so that references to
512 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000513 typedef std::pair<const void *, unsigned> MapKeyTy;
514 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000515 /// Temporaries - Temporary lvalues materialized within this stack frame.
516 MapTy Temporaries;
517
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000518 /// CallLoc - The location of the call expression for this call.
519 SourceLocation CallLoc;
520
521 /// Index - The call index of this call.
522 unsigned Index;
523
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000524 /// The stack of integers for tracking version numbers for temporaries.
525 SmallVector<unsigned, 2> TempVersionStack = {1};
526 unsigned CurTempVersion = TempVersionStack.back();
527
528 unsigned getTempVersion() const { return TempVersionStack.back(); }
529
530 void pushTempVersion() {
531 TempVersionStack.push_back(++CurTempVersion);
532 }
533
534 void popTempVersion() {
535 TempVersionStack.pop_back();
536 }
537
Faisal Vali051e3a22017-02-16 04:12:21 +0000538 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000539 // on the overall stack usage of deeply-recursing constexpr evaluations.
Faisal Vali051e3a22017-02-16 04:12:21 +0000540 // (We should cache this map rather than recomputing it repeatedly.)
541 // But let's try this and see how it goes; we can look into caching the map
542 // as a later change.
543
544 /// LambdaCaptureFields - Mapping from captured variables/this to
545 /// corresponding data members in the closure class.
546 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
547 FieldDecl *LambdaThisCaptureField;
548
Richard Smithf6f003a2011-12-16 19:06:07 +0000549 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
550 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000551 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000552 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000553
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000554 // Return the temporary for Key whose version number is Version.
555 APValue *getTemporary(const void *Key, unsigned Version) {
556 MapKeyTy KV(Key, Version);
557 auto LB = Temporaries.lower_bound(KV);
558 if (LB != Temporaries.end() && LB->first == KV)
559 return &LB->second;
560 // Pair (Key,Version) wasn't found in the map. Check that no elements
561 // in the map have 'Key' as their key.
562 assert((LB == Temporaries.end() || LB->first.first != Key) &&
563 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
564 "Element with key 'Key' found in map");
565 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000566 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000567
568 // Return the current temporary for Key in the map.
569 APValue *getCurrentTemporary(const void *Key) {
570 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
571 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
572 return &std::prev(UB)->second;
573 return nullptr;
574 }
575
576 // Return the version number of the current temporary for Key.
577 unsigned getCurrentTemporaryVersion(const void *Key) const {
578 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
579 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
580 return std::prev(UB)->first.second;
581 return 0;
582 }
583
Richard Smith457226e2019-09-23 03:48:44 +0000584 /// Allocate storage for an object of type T in this stack frame.
585 /// Populates LV with a handle to the created object. Key identifies
586 /// the temporary within the stack frame, and must not be reused without
587 /// bumping the temporary version number.
588 template<typename KeyT>
589 APValue &createTemporary(const KeyT *Key, QualType T,
590 bool IsLifetimeExtended, LValue &LV);
Nandor Licker950b70d2019-09-13 09:46:16 +0000591
592 void describe(llvm::raw_ostream &OS) override;
593
594 Frame *getCaller() const override { return Caller; }
595 SourceLocation getCallLocation() const override { return CallLoc; }
596 const FunctionDecl *getCallee() const override { return Callee; }
Richard Smithb5426022019-10-03 00:39:35 +0000597
598 bool isStdFunction() const {
599 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
600 if (DC->isStdNamespace())
601 return true;
602 return false;
603 }
Richard Smith254a73d2011-10-28 22:34:42 +0000604 };
605
Richard Smith852c9db2013-04-20 22:23:05 +0000606 /// Temporarily override 'this'.
607 class ThisOverrideRAII {
608 public:
609 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
610 : Frame(Frame), OldThis(Frame.This) {
611 if (Enable)
612 Frame.This = NewThis;
613 }
614 ~ThisOverrideRAII() {
615 Frame.This = OldThis;
616 }
617 private:
618 CallStackFrame &Frame;
619 const LValue *OldThis;
620 };
Richard Smith457226e2019-09-23 03:48:44 +0000621}
Richard Smith852c9db2013-04-20 22:23:05 +0000622
Richard Smith61422f92019-09-27 20:24:36 +0000623static bool HandleDestruction(EvalInfo &Info, const Expr *E,
624 const LValue &This, QualType ThisType);
625static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
626 APValue::LValueBase LVBase, APValue &Value,
627 QualType T);
Richard Smith457226e2019-09-23 03:48:44 +0000628
629namespace {
Richard Smith08d6a2c2013-07-24 07:11:57 +0000630 /// A cleanup, and a flag indicating whether it is lifetime-extended.
631 class Cleanup {
632 llvm::PointerIntPair<APValue*, 1, bool> Value;
Richard Smith457226e2019-09-23 03:48:44 +0000633 APValue::LValueBase Base;
634 QualType T;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000635
636 public:
Richard Smith457226e2019-09-23 03:48:44 +0000637 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
638 bool IsLifetimeExtended)
639 : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
Richard Smith08d6a2c2013-07-24 07:11:57 +0000640
641 bool isLifetimeExtended() const { return Value.getInt(); }
Richard Smith457226e2019-09-23 03:48:44 +0000642 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
Richard Smithda1b4342019-09-27 01:26:47 +0000643 if (RunDestructors) {
644 SourceLocation Loc;
645 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
646 Loc = VD->getLocation();
647 else if (const Expr *E = Base.dyn_cast<const Expr*>())
648 Loc = E->getExprLoc();
Richard Smith61422f92019-09-27 20:24:36 +0000649 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
Richard Smithda1b4342019-09-27 01:26:47 +0000650 }
Richard Smith08d6a2c2013-07-24 07:11:57 +0000651 *Value.getPointer() = APValue();
Richard Smith457226e2019-09-23 03:48:44 +0000652 return true;
653 }
654
655 bool hasSideEffect() {
656 return T.isDestructedType();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000657 }
658 };
659
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000660 /// A reference to an object whose construction we are currently evaluating.
661 struct ObjectUnderConstruction {
662 APValue::LValueBase Base;
663 ArrayRef<APValue::LValuePathEntry> Path;
664 friend bool operator==(const ObjectUnderConstruction &LHS,
665 const ObjectUnderConstruction &RHS) {
666 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
667 }
668 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
669 return llvm::hash_combine(Obj.Base, Obj.Path);
670 }
671 };
Richard Smith457226e2019-09-23 03:48:44 +0000672 enum class ConstructionPhase {
673 None,
674 Bases,
675 AfterBases,
676 Destroying,
677 DestroyingBases
678 };
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000679}
680
681namespace llvm {
682template<> struct DenseMapInfo<ObjectUnderConstruction> {
683 using Base = DenseMapInfo<APValue::LValueBase>;
684 static ObjectUnderConstruction getEmptyKey() {
685 return {Base::getEmptyKey(), {}}; }
686 static ObjectUnderConstruction getTombstoneKey() {
687 return {Base::getTombstoneKey(), {}};
688 }
689 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
690 return hash_value(Object);
691 }
692 static bool isEqual(const ObjectUnderConstruction &LHS,
693 const ObjectUnderConstruction &RHS) {
694 return LHS == RHS;
695 }
696};
697}
698
699namespace {
Richard Smith19ad5232019-10-03 00:39:33 +0000700 /// A dynamically-allocated heap object.
701 struct DynAlloc {
702 /// The value of this heap-allocated object.
703 APValue Value;
704 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
705 /// or a CallExpr (the latter is for direct calls to operator new inside
706 /// std::allocator<T>::allocate).
707 const Expr *AllocExpr = nullptr;
708
709 enum Kind {
710 New,
711 ArrayNew,
712 StdAllocator
713 };
714
715 /// Get the kind of the allocation. This must match between allocation
716 /// and deallocation.
717 Kind getKind() const {
718 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
719 return NE->isArray() ? ArrayNew : New;
720 assert(isa<CallExpr>(AllocExpr));
721 return StdAllocator;
722 }
723 };
724
725 struct DynAllocOrder {
726 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
727 return L.getIndex() < R.getIndex();
728 }
729 };
730
Richard Smithb228a862012-02-15 02:18:13 +0000731 /// EvalInfo - This is a private struct used by the evaluator to capture
732 /// information about a subexpression as it is folded. It retains information
733 /// about the AST context, but also maintains information about the folded
734 /// expression.
735 ///
736 /// If an expression could be evaluated, it is still possible it is not a C
737 /// "integer constant expression" or constant expression. If not, this struct
738 /// captures information about how and why not.
739 ///
740 /// One bit of information passed *into* the request for constant folding
741 /// indicates whether the subexpression is "evaluated" or not according to C
742 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
743 /// evaluate the expression regardless of what the RHS is, but C only allows
744 /// certain things in certain situations.
Nandor Licker950b70d2019-09-13 09:46:16 +0000745 class EvalInfo : public interp::State {
746 public:
Richard Smith92b1ce02011-12-12 09:28:41 +0000747 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000748
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000749 /// EvalStatus - Contains information about the evaluation.
750 Expr::EvalStatus &EvalStatus;
751
752 /// CurrentCall - The top of the constexpr call stack.
753 CallStackFrame *CurrentCall;
754
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000755 /// CallStackDepth - The number of calls in the call stack right now.
756 unsigned CallStackDepth;
757
Richard Smithb228a862012-02-15 02:18:13 +0000758 /// NextCallIndex - The next call index to assign.
759 unsigned NextCallIndex;
760
Richard Smitha3d3bd22013-05-08 02:12:03 +0000761 /// StepsLeft - The remaining number of evaluation steps we're permitted
762 /// to perform. This is essentially a limit for the number of statements
763 /// we will evaluate.
764 unsigned StepsLeft;
765
Nandor Lickerf584f042019-11-11 11:13:34 +0000766 /// Enable the experimental new constant interpreter. If an expression is
767 /// not supported by the interpreter, an error is triggered.
Nandor Licker950b70d2019-09-13 09:46:16 +0000768 bool EnableNewConstInterp;
769
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000770 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000771 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000772 CallStackFrame BottomFrame;
773
Richard Smith08d6a2c2013-07-24 07:11:57 +0000774 /// A stack of values whose lifetimes end at the end of some surrounding
775 /// evaluation frame.
776 llvm::SmallVector<Cleanup, 16> CleanupStack;
777
Richard Smithd62306a2011-11-10 06:34:14 +0000778 /// EvaluatingDecl - This is the declaration whose initializer is being
779 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000780 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000781
Richard Smith2b4fa532019-09-29 05:08:46 +0000782 enum class EvaluatingDeclKind {
783 None,
784 /// We're evaluating the construction of EvaluatingDecl.
785 Ctor,
786 /// We're evaluating the destruction of EvaluatingDecl.
787 Dtor,
788 };
789 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
790
Richard Smithd62306a2011-11-10 06:34:14 +0000791 /// EvaluatingDeclValue - This is the value being constructed for the
792 /// declaration whose initializer is being evaluated, if any.
793 APValue *EvaluatingDeclValue;
794
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000795 /// Set of objects that are currently being constructed.
796 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
797 ObjectsUnderConstruction;
Erik Pilkington42925492017-10-04 00:18:55 +0000798
Richard Smithda1b4342019-09-27 01:26:47 +0000799 /// Current heap allocations, along with the location where each was
800 /// allocated. We use std::map here because we need stable addresses
801 /// for the stored APValues.
802 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
803
804 /// The number of heap allocations performed so far in this evaluation.
805 unsigned NumHeapAllocs = 0;
806
Erik Pilkington42925492017-10-04 00:18:55 +0000807 struct EvaluatingConstructorRAII {
808 EvalInfo &EI;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000809 ObjectUnderConstruction Object;
Erik Pilkington42925492017-10-04 00:18:55 +0000810 bool DidInsert;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000811 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
812 bool HasBases)
Erik Pilkington42925492017-10-04 00:18:55 +0000813 : EI(EI), Object(Object) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000814 DidInsert =
815 EI.ObjectsUnderConstruction
816 .insert({Object, HasBases ? ConstructionPhase::Bases
817 : ConstructionPhase::AfterBases})
818 .second;
819 }
820 void finishedConstructingBases() {
821 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
Erik Pilkington42925492017-10-04 00:18:55 +0000822 }
823 ~EvaluatingConstructorRAII() {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000824 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
Erik Pilkington42925492017-10-04 00:18:55 +0000825 }
826 };
827
Richard Smith457226e2019-09-23 03:48:44 +0000828 struct EvaluatingDestructorRAII {
829 EvalInfo &EI;
830 ObjectUnderConstruction Object;
Richard Smithda1b4342019-09-27 01:26:47 +0000831 bool DidInsert;
Richard Smith457226e2019-09-23 03:48:44 +0000832 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
833 : EI(EI), Object(Object) {
Richard Smithda1b4342019-09-27 01:26:47 +0000834 DidInsert = EI.ObjectsUnderConstruction
835 .insert({Object, ConstructionPhase::Destroying})
836 .second;
Richard Smith457226e2019-09-23 03:48:44 +0000837 }
838 void startedDestroyingBases() {
839 EI.ObjectsUnderConstruction[Object] =
840 ConstructionPhase::DestroyingBases;
841 }
842 ~EvaluatingDestructorRAII() {
Richard Smithda1b4342019-09-27 01:26:47 +0000843 if (DidInsert)
844 EI.ObjectsUnderConstruction.erase(Object);
Richard Smith457226e2019-09-23 03:48:44 +0000845 }
846 };
847
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000848 ConstructionPhase
Richard Smith457226e2019-09-23 03:48:44 +0000849 isEvaluatingCtorDtor(APValue::LValueBase Base,
850 ArrayRef<APValue::LValuePathEntry> Path) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000851 return ObjectsUnderConstruction.lookup({Base, Path});
Erik Pilkington42925492017-10-04 00:18:55 +0000852 }
853
Richard Smith37be3362019-05-04 04:00:45 +0000854 /// If we're currently speculatively evaluating, the outermost call stack
855 /// depth at which we can mutate state, otherwise 0.
856 unsigned SpeculativeEvaluationDepth = 0;
857
Richard Smith410306b2016-12-12 02:53:20 +0000858 /// The current array initialization index, if we're performing array
859 /// initialization.
860 uint64_t ArrayInitIndex = -1;
861
Richard Smith357362d2011-12-13 06:39:58 +0000862 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
863 /// notes attached to it will also be stored, otherwise they will not be.
864 bool HasActiveDiagnostic;
865
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000866 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000867 /// fold (not just why it's not strictly a constant expression)?
868 bool HasFoldFailureDiagnostic;
869
Fangrui Song407659a2018-11-30 23:41:18 +0000870 /// Whether or not we're in a context where the front end requires a
871 /// constant value.
872 bool InConstantContext;
873
Richard Smith045b2272019-09-10 21:24:09 +0000874 /// Whether we're checking that an expression is a potential constant
875 /// expression. If so, do not fail on constructs that could become constant
876 /// later on (such as a use of an undefined global).
877 bool CheckingPotentialConstantExpression = false;
878
879 /// Whether we're checking for an expression that has undefined behavior.
880 /// If so, we will produce warnings if we encounter an operation that is
881 /// always undefined.
882 bool CheckingForUndefinedBehavior = false;
883
Richard Smith6d4c6582013-11-05 22:18:15 +0000884 enum EvaluationMode {
885 /// Evaluate as a constant expression. Stop if we find that the expression
886 /// is not a constant expression.
887 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000888
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000889 /// Evaluate as a constant expression. Stop if we find that the expression
890 /// is not a constant expression. Some expressions can be retried in the
891 /// optimizer if we don't constant fold them here, but in an unevaluated
892 /// context we try to fold them immediately since the optimizer never
893 /// gets a chance to look at it.
894 EM_ConstantExpressionUnevaluated,
895
Richard Smith045b2272019-09-10 21:24:09 +0000896 /// Fold the expression to a constant. Stop if we hit a side-effect that
897 /// we can't model.
898 EM_ConstantFold,
899
900 /// Evaluate in any way we know how. Don't worry about side-effects that
901 /// can't be modeled.
902 EM_IgnoreSideEffects,
Richard Smith6d4c6582013-11-05 22:18:15 +0000903 } EvalMode;
904
905 /// Are we checking whether the expression is a potential constant
906 /// expression?
Nandor Licker950b70d2019-09-13 09:46:16 +0000907 bool checkingPotentialConstantExpression() const override {
Richard Smith045b2272019-09-10 21:24:09 +0000908 return CheckingPotentialConstantExpression;
Richard Smith6d4c6582013-11-05 22:18:15 +0000909 }
910
911 /// Are we checking an expression for overflow?
912 // FIXME: We should check for any kind of undefined or suspicious behavior
913 // in such constructs, not just overflow.
Nandor Licker950b70d2019-09-13 09:46:16 +0000914 bool checkingForUndefinedBehavior() const override {
915 return CheckingForUndefinedBehavior;
916 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000917
918 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Nandor Licker950b70d2019-09-13 09:46:16 +0000919 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
920 CallStackDepth(0), NextCallIndex(1),
Yaxun (Sam) Liuded24902019-11-26 13:13:47 -0500921 StepsLeft(C.getLangOpts().ConstexprStepLimit),
Nandor Lickerf584f042019-11-11 11:13:34 +0000922 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
Nandor Licker950b70d2019-09-13 09:46:16 +0000923 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
924 EvaluatingDecl((const ValueDecl *)nullptr),
925 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
926 HasFoldFailureDiagnostic(false), InConstantContext(false),
927 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000928
Richard Smith457226e2019-09-23 03:48:44 +0000929 ~EvalInfo() {
930 discardCleanups();
931 }
932
Richard Smith2b4fa532019-09-29 05:08:46 +0000933 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
934 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
Richard Smith7525ff62013-05-09 07:14:00 +0000935 EvaluatingDecl = Base;
Richard Smith2b4fa532019-09-29 05:08:46 +0000936 IsEvaluatingDecl = EDK;
Richard Smithd62306a2011-11-10 06:34:14 +0000937 EvaluatingDeclValue = &Value;
938 }
939
Richard Smith357362d2011-12-13 06:39:58 +0000940 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000941 // Don't perform any constexpr calls (other than the call we're checking)
942 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000943 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000944 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000945 if (NextCallIndex == 0) {
946 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000947 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000948 return false;
949 }
Richard Smith357362d2011-12-13 06:39:58 +0000950 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
951 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000952 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000953 << getLangOpts().ConstexprCallDepth;
954 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000955 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000956
Richard Smith37be3362019-05-04 04:00:45 +0000957 std::pair<CallStackFrame *, unsigned>
958 getCallFrameAndDepth(unsigned CallIndex) {
959 assert(CallIndex && "no call index in getCallFrameAndDepth");
Richard Smithb228a862012-02-15 02:18:13 +0000960 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
961 // be null in this loop.
Richard Smith37be3362019-05-04 04:00:45 +0000962 unsigned Depth = CallStackDepth;
Richard Smithb228a862012-02-15 02:18:13 +0000963 CallStackFrame *Frame = CurrentCall;
Richard Smith37be3362019-05-04 04:00:45 +0000964 while (Frame->Index > CallIndex) {
Richard Smithb228a862012-02-15 02:18:13 +0000965 Frame = Frame->Caller;
Richard Smith37be3362019-05-04 04:00:45 +0000966 --Depth;
967 }
968 if (Frame->Index == CallIndex)
969 return {Frame, Depth};
970 return {nullptr, 0};
Richard Smithb228a862012-02-15 02:18:13 +0000971 }
972
Richard Smitha3d3bd22013-05-08 02:12:03 +0000973 bool nextStep(const Stmt *S) {
974 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000975 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000976 return false;
977 }
978 --StepsLeft;
979 return true;
980 }
981
Richard Smithda1b4342019-09-27 01:26:47 +0000982 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
983
984 Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
985 Optional<DynAlloc*> Result;
986 auto It = HeapAllocs.find(DA);
987 if (It != HeapAllocs.end())
988 Result = &It->second;
989 return Result;
990 }
991
Richard Smith19ad5232019-10-03 00:39:33 +0000992 /// Information about a stack frame for std::allocator<T>::[de]allocate.
993 struct StdAllocatorCaller {
994 unsigned FrameIndex;
995 QualType ElemType;
996 explicit operator bool() const { return FrameIndex != 0; };
997 };
998
999 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1000 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1001 Call = Call->Caller) {
1002 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1003 if (!MD)
1004 continue;
1005 const IdentifierInfo *FnII = MD->getIdentifier();
1006 if (!FnII || !FnII->isStr(FnName))
1007 continue;
1008
1009 const auto *CTSD =
1010 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1011 if (!CTSD)
1012 continue;
1013
1014 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1015 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1016 if (CTSD->isInStdNamespace() && ClassII &&
1017 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1018 TAL[0].getKind() == TemplateArgument::Type)
1019 return {Call->Index, TAL[0].getAsType()};
1020 }
1021
1022 return {};
1023 }
1024
Richard Smith457226e2019-09-23 03:48:44 +00001025 void performLifetimeExtension() {
1026 // Disable the cleanups for lifetime-extended temporaries.
1027 CleanupStack.erase(
1028 std::remove_if(CleanupStack.begin(), CleanupStack.end(),
1029 [](Cleanup &C) { return C.isLifetimeExtended(); }),
1030 CleanupStack.end());
1031 }
1032
1033 /// Throw away any remaining cleanups at the end of evaluation. If any
1034 /// cleanups would have had a side-effect, note that as an unmodeled
1035 /// side-effect and return false. Otherwise, return true.
1036 bool discardCleanups() {
Richard Smithbb061492019-10-30 13:32:52 -07001037 for (Cleanup &C : CleanupStack) {
1038 if (C.hasSideEffect() && !noteSideEffect()) {
1039 CleanupStack.clear();
1040 return false;
1041 }
1042 }
1043 CleanupStack.clear();
Richard Smith457226e2019-09-23 03:48:44 +00001044 return true;
1045 }
1046
Richard Smith357362d2011-12-13 06:39:58 +00001047 private:
Nandor Licker950b70d2019-09-13 09:46:16 +00001048 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1049 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1050
1051 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1052 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1053
1054 void setFoldFailureDiagnostic(bool Flag) override {
1055 HasFoldFailureDiagnostic = Flag;
Richard Smith357362d2011-12-13 06:39:58 +00001056 }
1057
Nandor Licker950b70d2019-09-13 09:46:16 +00001058 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
Richard Smithf6f003a2011-12-16 19:06:07 +00001059
Nandor Licker950b70d2019-09-13 09:46:16 +00001060 ASTContext &getCtx() const override { return Ctx; }
Fangrui Song6907ce22018-07-30 19:24:48 +00001061
Nandor Licker950b70d2019-09-13 09:46:16 +00001062 // If we have a prior diagnostic, it will be noting that the expression
1063 // isn't a constant expression. This diagnostic is more important,
1064 // unless we require this evaluation to produce a constant expression.
1065 //
1066 // FIXME: We might want to show both diagnostics to the user in
1067 // EM_ConstantFold mode.
1068 bool hasPriorDiagnostic() override {
1069 if (!EvalStatus.Diag->empty()) {
1070 switch (EvalMode) {
1071 case EM_ConstantFold:
1072 case EM_IgnoreSideEffects:
1073 if (!HasFoldFailureDiagnostic)
1074 break;
1075 // We've already failed to fold something. Keep that diagnostic.
1076 LLVM_FALLTHROUGH;
1077 case EM_ConstantExpression:
1078 case EM_ConstantExpressionUnevaluated:
1079 setActiveDiagnostic(false);
1080 return true;
Richard Smith6d4c6582013-11-05 22:18:15 +00001081 }
Richard Smith92b1ce02011-12-12 09:28:41 +00001082 }
Nandor Licker950b70d2019-09-13 09:46:16 +00001083 return false;
Richard Smith92b1ce02011-12-12 09:28:41 +00001084 }
Nandor Licker950b70d2019-09-13 09:46:16 +00001085
1086 unsigned getCallStackDepth() override { return CallStackDepth; }
1087
Faisal Valie690b7a2016-07-02 22:34:24 +00001088 public:
Richard Smith6d4c6582013-11-05 22:18:15 +00001089 /// Should we continue evaluation after encountering a side-effect that we
1090 /// couldn't model?
1091 bool keepEvaluatingAfterSideEffect() {
1092 switch (EvalMode) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001093 case EM_IgnoreSideEffects:
1094 return true;
1095
Richard Smith6d4c6582013-11-05 22:18:15 +00001096 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001097 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001098 case EM_ConstantFold:
Richard Smith045b2272019-09-10 21:24:09 +00001099 // By default, assume any side effect might be valid in some other
1100 // evaluation of this expression from a different context.
1101 return checkingPotentialConstantExpression() ||
1102 checkingForUndefinedBehavior();
Richard Smith6d4c6582013-11-05 22:18:15 +00001103 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001104 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +00001105 }
1106
1107 /// Note that we have had a side-effect, and determine whether we should
1108 /// keep evaluating.
1109 bool noteSideEffect() {
1110 EvalStatus.HasSideEffects = true;
1111 return keepEvaluatingAfterSideEffect();
1112 }
1113
Richard Smithce8eca52015-12-08 03:21:47 +00001114 /// Should we continue evaluation after encountering undefined behavior?
1115 bool keepEvaluatingAfterUndefinedBehavior() {
1116 switch (EvalMode) {
Richard Smithce8eca52015-12-08 03:21:47 +00001117 case EM_IgnoreSideEffects:
1118 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +00001119 return true;
1120
Richard Smithce8eca52015-12-08 03:21:47 +00001121 case EM_ConstantExpression:
1122 case EM_ConstantExpressionUnevaluated:
Richard Smith045b2272019-09-10 21:24:09 +00001123 return checkingForUndefinedBehavior();
Richard Smithce8eca52015-12-08 03:21:47 +00001124 }
1125 llvm_unreachable("Missed EvalMode case");
1126 }
1127
1128 /// Note that we hit something that was technically undefined behavior, but
1129 /// that we can evaluate past it (such as signed overflow or floating-point
1130 /// division by zero.)
Nandor Licker950b70d2019-09-13 09:46:16 +00001131 bool noteUndefinedBehavior() override {
Richard Smithce8eca52015-12-08 03:21:47 +00001132 EvalStatus.HasUndefinedBehavior = true;
1133 return keepEvaluatingAfterUndefinedBehavior();
1134 }
1135
Richard Smith253c2a32012-01-27 01:14:48 +00001136 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001137 /// construct which can't be reduced to a value?
Nandor Licker950b70d2019-09-13 09:46:16 +00001138 bool keepEvaluatingAfterFailure() const override {
Richard Smith6d4c6582013-11-05 22:18:15 +00001139 if (!StepsLeft)
1140 return false;
1141
1142 switch (EvalMode) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001143 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001144 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001145 case EM_ConstantFold:
1146 case EM_IgnoreSideEffects:
Richard Smith045b2272019-09-10 21:24:09 +00001147 return checkingPotentialConstantExpression() ||
1148 checkingForUndefinedBehavior();
Richard Smith6d4c6582013-11-05 22:18:15 +00001149 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001150 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001151 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001152
George Burgess IV8c892b52016-05-25 22:31:54 +00001153 /// Notes that we failed to evaluate an expression that other expressions
1154 /// directly depend on, and determine if we should keep evaluating. This
1155 /// should only be called if we actually intend to keep evaluating.
1156 ///
1157 /// Call noteSideEffect() instead if we may be able to ignore the value that
1158 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1159 ///
1160 /// (Foo(), 1) // use noteSideEffect
1161 /// (Foo() || true) // use noteSideEffect
1162 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001163 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001164 // Failure when evaluating some expression often means there is some
1165 // subexpression whose evaluation was skipped. Therefore, (because we
1166 // don't track whether we skipped an expression when unwinding after an
1167 // evaluation failure) every evaluation failure that bubbles up from a
1168 // subexpression implies that a side-effect has potentially happened. We
1169 // skip setting the HasSideEffects flag to true until we decide to
1170 // continue evaluating after that point, which happens here.
1171 bool KeepGoing = keepEvaluatingAfterFailure();
1172 EvalStatus.HasSideEffects |= KeepGoing;
1173 return KeepGoing;
1174 }
1175
Richard Smith410306b2016-12-12 02:53:20 +00001176 class ArrayInitLoopIndex {
1177 EvalInfo &Info;
1178 uint64_t OuterIndex;
1179
1180 public:
1181 ArrayInitLoopIndex(EvalInfo &Info)
1182 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1183 Info.ArrayInitIndex = 0;
1184 }
1185 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1186
1187 operator uint64_t&() { return Info.ArrayInitIndex; }
1188 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001189 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001190
1191 /// Object used to treat all foldable expressions as constant expressions.
1192 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001193 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001194 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001195 bool HadNoPriorDiags;
1196 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001197
Richard Smith6d4c6582013-11-05 22:18:15 +00001198 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1199 : Info(Info),
1200 Enabled(Enabled),
1201 HadNoPriorDiags(Info.EvalStatus.Diag &&
1202 Info.EvalStatus.Diag->empty() &&
1203 !Info.EvalStatus.HasSideEffects),
1204 OldMode(Info.EvalMode) {
Richard Smith045b2272019-09-10 21:24:09 +00001205 if (Enabled)
Richard Smith6d4c6582013-11-05 22:18:15 +00001206 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001207 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001208 void keepDiagnostics() { Enabled = false; }
1209 ~FoldConstant() {
1210 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001211 !Info.EvalStatus.HasSideEffects)
1212 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001213 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001214 }
1215 };
Richard Smith17100ba2012-02-16 02:46:34 +00001216
James Y Knight892b09b2018-10-10 02:53:43 +00001217 /// RAII object used to set the current evaluation mode to ignore
1218 /// side-effects.
1219 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001220 EvalInfo &Info;
1221 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001222 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001223 : Info(Info), OldMode(Info.EvalMode) {
Richard Smith045b2272019-09-10 21:24:09 +00001224 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001225 }
1226
James Y Knight892b09b2018-10-10 02:53:43 +00001227 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001228 };
1229
George Burgess IV8c892b52016-05-25 22:31:54 +00001230 /// RAII object used to optionally suppress diagnostics and side-effects from
1231 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001232 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001233 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001234 Expr::EvalStatus OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001235 unsigned OldSpeculativeEvaluationDepth;
Richard Smith17100ba2012-02-16 02:46:34 +00001236
George Burgess IV8c892b52016-05-25 22:31:54 +00001237 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001238 Info = Other.Info;
1239 OldStatus = Other.OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001240 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001241 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001242 }
1243
1244 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001245 if (!Info)
1246 return;
1247
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001248 Info->EvalStatus = OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001249 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
George Burgess IV8c892b52016-05-25 22:31:54 +00001250 }
1251
Richard Smith17100ba2012-02-16 02:46:34 +00001252 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001253 SpeculativeEvaluationRAII() = default;
1254
1255 SpeculativeEvaluationRAII(
1256 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001257 : Info(&Info), OldStatus(Info.EvalStatus),
Richard Smith37be3362019-05-04 04:00:45 +00001258 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
Richard Smith17100ba2012-02-16 02:46:34 +00001259 Info.EvalStatus.Diag = NewDiag;
Richard Smith37be3362019-05-04 04:00:45 +00001260 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
Richard Smith17100ba2012-02-16 02:46:34 +00001261 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001262
1263 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1264 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1265 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001266 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001267
1268 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1269 maybeRestoreState();
1270 moveFromAndCancel(std::move(Other));
1271 return *this;
1272 }
1273
1274 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001275 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001276
1277 /// RAII object wrapping a full-expression or block scope, and handling
1278 /// the ending of the lifetime of temporaries created within it.
1279 template<bool IsFullExpression>
1280 class ScopeRAII {
1281 EvalInfo &Info;
1282 unsigned OldStackSize;
1283 public:
1284 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001285 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1286 // Push a new temporary version. This is needed to distinguish between
1287 // temporaries created in different iterations of a loop.
1288 Info.CurrentCall->pushTempVersion();
1289 }
Richard Smith457226e2019-09-23 03:48:44 +00001290 bool destroy(bool RunDestructors = true) {
1291 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1292 OldStackSize = -1U;
1293 return OK;
1294 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001295 ~ScopeRAII() {
Richard Smith457226e2019-09-23 03:48:44 +00001296 if (OldStackSize != -1U)
1297 destroy(false);
Richard Smith08d6a2c2013-07-24 07:11:57 +00001298 // Body moved to a static method to encourage the compiler to inline away
1299 // instances of this class.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001300 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001301 }
1302 private:
Richard Smithda1b4342019-09-27 01:26:47 +00001303 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1304 unsigned OldStackSize) {
1305 assert(OldStackSize <= Info.CleanupStack.size() &&
1306 "running cleanups out of order?");
1307
Richard Smith457226e2019-09-23 03:48:44 +00001308 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1309 // for a full-expression scope.
Richard Smith49494732019-09-27 05:36:16 +00001310 bool Success = true;
Richard Smith457226e2019-09-23 03:48:44 +00001311 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
Richard Smithda1b4342019-09-27 01:26:47 +00001312 if (!(IsFullExpression &&
1313 Info.CleanupStack[I - 1].isLifetimeExtended())) {
Richard Smith49494732019-09-27 05:36:16 +00001314 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1315 Success = false;
1316 break;
1317 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001318 }
1319 }
Richard Smith457226e2019-09-23 03:48:44 +00001320
1321 // Compact lifetime-extended cleanups.
1322 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1323 if (IsFullExpression)
1324 NewEnd =
1325 std::remove_if(NewEnd, Info.CleanupStack.end(),
1326 [](Cleanup &C) { return !C.isLifetimeExtended(); });
1327 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
Richard Smith49494732019-09-27 05:36:16 +00001328 return Success;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001329 }
1330 };
1331 typedef ScopeRAII<false> BlockScopeRAII;
1332 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001333}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001334
Richard Smitha8105bc2012-01-06 16:39:00 +00001335bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1336 CheckSubobjectKind CSK) {
1337 if (Invalid)
1338 return false;
1339 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001340 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001341 << CSK;
1342 setInvalid();
1343 return false;
1344 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001345 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1346 // must actually be at least one array element; even a VLA cannot have a
1347 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001348 return true;
1349}
1350
Richard Smith6f4f0f12017-10-20 22:56:25 +00001351void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1352 const Expr *E) {
1353 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1354 // Do not set the designator as invalid: we can represent this situation,
1355 // and correct handling of __builtin_object_size requires us to do so.
1356}
1357
Richard Smitha8105bc2012-01-06 16:39:00 +00001358void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001359 const Expr *E,
1360 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001361 // If we're complaining, we must be able to statically determine the size of
1362 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001363 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001364 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001365 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001366 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001367 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001368 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001369 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001370 setInvalid();
1371}
1372
Richard Smithf6f003a2011-12-16 19:06:07 +00001373CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1374 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001375 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001376 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1377 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001378 Info.CurrentCall = this;
1379 ++Info.CallStackDepth;
1380}
1381
1382CallStackFrame::~CallStackFrame() {
1383 assert(Info.CurrentCall == this && "calls retired out of order");
1384 --Info.CallStackDepth;
1385 Info.CurrentCall = Caller;
1386}
1387
Richard Smithc667cdc2019-09-18 17:37:44 +00001388static bool isRead(AccessKinds AK) {
1389 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1390}
1391
Richard Smithdebad642019-05-12 09:39:08 +00001392static bool isModification(AccessKinds AK) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00001393 switch (AK) {
1394 case AK_Read:
Richard Smithc667cdc2019-09-18 17:37:44 +00001395 case AK_ReadObjectRepresentation:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001396 case AK_MemberCall:
1397 case AK_DynamicCast:
Richard Smitha9330302019-05-17 19:19:28 +00001398 case AK_TypeId:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001399 return false;
1400 case AK_Assign:
1401 case AK_Increment:
1402 case AK_Decrement:
Richard Smithb5426022019-10-03 00:39:35 +00001403 case AK_Construct:
Richard Smith61422f92019-09-27 20:24:36 +00001404 case AK_Destroy:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001405 return true;
1406 }
1407 llvm_unreachable("unknown access kind");
1408}
1409
Richard Smith61422f92019-09-27 20:24:36 +00001410static bool isAnyAccess(AccessKinds AK) {
1411 return isRead(AK) || isModification(AK);
1412}
1413
Richard Smith7bd54ab2019-05-15 20:22:21 +00001414/// Is this an access per the C++ definition?
1415static bool isFormalAccess(AccessKinds AK) {
Richard Smithb5426022019-10-03 00:39:35 +00001416 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
Richard Smithdebad642019-05-12 09:39:08 +00001417}
1418
Richard Smithf6f003a2011-12-16 19:06:07 +00001419namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001420 struct ComplexValue {
1421 private:
1422 bool IsInt;
1423
1424 public:
1425 APSInt IntReal, IntImag;
1426 APFloat FloatReal, FloatImag;
1427
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001428 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001429
1430 void makeComplexFloat() { IsInt = false; }
1431 bool isComplexFloat() const { return !IsInt; }
1432 APFloat &getComplexFloatReal() { return FloatReal; }
1433 APFloat &getComplexFloatImag() { return FloatImag; }
1434
1435 void makeComplexInt() { IsInt = true; }
1436 bool isComplexInt() const { return IsInt; }
1437 APSInt &getComplexIntReal() { return IntReal; }
1438 APSInt &getComplexIntImag() { return IntImag; }
1439
Richard Smith2e312c82012-03-03 22:46:17 +00001440 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001441 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001442 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001443 else
Richard Smith2e312c82012-03-03 22:46:17 +00001444 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001445 }
Richard Smith2e312c82012-03-03 22:46:17 +00001446 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001447 assert(v.isComplexFloat() || v.isComplexInt());
1448 if (v.isComplexFloat()) {
1449 makeComplexFloat();
1450 FloatReal = v.getComplexFloatReal();
1451 FloatImag = v.getComplexFloatImag();
1452 } else {
1453 makeComplexInt();
1454 IntReal = v.getComplexIntReal();
1455 IntImag = v.getComplexIntImag();
1456 }
1457 }
John McCall93d91dc2010-05-07 17:22:02 +00001458 };
John McCall45d55e42010-05-07 21:00:08 +00001459
1460 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001461 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001462 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001463 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001464 bool IsNullPtr : 1;
1465 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001466
Richard Smithce40ad62011-11-12 22:28:03 +00001467 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001468 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001469 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001470 SubobjectDesignator &getLValueDesignator() { return Designator; }
1471 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001472 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001473
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001474 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1475 unsigned getLValueVersion() const { return Base.getVersion(); }
1476
Richard Smith2e312c82012-03-03 22:46:17 +00001477 void moveInto(APValue &V) const {
1478 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001479 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001480 else {
1481 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001482 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001483 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001484 }
John McCall45d55e42010-05-07 21:00:08 +00001485 }
Richard Smith2e312c82012-03-03 22:46:17 +00001486 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001487 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001488 Base = V.getLValueBase();
1489 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001490 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001491 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001492 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001493 }
1494
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001495 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001496#ifndef NDEBUG
1497 // We only allow a few types of invalid bases. Enforce that here.
1498 if (BInvalid) {
1499 const auto *E = B.get<const Expr *>();
1500 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1501 "Unexpected type of invalid base");
1502 }
1503#endif
1504
Richard Smithce40ad62011-11-12 22:28:03 +00001505 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001506 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001507 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001508 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001509 IsNullPtr = false;
1510 }
1511
Richard Smith19ad5232019-10-03 00:39:33 +00001512 void setNull(ASTContext &Ctx, QualType PointerTy) {
Tim Northover01503332017-05-26 02:16:00 +00001513 Base = (Expr *)nullptr;
Richard Smith19ad5232019-10-03 00:39:33 +00001514 Offset =
1515 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
Tim Northover01503332017-05-26 02:16:00 +00001516 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001517 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1518 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001519 }
1520
George Burgess IV3a03fab2015-09-04 21:28:13 +00001521 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001522 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001523 }
1524
Richard Smith19ad5232019-10-03 00:39:33 +00001525 std::string toString(ASTContext &Ctx, QualType T) const {
1526 APValue Printable;
1527 moveInto(Printable);
1528 return Printable.getAsString(Ctx, T);
1529 }
1530
Hubert Tong147b7432018-12-12 16:53:43 +00001531 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001532 // Check that this LValue is not based on a null pointer. If it is, produce
1533 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001534 template <typename GenDiagType>
1535 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001536 if (Designator.Invalid)
1537 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001538 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001539 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001540 Designator.setInvalid();
1541 return false;
1542 }
1543 return true;
1544 }
1545
Hubert Tong147b7432018-12-12 16:53:43 +00001546 public:
1547 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1548 CheckSubobjectKind CSK) {
1549 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1550 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1551 });
1552 }
1553
1554 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1555 AccessKinds AK) {
1556 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1557 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1558 });
1559 }
1560
Richard Smitha8105bc2012-01-06 16:39:00 +00001561 // Check this LValue refers to an object. If not, set the designator to be
1562 // invalid and emit a diagnostic.
1563 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001564 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001565 Designator.checkSubobject(Info, E, CSK);
1566 }
1567
1568 void addDecl(EvalInfo &Info, const Expr *E,
1569 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001570 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1571 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001572 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001573 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1574 if (!Designator.Entries.empty()) {
1575 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1576 Designator.setInvalid();
1577 return;
1578 }
Richard Smithefdb5032017-11-15 03:03:56 +00001579 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1580 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1581 Designator.FirstEntryIsAnUnsizedArray = true;
1582 Designator.addUnsizedArrayUnchecked(ElemTy);
1583 }
George Burgess IVe3763372016-12-22 02:50:20 +00001584 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001585 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001586 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1587 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001588 }
Richard Smith66c96992012-02-18 22:04:06 +00001589 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001590 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1591 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001592 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001593 void clearIsNullPointer() {
1594 IsNullPtr = false;
1595 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001596 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1597 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001598 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1599 // but we're not required to diagnose it and it's valid in C++.)
1600 if (!Index)
1601 return;
1602
1603 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1604 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1605 // offsets.
1606 uint64_t Offset64 = Offset.getQuantity();
1607 uint64_t ElemSize64 = ElementSize.getQuantity();
1608 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1609 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1610
1611 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001612 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001613 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001614 }
1615 void adjustOffset(CharUnits N) {
1616 Offset += N;
1617 if (N.getQuantity())
1618 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001619 }
John McCall45d55e42010-05-07 21:00:08 +00001620 };
Richard Smith027bf112011-11-17 22:56:20 +00001621
1622 struct MemberPtr {
1623 MemberPtr() {}
1624 explicit MemberPtr(const ValueDecl *Decl) :
1625 DeclAndIsDerivedMember(Decl, false), Path() {}
1626
1627 /// The member or (direct or indirect) field referred to by this member
1628 /// pointer, or 0 if this is a null member pointer.
1629 const ValueDecl *getDecl() const {
1630 return DeclAndIsDerivedMember.getPointer();
1631 }
1632 /// Is this actually a member of some type derived from the relevant class?
1633 bool isDerivedMember() const {
1634 return DeclAndIsDerivedMember.getInt();
1635 }
1636 /// Get the class which the declaration actually lives in.
1637 const CXXRecordDecl *getContainingRecord() const {
1638 return cast<CXXRecordDecl>(
1639 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1640 }
1641
Richard Smith2e312c82012-03-03 22:46:17 +00001642 void moveInto(APValue &V) const {
1643 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001644 }
Richard Smith2e312c82012-03-03 22:46:17 +00001645 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001646 assert(V.isMemberPointer());
1647 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1648 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1649 Path.clear();
1650 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1651 Path.insert(Path.end(), P.begin(), P.end());
1652 }
1653
1654 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1655 /// whether the member is a member of some class derived from the class type
1656 /// of the member pointer.
1657 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1658 /// Path - The path of base/derived classes from the member declaration's
1659 /// class (exclusive) to the class type of the member pointer (inclusive).
1660 SmallVector<const CXXRecordDecl*, 4> Path;
1661
1662 /// Perform a cast towards the class of the Decl (either up or down the
1663 /// hierarchy).
1664 bool castBack(const CXXRecordDecl *Class) {
1665 assert(!Path.empty());
1666 const CXXRecordDecl *Expected;
1667 if (Path.size() >= 2)
1668 Expected = Path[Path.size() - 2];
1669 else
1670 Expected = getContainingRecord();
1671 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1672 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1673 // if B does not contain the original member and is not a base or
1674 // derived class of the class containing the original member, the result
1675 // of the cast is undefined.
1676 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1677 // (D::*). We consider that to be a language defect.
1678 return false;
1679 }
1680 Path.pop_back();
1681 return true;
1682 }
1683 /// Perform a base-to-derived member pointer cast.
1684 bool castToDerived(const CXXRecordDecl *Derived) {
1685 if (!getDecl())
1686 return true;
1687 if (!isDerivedMember()) {
1688 Path.push_back(Derived);
1689 return true;
1690 }
1691 if (!castBack(Derived))
1692 return false;
1693 if (Path.empty())
1694 DeclAndIsDerivedMember.setInt(false);
1695 return true;
1696 }
1697 /// Perform a derived-to-base member pointer cast.
1698 bool castToBase(const CXXRecordDecl *Base) {
1699 if (!getDecl())
1700 return true;
1701 if (Path.empty())
1702 DeclAndIsDerivedMember.setInt(true);
1703 if (isDerivedMember()) {
1704 Path.push_back(Base);
1705 return true;
1706 }
1707 return castBack(Base);
1708 }
1709 };
Richard Smith357362d2011-12-13 06:39:58 +00001710
Richard Smith7bb00672012-02-01 01:42:44 +00001711 /// Compare two member pointers, which are assumed to be of the same type.
1712 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1713 if (!LHS.getDecl() || !RHS.getDecl())
1714 return !LHS.getDecl() && !RHS.getDecl();
1715 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1716 return false;
1717 return LHS.Path == RHS.Path;
1718 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001719}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001720
Richard Smith2e312c82012-03-03 22:46:17 +00001721static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001722static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1723 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001724 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001725static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1726 bool InvalidBaseOK = false);
1727static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1728 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001729static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1730 EvalInfo &Info);
1731static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001732static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001733static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001734 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001735static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001736static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001737static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1738 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001739static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001740
Leonard Chand3f3e162019-01-18 21:04:25 +00001741/// Evaluate an integer or fixed point expression into an APResult.
1742static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1743 EvalInfo &Info);
1744
1745/// Evaluate only a fixed point expression into an APResult.
1746static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1747 EvalInfo &Info);
1748
Chris Lattner05706e882008-07-11 18:11:29 +00001749//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001750// Misc utilities
1751//===----------------------------------------------------------------------===//
1752
Richard Smithd6cc1982017-01-31 02:23:02 +00001753/// Negate an APSInt in place, converting it to a signed form if necessary, and
1754/// preserving its value (by extending by up to one bit as needed).
1755static void negateAsSigned(APSInt &Int) {
1756 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1757 Int = Int.extend(Int.getBitWidth() + 1);
1758 Int.setIsSigned(true);
1759 }
1760 Int = -Int;
1761}
1762
Richard Smith457226e2019-09-23 03:48:44 +00001763template<typename KeyT>
1764APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1765 bool IsLifetimeExtended, LValue &LV) {
Richard Smithda1b4342019-09-27 01:26:47 +00001766 unsigned Version = getTempVersion();
Richard Smith457226e2019-09-23 03:48:44 +00001767 APValue::LValueBase Base(Key, Index, Version);
1768 LV.set(Base);
1769 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1770 assert(Result.isAbsent() && "temporary created multiple times");
Richard Smithda1b4342019-09-27 01:26:47 +00001771
1772 // If we're creating a temporary immediately in the operand of a speculative
1773 // evaluation, don't register a cleanup to be run outside the speculative
1774 // evaluation context, since we won't actually be able to initialize this
1775 // object.
1776 if (Index <= Info.SpeculativeEvaluationDepth) {
1777 if (T.isDestructedType())
1778 Info.noteSideEffect();
1779 } else {
1780 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1781 }
Richard Smith457226e2019-09-23 03:48:44 +00001782 return Result;
1783}
1784
Richard Smithda1b4342019-09-27 01:26:47 +00001785APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1786 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1787 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1788 return nullptr;
1789 }
1790
1791 DynamicAllocLValue DA(NumHeapAllocs++);
1792 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1793 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1794 std::forward_as_tuple(DA), std::tuple<>());
1795 assert(Result.second && "reused a heap alloc index?");
1796 Result.first->second.AllocExpr = E;
1797 return &Result.first->second.Value;
1798}
1799
Richard Smith84401042013-06-03 05:03:02 +00001800/// Produce a string describing the given constexpr call.
Nandor Licker950b70d2019-09-13 09:46:16 +00001801void CallStackFrame::describe(raw_ostream &Out) {
Richard Smith84401042013-06-03 05:03:02 +00001802 unsigned ArgIndex = 0;
Nandor Licker950b70d2019-09-13 09:46:16 +00001803 bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1804 !isa<CXXConstructorDecl>(Callee) &&
1805 cast<CXXMethodDecl>(Callee)->isInstance();
Richard Smith84401042013-06-03 05:03:02 +00001806
1807 if (!IsMemberCall)
Nandor Licker950b70d2019-09-13 09:46:16 +00001808 Out << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001809
Nandor Licker950b70d2019-09-13 09:46:16 +00001810 if (This && IsMemberCall) {
Richard Smith84401042013-06-03 05:03:02 +00001811 APValue Val;
Nandor Licker950b70d2019-09-13 09:46:16 +00001812 This->moveInto(Val);
1813 Val.printPretty(Out, Info.Ctx,
1814 This->Designator.MostDerivedType);
Richard Smith84401042013-06-03 05:03:02 +00001815 // FIXME: Add parens around Val if needed.
Nandor Licker950b70d2019-09-13 09:46:16 +00001816 Out << "->" << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001817 IsMemberCall = false;
1818 }
1819
Nandor Licker950b70d2019-09-13 09:46:16 +00001820 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1821 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
Richard Smith84401042013-06-03 05:03:02 +00001822 if (ArgIndex > (unsigned)IsMemberCall)
1823 Out << ", ";
1824
1825 const ParmVarDecl *Param = *I;
Nandor Licker950b70d2019-09-13 09:46:16 +00001826 const APValue &Arg = Arguments[ArgIndex];
1827 Arg.printPretty(Out, Info.Ctx, Param->getType());
Richard Smith84401042013-06-03 05:03:02 +00001828
1829 if (ArgIndex == 0 && IsMemberCall)
Nandor Licker950b70d2019-09-13 09:46:16 +00001830 Out << "->" << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001831 }
1832
1833 Out << ')';
1834}
1835
Richard Smithd9f663b2013-04-22 15:31:51 +00001836/// Evaluate an expression to see if it had side-effects, and discard its
1837/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001838/// \return \c true if the caller should keep evaluating.
1839static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001840 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001841 if (!Evaluate(Scratch, Info, E))
1842 // We don't need the value, but we might have skipped a side effect here.
1843 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001844 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001845}
1846
Richard Smithd62306a2011-11-10 06:34:14 +00001847/// Should this call expression be treated as a string literal?
1848static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001849 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001850 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1851 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1852}
1853
Richard Smithce40ad62011-11-12 22:28:03 +00001854static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001855 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1856 // constant expression of pointer type that evaluates to...
1857
1858 // ... a null pointer value, or a prvalue core constant expression of type
1859 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001860 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001861
Richard Smithce40ad62011-11-12 22:28:03 +00001862 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1863 // ... the address of an object with static storage duration,
1864 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1865 return VD->hasGlobalStorage();
1866 // ... the address of a function,
1867 return isa<FunctionDecl>(D);
1868 }
1869
Richard Smithda1b4342019-09-27 01:26:47 +00001870 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
Richard Smithee0ce3022019-05-17 07:06:46 +00001871 return true;
1872
Richard Smithce40ad62011-11-12 22:28:03 +00001873 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001874 switch (E->getStmtClass()) {
1875 default:
1876 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001877 case Expr::CompoundLiteralExprClass: {
1878 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1879 return CLE->isFileScope() && CLE->isLValue();
1880 }
Richard Smithe6c01442013-06-05 00:46:14 +00001881 case Expr::MaterializeTemporaryExprClass:
1882 // A materialized temporary might have been lifetime-extended to static
1883 // storage duration.
1884 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001885 // A string literal has static storage duration.
1886 case Expr::StringLiteralClass:
1887 case Expr::PredefinedExprClass:
1888 case Expr::ObjCStringLiteralClass:
1889 case Expr::ObjCEncodeExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001890 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001891 return true;
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001892 case Expr::ObjCBoxedExprClass:
1893 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
Richard Smithd62306a2011-11-10 06:34:14 +00001894 case Expr::CallExprClass:
1895 return IsStringLiteralCall(cast<CallExpr>(E));
1896 // For GCC compatibility, &&label has static storage duration.
1897 case Expr::AddrLabelExprClass:
1898 return true;
1899 // A Block literal expression may be used as the initialization value for
1900 // Block variables at global or local static scope.
1901 case Expr::BlockExprClass:
1902 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001903 case Expr::ImplicitValueInitExprClass:
1904 // FIXME:
1905 // We can never form an lvalue with an implicit value initialization as its
1906 // base through expression evaluation, so these only appear in one case: the
1907 // implicit variable declaration we invent when checking whether a constexpr
1908 // constructor can produce a constant expression. We must assume that such
1909 // an expression might be a global lvalue.
1910 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001911 }
John McCall95007602010-05-10 23:27:23 +00001912}
1913
Richard Smith06f71b52018-08-04 00:57:17 +00001914static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1915 return LVal.Base.dyn_cast<const ValueDecl*>();
1916}
1917
1918static bool IsLiteralLValue(const LValue &Value) {
1919 if (Value.getLValueCallIndex())
1920 return false;
1921 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1922 return E && !isa<MaterializeTemporaryExpr>(E);
1923}
1924
1925static bool IsWeakLValue(const LValue &Value) {
1926 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1927 return Decl && Decl->isWeak();
1928}
1929
1930static bool isZeroSized(const LValue &Value) {
1931 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1932 if (Decl && isa<VarDecl>(Decl)) {
1933 QualType Ty = Decl->getType();
1934 if (Ty->isArrayType())
1935 return Ty->isIncompleteType() ||
1936 Decl->getASTContext().getTypeSize(Ty) == 0;
1937 }
1938 return false;
1939}
1940
1941static bool HasSameBase(const LValue &A, const LValue &B) {
1942 if (!A.getLValueBase())
1943 return !B.getLValueBase();
1944 if (!B.getLValueBase())
1945 return false;
1946
1947 if (A.getLValueBase().getOpaqueValue() !=
1948 B.getLValueBase().getOpaqueValue()) {
1949 const Decl *ADecl = GetLValueBaseDecl(A);
1950 if (!ADecl)
1951 return false;
1952 const Decl *BDecl = GetLValueBaseDecl(B);
1953 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1954 return false;
1955 }
1956
1957 return IsGlobalLValue(A.getLValueBase()) ||
1958 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1959 A.getLValueVersion() == B.getLValueVersion());
1960}
1961
Richard Smithb228a862012-02-15 02:18:13 +00001962static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1963 assert(Base && "no location for a null lvalue");
1964 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1965 if (VD)
1966 Info.Note(VD->getLocation(), diag::note_declared_at);
Richard Smithee0ce3022019-05-17 07:06:46 +00001967 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1968 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
Richard Smithda1b4342019-09-27 01:26:47 +00001969 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
1970 // FIXME: Produce a note for dangling pointers too.
Richard Smith19ad5232019-10-03 00:39:33 +00001971 if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
Richard Smithda1b4342019-09-27 01:26:47 +00001972 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
1973 diag::note_constexpr_dynamic_alloc_here);
1974 }
Richard Smithee0ce3022019-05-17 07:06:46 +00001975 // We have no information to show for a typeid(T) object.
Richard Smithb228a862012-02-15 02:18:13 +00001976}
1977
Richard Smith4566f872019-09-29 05:58:31 +00001978enum class CheckEvaluationResultKind {
1979 ConstantExpression,
1980 FullyInitialized,
1981};
1982
1983/// Materialized temporaries that we've already checked to determine if they're
1984/// initializsed by a constant expression.
1985using CheckedTemporaries =
1986 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
1987
1988static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
1989 EvalInfo &Info, SourceLocation DiagLoc,
1990 QualType Type, const APValue &Value,
1991 Expr::ConstExprUsage Usage,
1992 SourceLocation SubobjectLoc,
1993 CheckedTemporaries &CheckedTemps);
1994
Richard Smith80815602011-11-07 05:07:52 +00001995/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001996/// value for an address or reference constant expression. Return true if we
1997/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001998static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001999 QualType Type, const LValue &LVal,
Richard Smith4566f872019-09-29 05:58:31 +00002000 Expr::ConstExprUsage Usage,
2001 CheckedTemporaries &CheckedTemps) {
Richard Smithb228a862012-02-15 02:18:13 +00002002 bool IsReferenceType = Type->isReferenceType();
2003
Richard Smith357362d2011-12-13 06:39:58 +00002004 APValue::LValueBase Base = LVal.getLValueBase();
2005 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2006
Richard Smith0dea49e2012-02-18 04:58:18 +00002007 // Check that the object is a global. Note that the fake 'this' object we
2008 // manufacture when checking potential constant expressions is conservatively
2009 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00002010 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002011 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00002012 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00002013 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00002014 << IsReferenceType << !Designator.Entries.empty()
2015 << !!VD << VD;
2016 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00002017 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002018 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00002019 }
Richard Smith02ab9c22012-01-12 06:08:57 +00002020 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00002021 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002022 }
Richard Smith6d4c6582013-11-05 22:18:15 +00002023 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00002024 LVal.getLValueCallIndex() == 0) &&
2025 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00002026
Richard Smithda1b4342019-09-27 01:26:47 +00002027 if (Base.is<DynamicAllocLValue>()) {
2028 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2029 << IsReferenceType << !Designator.Entries.empty();
2030 NoteLValueLocation(Info, Base);
2031 return false;
2032 }
2033
Hans Wennborgcb9ad992012-08-29 18:27:29 +00002034 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2035 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00002036 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00002037 if (Var->getTLSKind())
Richard Smithda1b4342019-09-27 01:26:47 +00002038 // FIXME: Diagnostic!
Hans Wennborgcb9ad992012-08-29 18:27:29 +00002039 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00002040
Hans Wennborg82dd8772014-06-25 22:19:48 +00002041 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00002042 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
Richard Smithda1b4342019-09-27 01:26:47 +00002043 // FIXME: Diagnostic!
David Majnemer0c43d802014-06-25 08:15:07 +00002044 return false;
2045 }
2046 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2047 // __declspec(dllimport) must be handled very carefully:
2048 // We must never initialize an expression with the thunk in C++.
2049 // Doing otherwise would allow the same id-expression to yield
2050 // different addresses for the same function in different translation
2051 // units. However, this means that we must dynamically initialize the
2052 // expression with the contents of the import address table at runtime.
2053 //
2054 // The C language has no notion of ODR; furthermore, it has no notion of
2055 // dynamic initialization. This means that we are permitted to
2056 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00002057 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2058 FD->hasAttr<DLLImportAttr>())
Richard Smithda1b4342019-09-27 01:26:47 +00002059 // FIXME: Diagnostic!
David Majnemer0c43d802014-06-25 08:15:07 +00002060 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00002061 }
Richard Smith4566f872019-09-29 05:58:31 +00002062 } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2063 Base.dyn_cast<const Expr *>())) {
2064 if (CheckedTemps.insert(MTE).second) {
Richard Smith1e8c0852019-09-29 06:22:54 +00002065 QualType TempType = getType(Base);
2066 if (TempType.isDestructedType()) {
2067 Info.FFDiag(MTE->getExprLoc(),
2068 diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2069 << TempType;
2070 return false;
2071 }
2072
Tykerb0561b32019-11-17 11:41:55 +01002073 APValue *V = MTE->getOrCreateValue(false);
Richard Smith4566f872019-09-29 05:58:31 +00002074 assert(V && "evasluation result refers to uninitialised temporary");
2075 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
Richard Smith1e8c0852019-09-29 06:22:54 +00002076 Info, MTE->getExprLoc(), TempType, *V,
Richard Smith4566f872019-09-29 05:58:31 +00002077 Usage, SourceLocation(), CheckedTemps))
2078 return false;
2079 }
Hans Wennborgcb9ad992012-08-29 18:27:29 +00002080 }
2081
Richard Smitha8105bc2012-01-06 16:39:00 +00002082 // Allow address constant expressions to be past-the-end pointers. This is
2083 // an extension: the standard requires them to point to an object.
2084 if (!IsReferenceType)
2085 return true;
2086
2087 // A reference constant expression must refer to an object.
2088 if (!Base) {
2089 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00002090 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00002091 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00002092 }
2093
Richard Smith357362d2011-12-13 06:39:58 +00002094 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00002095 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00002096 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00002097 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00002098 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00002099 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00002100 }
2101
Richard Smith80815602011-11-07 05:07:52 +00002102 return true;
2103}
2104
Reid Klecknercd016d82017-07-07 22:04:29 +00002105/// Member pointers are constant expressions unless they point to a
2106/// non-virtual dllimport member function.
2107static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2108 SourceLocation Loc,
2109 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00002110 const APValue &Value,
2111 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00002112 const ValueDecl *Member = Value.getMemberPointerDecl();
2113 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2114 if (!FD)
2115 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002116 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2117 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00002118}
2119
Richard Smithfddd3842011-12-30 21:15:51 +00002120/// Check that this core constant expression is of literal type, and if not,
2121/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00002122static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00002123 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002124 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00002125 return true;
2126
Richard Smith7525ff62013-05-09 07:14:00 +00002127 // C++1y: A constant initializer for an object o [...] may also invoke
2128 // constexpr constructors for o and its subobjects even if those objects
2129 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00002130 //
2131 // C++11 missed this detail for aggregates, so classes like this:
2132 // struct foo_t { union { int i; volatile int j; } u; };
2133 // are not (obviously) initializable like so:
2134 // __attribute__((__require_constant_initialization__))
2135 // static const foo_t x = {{0}};
2136 // because "i" is a subobject with non-literal initialization (due to the
2137 // volatile member of the union). See:
2138 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2139 // Therefore, we use the C++1y behavior.
2140 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00002141 return true;
2142
Richard Smithfddd3842011-12-30 21:15:51 +00002143 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002144 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002145 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00002146 << E->getType();
2147 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002148 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00002149 return false;
2150}
2151
Richard Smith4566f872019-09-29 05:58:31 +00002152static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2153 EvalInfo &Info, SourceLocation DiagLoc,
2154 QualType Type, const APValue &Value,
2155 Expr::ConstExprUsage Usage,
2156 SourceLocation SubobjectLoc,
2157 CheckedTemporaries &CheckedTemps) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002158 if (!Value.hasValue()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002159 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00002160 << true << Type;
Richard Smith31c69a32019-05-21 23:15:20 +00002161 if (SubobjectLoc.isValid())
2162 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
Richard Smith1a90f592013-06-18 17:51:51 +00002163 return false;
2164 }
2165
Richard Smith77be48a2014-07-31 06:31:19 +00002166 // We allow _Atomic(T) to be initialized from anything that T can be
2167 // initialized from.
2168 if (const AtomicType *AT = Type->getAs<AtomicType>())
2169 Type = AT->getValueType();
2170
Richard Smithb228a862012-02-15 02:18:13 +00002171 // Core issue 1454: For a literal constant expression of array or class type,
2172 // each subobject of its value shall have been initialized by a constant
2173 // expression.
2174 if (Value.isArray()) {
2175 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2176 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
Richard Smithc667cdc2019-09-18 17:37:44 +00002177 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2178 Value.getArrayInitializedElt(I), Usage,
Richard Smith4566f872019-09-29 05:58:31 +00002179 SubobjectLoc, CheckedTemps))
Richard Smithb228a862012-02-15 02:18:13 +00002180 return false;
2181 }
2182 if (!Value.hasArrayFiller())
2183 return true;
Richard Smithc667cdc2019-09-18 17:37:44 +00002184 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
Richard Smith4566f872019-09-29 05:58:31 +00002185 Value.getArrayFiller(), Usage, SubobjectLoc,
2186 CheckedTemps);
Richard Smith80815602011-11-07 05:07:52 +00002187 }
Richard Smithb228a862012-02-15 02:18:13 +00002188 if (Value.isUnion() && Value.getUnionField()) {
Richard Smithc667cdc2019-09-18 17:37:44 +00002189 return CheckEvaluationResult(
2190 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
Richard Smith4566f872019-09-29 05:58:31 +00002191 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2192 CheckedTemps);
Richard Smithb228a862012-02-15 02:18:13 +00002193 }
2194 if (Value.isStruct()) {
2195 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2196 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2197 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002198 for (const CXXBaseSpecifier &BS : CD->bases()) {
Richard Smithc667cdc2019-09-18 17:37:44 +00002199 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2200 Value.getStructBase(BaseIndex), Usage,
Richard Smith4566f872019-09-29 05:58:31 +00002201 BS.getBeginLoc(), CheckedTemps))
Richard Smithb228a862012-02-15 02:18:13 +00002202 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002203 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00002204 }
2205 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002206 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00002207 if (I->isUnnamedBitfield())
2208 continue;
2209
Richard Smithc667cdc2019-09-18 17:37:44 +00002210 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2211 Value.getStructField(I->getFieldIndex()),
Richard Smith4566f872019-09-29 05:58:31 +00002212 Usage, I->getLocation(), CheckedTemps))
Richard Smithb228a862012-02-15 02:18:13 +00002213 return false;
2214 }
2215 }
2216
Richard Smithc667cdc2019-09-18 17:37:44 +00002217 if (Value.isLValue() &&
2218 CERK == CheckEvaluationResultKind::ConstantExpression) {
Richard Smithb228a862012-02-15 02:18:13 +00002219 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00002220 LVal.setFrom(Info.Ctx, Value);
Richard Smith4566f872019-09-29 05:58:31 +00002221 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2222 CheckedTemps);
Richard Smithb228a862012-02-15 02:18:13 +00002223 }
2224
Richard Smithc667cdc2019-09-18 17:37:44 +00002225 if (Value.isMemberPointer() &&
2226 CERK == CheckEvaluationResultKind::ConstantExpression)
Reid Kleckner1a840d22018-05-10 18:57:35 +00002227 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00002228
Richard Smithb228a862012-02-15 02:18:13 +00002229 // Everything else is fine.
2230 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002231}
2232
Richard Smithc667cdc2019-09-18 17:37:44 +00002233/// Check that this core constant expression value is a valid value for a
2234/// constant expression. If not, report an appropriate diagnostic. Does not
2235/// check that the expression is of literal type.
2236static bool
2237CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2238 const APValue &Value,
2239 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
Richard Smith4566f872019-09-29 05:58:31 +00002240 CheckedTemporaries CheckedTemps;
Richard Smithc667cdc2019-09-18 17:37:44 +00002241 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
Richard Smith4566f872019-09-29 05:58:31 +00002242 Info, DiagLoc, Type, Value, Usage,
2243 SourceLocation(), CheckedTemps);
Richard Smithc667cdc2019-09-18 17:37:44 +00002244}
2245
2246/// Check that this evaluated value is fully-initialized and can be loaded by
2247/// an lvalue-to-rvalue conversion.
2248static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2249 QualType Type, const APValue &Value) {
Richard Smith4566f872019-09-29 05:58:31 +00002250 CheckedTemporaries CheckedTemps;
2251 return CheckEvaluationResult(
2252 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2253 Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
Richard Smithc667cdc2019-09-18 17:37:44 +00002254}
2255
Richard Smithda1b4342019-09-27 01:26:47 +00002256/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2257/// "the allocated storage is deallocated within the evaluation".
2258static bool CheckMemoryLeaks(EvalInfo &Info) {
2259 if (!Info.HeapAllocs.empty()) {
2260 // We can still fold to a constant despite a compile-time memory leak,
2261 // so long as the heap allocation isn't referenced in the result (we check
2262 // that in CheckConstantExpression).
2263 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2264 diag::note_constexpr_memory_leak)
2265 << unsigned(Info.HeapAllocs.size() - 1);
2266 }
2267 return true;
2268}
2269
Richard Smith2e312c82012-03-03 22:46:17 +00002270static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00002271 // A null base expression indicates a null pointer. These are always
2272 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00002273 if (!Value.getLValueBase()) {
2274 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002275 return true;
2276 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002277
Richard Smith027bf112011-11-17 22:56:20 +00002278 // We have a non-null base. These are generally known to be true, but if it's
2279 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002280 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002281 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002282 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002283}
2284
Richard Smith2e312c82012-03-03 22:46:17 +00002285static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002286 switch (Val.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002287 case APValue::None:
2288 case APValue::Indeterminate:
Richard Smith11562c52011-10-28 17:51:58 +00002289 return false;
2290 case APValue::Int:
2291 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002292 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00002293 case APValue::FixedPoint:
2294 Result = Val.getFixedPoint().getBoolValue();
2295 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002296 case APValue::Float:
2297 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002298 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002299 case APValue::ComplexInt:
2300 Result = Val.getComplexIntReal().getBoolValue() ||
2301 Val.getComplexIntImag().getBoolValue();
2302 return true;
2303 case APValue::ComplexFloat:
2304 Result = !Val.getComplexFloatReal().isZero() ||
2305 !Val.getComplexFloatImag().isZero();
2306 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002307 case APValue::LValue:
2308 return EvalPointerValueAsBool(Val, Result);
2309 case APValue::MemberPointer:
2310 Result = Val.getMemberPointerDecl();
2311 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002312 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002313 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002314 case APValue::Struct:
2315 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002316 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002317 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002318 }
2319
Richard Smith11562c52011-10-28 17:51:58 +00002320 llvm_unreachable("unknown APValue kind");
2321}
2322
2323static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2324 EvalInfo &Info) {
2325 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002326 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002327 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002328 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002329 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002330}
2331
Richard Smith357362d2011-12-13 06:39:58 +00002332template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002333static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002334 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002335 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002336 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002337 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002338}
2339
2340static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2341 QualType SrcType, const APFloat &Value,
2342 QualType DestType, APSInt &Result) {
2343 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002344 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002345 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002346
Richard Smith357362d2011-12-13 06:39:58 +00002347 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002348 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002349 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2350 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002351 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002352 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002353}
2354
Richard Smith357362d2011-12-13 06:39:58 +00002355static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2356 QualType SrcType, QualType DestType,
2357 APFloat &Result) {
2358 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002359 bool ignored;
Richard Smith9e52c432019-07-06 21:05:52 +00002360 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2361 APFloat::rmNearestTiesToEven, &ignored);
Richard Smith357362d2011-12-13 06:39:58 +00002362 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002363}
2364
Richard Smith911e1422012-01-30 22:27:01 +00002365static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2366 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002367 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002368 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002369 // Figure out if this is a truncate, extend or noop cast.
2370 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002371 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002372 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002373 if (DestType->isBooleanType())
2374 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002375 return Result;
2376}
2377
Richard Smith357362d2011-12-13 06:39:58 +00002378static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2379 QualType SrcType, const APSInt &Value,
2380 QualType DestType, APFloat &Result) {
2381 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
Richard Smith9e52c432019-07-06 21:05:52 +00002382 Result.convertFromAPInt(Value, Value.isSigned(),
2383 APFloat::rmNearestTiesToEven);
Richard Smith357362d2011-12-13 06:39:58 +00002384 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002385}
2386
Richard Smith49ca8aa2013-08-06 07:09:20 +00002387static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2388 APValue &Value, const FieldDecl *FD) {
2389 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2390
2391 if (!Value.isInt()) {
2392 // Trying to store a pointer-cast-to-integer into a bitfield.
2393 // FIXME: In this case, we should provide the diagnostic for casting
2394 // a pointer to an integer.
2395 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002396 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002397 return false;
2398 }
2399
2400 APSInt &Int = Value.getInt();
2401 unsigned OldBitWidth = Int.getBitWidth();
2402 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2403 if (NewBitWidth < OldBitWidth)
2404 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2405 return true;
2406}
2407
Eli Friedman803acb32011-12-22 03:51:45 +00002408static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2409 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002410 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002411 if (!Evaluate(SVal, Info, E))
2412 return false;
2413 if (SVal.isInt()) {
2414 Res = SVal.getInt();
2415 return true;
2416 }
2417 if (SVal.isFloat()) {
2418 Res = SVal.getFloat().bitcastToAPInt();
2419 return true;
2420 }
2421 if (SVal.isVector()) {
2422 QualType VecTy = E->getType();
2423 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2424 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2425 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2426 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2427 Res = llvm::APInt::getNullValue(VecSize);
2428 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2429 APValue &Elt = SVal.getVectorElt(i);
2430 llvm::APInt EltAsInt;
2431 if (Elt.isInt()) {
2432 EltAsInt = Elt.getInt();
2433 } else if (Elt.isFloat()) {
2434 EltAsInt = Elt.getFloat().bitcastToAPInt();
2435 } else {
2436 // Don't try to handle vectors of anything other than int or float
2437 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002438 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002439 return false;
2440 }
2441 unsigned BaseEltSize = EltAsInt.getBitWidth();
2442 if (BigEndian)
2443 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2444 else
2445 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2446 }
2447 return true;
2448 }
2449 // Give up if the input isn't an int, float, or vector. For example, we
2450 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002451 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002452 return false;
2453}
2454
Richard Smith43e77732013-05-07 04:50:00 +00002455/// Perform the given integer operation, which is known to need at most BitWidth
2456/// bits, and check for overflow in the original type (if that type was not an
2457/// unsigned type).
2458template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002459static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2460 const APSInt &LHS, const APSInt &RHS,
2461 unsigned BitWidth, Operation Op,
2462 APSInt &Result) {
2463 if (LHS.isUnsigned()) {
2464 Result = Op(LHS, RHS);
2465 return true;
2466 }
Richard Smith43e77732013-05-07 04:50:00 +00002467
2468 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002469 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002470 if (Result.extend(BitWidth) != Value) {
Richard Smith045b2272019-09-10 21:24:09 +00002471 if (Info.checkingForUndefinedBehavior())
Richard Smith43e77732013-05-07 04:50:00 +00002472 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002473 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002474 << Result.toString(10) << E->getType();
2475 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002476 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002477 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002478 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002479}
2480
2481/// Perform the given binary integer operation.
2482static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2483 BinaryOperatorKind Opcode, APSInt RHS,
2484 APSInt &Result) {
2485 switch (Opcode) {
2486 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002487 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002488 return false;
2489 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002490 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2491 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002492 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002493 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2494 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002495 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002496 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2497 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002498 case BO_And: Result = LHS & RHS; return true;
2499 case BO_Xor: Result = LHS ^ RHS; return true;
2500 case BO_Or: Result = LHS | RHS; return true;
2501 case BO_Div:
2502 case BO_Rem:
2503 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002504 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002505 return false;
2506 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002507 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2508 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2509 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002510 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2511 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002512 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2513 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002514 return true;
2515 case BO_Shl: {
2516 if (Info.getLangOpts().OpenCL)
2517 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2518 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2519 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2520 RHS.isUnsigned());
2521 else if (RHS.isSigned() && RHS.isNegative()) {
2522 // During constant-folding, a negative shift is an opposite shift. Such
2523 // a shift is not a constant expression.
2524 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2525 RHS = -RHS;
2526 goto shift_right;
2527 }
2528 shift_left:
2529 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2530 // the shifted type.
2531 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2532 if (SA != RHS) {
2533 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2534 << RHS << E->getType() << LHS.getBitWidth();
Richard Smith7939ba02019-06-25 01:45:26 +00002535 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
Richard Smith43e77732013-05-07 04:50:00 +00002536 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2537 // operand, and must not overflow the corresponding unsigned type.
Richard Smith7939ba02019-06-25 01:45:26 +00002538 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2539 // E1 x 2^E2 module 2^N.
Richard Smith43e77732013-05-07 04:50:00 +00002540 if (LHS.isNegative())
2541 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2542 else if (LHS.countLeadingZeros() < SA)
2543 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2544 }
2545 Result = LHS << SA;
2546 return true;
2547 }
2548 case BO_Shr: {
2549 if (Info.getLangOpts().OpenCL)
2550 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2551 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2552 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2553 RHS.isUnsigned());
2554 else if (RHS.isSigned() && RHS.isNegative()) {
2555 // During constant-folding, a negative shift is an opposite shift. Such a
2556 // shift is not a constant expression.
2557 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2558 RHS = -RHS;
2559 goto shift_left;
2560 }
2561 shift_right:
2562 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2563 // shifted type.
2564 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2565 if (SA != RHS)
2566 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2567 << RHS << E->getType() << LHS.getBitWidth();
2568 Result = LHS >> SA;
2569 return true;
2570 }
2571
2572 case BO_LT: Result = LHS < RHS; return true;
2573 case BO_GT: Result = LHS > RHS; return true;
2574 case BO_LE: Result = LHS <= RHS; return true;
2575 case BO_GE: Result = LHS >= RHS; return true;
2576 case BO_EQ: Result = LHS == RHS; return true;
2577 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002578 case BO_Cmp:
2579 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002580 }
2581}
2582
Richard Smith861b5b52013-05-07 23:34:45 +00002583/// Perform the given binary floating-point operation, in-place, on LHS.
2584static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2585 APFloat &LHS, BinaryOperatorKind Opcode,
2586 const APFloat &RHS) {
2587 switch (Opcode) {
2588 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002589 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002590 return false;
2591 case BO_Mul:
2592 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2593 break;
2594 case BO_Add:
2595 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2596 break;
2597 case BO_Sub:
2598 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2599 break;
2600 case BO_Div:
Richard Smith9e52c432019-07-06 21:05:52 +00002601 // [expr.mul]p4:
2602 // If the second operand of / or % is zero the behavior is undefined.
2603 if (RHS.isZero())
2604 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
Richard Smith861b5b52013-05-07 23:34:45 +00002605 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2606 break;
2607 }
2608
Richard Smith9e52c432019-07-06 21:05:52 +00002609 // [expr.pre]p4:
2610 // If during the evaluation of an expression, the result is not
2611 // mathematically defined [...], the behavior is undefined.
2612 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2613 if (LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002614 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002615 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002616 }
Richard Smith861b5b52013-05-07 23:34:45 +00002617 return true;
2618}
2619
Richard Smitha8105bc2012-01-06 16:39:00 +00002620/// Cast an lvalue referring to a base subobject to a derived class, by
2621/// truncating the lvalue's path to the given length.
2622static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2623 const RecordDecl *TruncatedType,
2624 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002625 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002626
2627 // Check we actually point to a derived class object.
2628 if (TruncatedElements == D.Entries.size())
2629 return true;
2630 assert(TruncatedElements >= D.MostDerivedPathLength &&
2631 "not casting to a derived class");
2632 if (!Result.checkSubobject(Info, E, CSK_Derived))
2633 return false;
2634
2635 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002636 const RecordDecl *RD = TruncatedType;
2637 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002638 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002639 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2640 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002641 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002642 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002643 else
Richard Smithd62306a2011-11-10 06:34:14 +00002644 Result.Offset -= Layout.getBaseClassOffset(Base);
2645 RD = Base;
2646 }
Richard Smith027bf112011-11-17 22:56:20 +00002647 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002648 return true;
2649}
2650
John McCalld7bca762012-05-01 00:38:49 +00002651static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002652 const CXXRecordDecl *Derived,
2653 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002654 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002655 if (!RL) {
2656 if (Derived->isInvalidDecl()) return false;
2657 RL = &Info.Ctx.getASTRecordLayout(Derived);
2658 }
2659
Richard Smithd62306a2011-11-10 06:34:14 +00002660 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002661 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002662 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002663}
2664
Richard Smitha8105bc2012-01-06 16:39:00 +00002665static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002666 const CXXRecordDecl *DerivedDecl,
2667 const CXXBaseSpecifier *Base) {
2668 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2669
John McCalld7bca762012-05-01 00:38:49 +00002670 if (!Base->isVirtual())
2671 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002672
Richard Smitha8105bc2012-01-06 16:39:00 +00002673 SubobjectDesignator &D = Obj.Designator;
2674 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002675 return false;
2676
Richard Smitha8105bc2012-01-06 16:39:00 +00002677 // Extract most-derived object and corresponding type.
2678 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2679 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2680 return false;
2681
2682 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002683 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002684 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2685 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002686 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002687 return true;
2688}
2689
Richard Smith84401042013-06-03 05:03:02 +00002690static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2691 QualType Type, LValue &Result) {
2692 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2693 PathE = E->path_end();
2694 PathI != PathE; ++PathI) {
2695 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2696 *PathI))
2697 return false;
2698 Type = (*PathI)->getType();
2699 }
2700 return true;
2701}
2702
Richard Smith921f1322019-05-13 23:35:21 +00002703/// Cast an lvalue referring to a derived class to a known base subobject.
2704static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2705 const CXXRecordDecl *DerivedRD,
2706 const CXXRecordDecl *BaseRD) {
2707 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2708 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2709 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2710 llvm_unreachable("Class must be derived from the passed in base class!");
2711
2712 for (CXXBasePathElement &Elem : Paths.front())
2713 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2714 return false;
2715 return true;
2716}
2717
Richard Smithd62306a2011-11-10 06:34:14 +00002718/// Update LVal to refer to the given field, which must be a member of the type
2719/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002720static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002721 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002722 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002723 if (!RL) {
2724 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002725 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002726 }
Richard Smithd62306a2011-11-10 06:34:14 +00002727
2728 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002729 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002730 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002731 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002732}
2733
Richard Smith1b78b3d2012-01-25 22:15:11 +00002734/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002735static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002736 LValue &LVal,
2737 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002738 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002739 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002740 return false;
2741 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002742}
2743
Richard Smithd62306a2011-11-10 06:34:14 +00002744/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002745static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2746 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002747 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2748 // extension.
2749 if (Type->isVoidType() || Type->isFunctionType()) {
2750 Size = CharUnits::One();
2751 return true;
2752 }
2753
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002754 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002755 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002756 return false;
2757 }
2758
Richard Smithd62306a2011-11-10 06:34:14 +00002759 if (!Type->isConstantSizeType()) {
2760 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002761 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002762 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002763 return false;
2764 }
2765
2766 Size = Info.Ctx.getTypeSizeInChars(Type);
2767 return true;
2768}
2769
2770/// Update a pointer value to model pointer arithmetic.
2771/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002772/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002773/// \param LVal - The pointer value to be updated.
2774/// \param EltTy - The pointee type represented by LVal.
2775/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002776static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2777 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002778 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002779 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002780 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002781 return false;
2782
Yaxun Liu402804b2016-12-15 08:09:08 +00002783 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002784 return true;
2785}
2786
Richard Smithd6cc1982017-01-31 02:23:02 +00002787static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2788 LValue &LVal, QualType EltTy,
2789 int64_t Adjustment) {
2790 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2791 APSInt::get(Adjustment));
2792}
2793
Richard Smith66c96992012-02-18 22:04:06 +00002794/// Update an lvalue to refer to a component of a complex number.
2795/// \param Info - Information about the ongoing evaluation.
2796/// \param LVal - The lvalue to be updated.
2797/// \param EltTy - The complex number's component type.
2798/// \param Imag - False for the real component, true for the imaginary.
2799static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2800 LValue &LVal, QualType EltTy,
2801 bool Imag) {
2802 if (Imag) {
2803 CharUnits SizeOfComponent;
2804 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2805 return false;
2806 LVal.Offset += SizeOfComponent;
2807 }
2808 LVal.addComplex(Info, E, EltTy, Imag);
2809 return true;
2810}
2811
Richard Smith27908702011-10-24 17:54:18 +00002812/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002813///
2814/// \param Info Information about the ongoing evaluation.
2815/// \param E An expression to be used when printing diagnostics.
2816/// \param VD The variable whose initializer should be obtained.
2817/// \param Frame The frame in which the variable was created. Must be null
2818/// if this variable is not local to the evaluation.
2819/// \param Result Filled in with a pointer to the value of the variable.
2820static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2821 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002822 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002823
Richard Smith254a73d2011-10-28 22:34:42 +00002824 // If this is a parameter to an active constexpr function call, perform
2825 // argument substitution.
2826 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002827 // Assume arguments of a potential constant expression are unknown
2828 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002829 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002830 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002831 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002832 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002833 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002834 }
Richard Smith3229b742013-05-05 21:17:10 +00002835 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002836 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002837 }
Richard Smith27908702011-10-24 17:54:18 +00002838
Richard Smithd9f663b2013-04-22 15:31:51 +00002839 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002840 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002841 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2842 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002843 if (!Result) {
2844 // Assume variables referenced within a lambda's call operator that were
2845 // not declared within the call operator are captures and during checking
2846 // of a potential constant expression, assume they are unknown constant
2847 // expressions.
2848 assert(isLambdaCallOperator(Frame->Callee) &&
2849 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2850 "missing value for local variable");
2851 if (Info.checkingPotentialConstantExpression())
2852 return false;
2853 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002854 Info.FFDiag(E->getBeginLoc(),
2855 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002856 << "captures not currently allowed";
2857 return false;
2858 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002859 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002860 }
2861
Richard Smithd0b4dd62011-12-19 06:19:21 +00002862 // Dig out the initializer, and use the declaration which it's attached to.
2863 const Expr *Init = VD->getAnyInitializer(VD);
2864 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002865 // If we're checking a potential constant expression, the variable could be
2866 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002867 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002868 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002869 return false;
2870 }
2871
Richard Smithd62306a2011-11-10 06:34:14 +00002872 // If we're currently evaluating the initializer of this declaration, use that
2873 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002874 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002875 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002876 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002877 }
2878
Richard Smithcecf1842011-11-01 21:06:14 +00002879 // Never evaluate the initializer of a weak variable. We can't be sure that
2880 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002881 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002882 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002883 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002884 }
Richard Smithcecf1842011-11-01 21:06:14 +00002885
Richard Smithd0b4dd62011-12-19 06:19:21 +00002886 // Check that we can fold the initializer. In C++, we will have already done
2887 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002888 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002889 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002890 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002891 Notes.size() + 1) << VD;
2892 Info.Note(VD->getLocation(), diag::note_declared_at);
2893 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002894 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002895 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002896 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002897 Notes.size() + 1) << VD;
2898 Info.Note(VD->getLocation(), diag::note_declared_at);
2899 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002900 }
Richard Smith27908702011-10-24 17:54:18 +00002901
Richard Smith3229b742013-05-05 21:17:10 +00002902 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002903 return true;
Richard Smith27908702011-10-24 17:54:18 +00002904}
2905
Richard Smith11562c52011-10-28 17:51:58 +00002906static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002907 Qualifiers Quals = T.getQualifiers();
2908 return Quals.hasConst() && !Quals.hasVolatile();
2909}
2910
Richard Smithe97cbd72011-11-11 04:05:33 +00002911/// Get the base index of the given base class within an APValue representing
2912/// the given derived class.
2913static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2914 const CXXRecordDecl *Base) {
2915 Base = Base->getCanonicalDecl();
2916 unsigned Index = 0;
2917 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2918 E = Derived->bases_end(); I != E; ++I, ++Index) {
2919 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2920 return Index;
2921 }
2922
2923 llvm_unreachable("base class missing from derived class's bases list");
2924}
2925
Richard Smith3da88fa2013-04-26 14:36:30 +00002926/// Extract the value of a character from a string literal.
2927static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2928 uint64_t Index) {
Eric Fiselier708afb52019-05-16 21:04:15 +00002929 assert(!isa<SourceLocExpr>(Lit) &&
2930 "SourceLocExpr should have already been converted to a StringLiteral");
2931
Akira Hatanakabc332642017-01-31 02:31:39 +00002932 // FIXME: Support MakeStringConstant
2933 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2934 std::string Str;
2935 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2936 assert(Index <= Str.size() && "Index too large");
2937 return APSInt::getUnsigned(Str.c_str()[Index]);
2938 }
2939
Alexey Bataevec474782014-10-09 08:45:04 +00002940 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2941 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002942 const StringLiteral *S = cast<StringLiteral>(Lit);
2943 const ConstantArrayType *CAT =
2944 Info.Ctx.getAsConstantArrayType(S->getType());
2945 assert(CAT && "string literal isn't an array");
2946 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002947 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002948
2949 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002950 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002951 if (Index < S->getLength())
2952 Value = S->getCodeUnit(Index);
2953 return Value;
2954}
2955
Richard Smith3da88fa2013-04-26 14:36:30 +00002956// Expand a string literal into an array of characters.
Eli Friedman3bf72d72019-02-08 21:18:46 +00002957//
2958// FIXME: This is inefficient; we should probably introduce something similar
2959// to the LLVM ConstantDataArray to make this cheaper.
2960static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
Richard Smithda1b4342019-09-27 01:26:47 +00002961 APValue &Result,
2962 QualType AllocType = QualType()) {
2963 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
2964 AllocType.isNull() ? S->getType() : AllocType);
Richard Smith3da88fa2013-04-26 14:36:30 +00002965 assert(CAT && "string literal isn't an array");
2966 QualType CharType = CAT->getElementType();
2967 assert(CharType->isIntegerType() && "unexpected character type");
2968
2969 unsigned Elts = CAT->getSize().getZExtValue();
2970 Result = APValue(APValue::UninitArray(),
2971 std::min(S->getLength(), Elts), Elts);
2972 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2973 CharType->isUnsignedIntegerType());
2974 if (Result.hasArrayFiller())
2975 Result.getArrayFiller() = APValue(Value);
2976 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2977 Value = S->getCodeUnit(I);
2978 Result.getArrayInitializedElt(I) = APValue(Value);
2979 }
2980}
2981
2982// Expand an array so that it has more than Index filled elements.
2983static void expandArray(APValue &Array, unsigned Index) {
2984 unsigned Size = Array.getArraySize();
2985 assert(Index < Size);
2986
2987 // Always at least double the number of elements for which we store a value.
2988 unsigned OldElts = Array.getArrayInitializedElts();
2989 unsigned NewElts = std::max(Index+1, OldElts * 2);
2990 NewElts = std::min(Size, std::max(NewElts, 8u));
2991
2992 // Copy the data across.
2993 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2994 for (unsigned I = 0; I != OldElts; ++I)
2995 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2996 for (unsigned I = OldElts; I != NewElts; ++I)
2997 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2998 if (NewValue.hasArrayFiller())
2999 NewValue.getArrayFiller() = Array.getArrayFiller();
3000 Array.swap(NewValue);
3001}
3002
Richard Smithb01fe402014-09-16 01:24:02 +00003003/// Determine whether a type would actually be read by an lvalue-to-rvalue
3004/// conversion. If it's of class type, we may assume that the copy operation
3005/// is trivial. Note that this is never true for a union type with fields
3006/// (because the copy always "reads" the active member) and always true for
3007/// a non-class type.
3008static bool isReadByLvalueToRvalueConversion(QualType T) {
3009 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3010 if (!RD || (RD->isUnion() && !RD->field_empty()))
3011 return true;
3012 if (RD->isEmpty())
3013 return false;
3014
3015 for (auto *Field : RD->fields())
3016 if (isReadByLvalueToRvalueConversion(Field->getType()))
3017 return true;
3018
3019 for (auto &BaseSpec : RD->bases())
3020 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3021 return true;
3022
3023 return false;
3024}
3025
3026/// Diagnose an attempt to read from any unreadable field within the specified
3027/// type, which might be a class type.
Richard Smith2b4fa532019-09-29 05:08:46 +00003028static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3029 QualType T) {
Richard Smithb01fe402014-09-16 01:24:02 +00003030 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3031 if (!RD)
3032 return false;
3033
3034 if (!RD->hasMutableFields())
3035 return false;
3036
3037 for (auto *Field : RD->fields()) {
3038 // If we're actually going to read this field in some way, then it can't
3039 // be mutable. If we're in a union, then assigning to a mutable field
3040 // (even an empty one) can change the active member, so that's not OK.
3041 // FIXME: Add core issue number for the union case.
3042 if (Field->isMutable() &&
3043 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Richard Smith2b4fa532019-09-29 05:08:46 +00003044 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00003045 Info.Note(Field->getLocation(), diag::note_declared_at);
3046 return true;
3047 }
3048
Richard Smith2b4fa532019-09-29 05:08:46 +00003049 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
Richard Smithb01fe402014-09-16 01:24:02 +00003050 return true;
3051 }
3052
3053 for (auto &BaseSpec : RD->bases())
Richard Smith2b4fa532019-09-29 05:08:46 +00003054 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
Richard Smithb01fe402014-09-16 01:24:02 +00003055 return true;
3056
3057 // All mutable fields were empty, and thus not actually read.
3058 return false;
3059}
3060
Richard Smithdebad642019-05-12 09:39:08 +00003061static bool lifetimeStartedInEvaluation(EvalInfo &Info,
Richard Smith2b4fa532019-09-29 05:08:46 +00003062 APValue::LValueBase Base,
3063 bool MutableSubobject = false) {
Richard Smithdebad642019-05-12 09:39:08 +00003064 // A temporary we created.
3065 if (Base.getCallIndex())
3066 return true;
3067
3068 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3069 if (!Evaluating)
3070 return false;
3071
Richard Smith2b4fa532019-09-29 05:08:46 +00003072 auto *BaseD = Base.dyn_cast<const ValueDecl*>();
Richard Smithdebad642019-05-12 09:39:08 +00003073
Richard Smith2b4fa532019-09-29 05:08:46 +00003074 switch (Info.IsEvaluatingDecl) {
3075 case EvalInfo::EvaluatingDeclKind::None:
3076 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003077
Richard Smith2b4fa532019-09-29 05:08:46 +00003078 case EvalInfo::EvaluatingDeclKind::Ctor:
3079 // The variable whose initializer we're evaluating.
3080 if (BaseD)
3081 return declaresSameEntity(Evaluating, BaseD);
3082
3083 // A temporary lifetime-extended by the variable whose initializer we're
3084 // evaluating.
3085 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3086 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3087 return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3088 return false;
3089
3090 case EvalInfo::EvaluatingDeclKind::Dtor:
3091 // C++2a [expr.const]p6:
3092 // [during constant destruction] the lifetime of a and its non-mutable
3093 // subobjects (but not its mutable subobjects) [are] considered to start
3094 // within e.
3095 //
3096 // FIXME: We can meaningfully extend this to cover non-const objects, but
3097 // we will need special handling: we should be able to access only
3098 // subobjects of such objects that are themselves declared const.
3099 if (!BaseD ||
3100 !(BaseD->getType().isConstQualified() ||
3101 BaseD->getType()->isReferenceType()) ||
3102 MutableSubobject)
3103 return false;
3104 return declaresSameEntity(Evaluating, BaseD);
3105 }
3106
3107 llvm_unreachable("unknown evaluating decl kind");
Richard Smithdebad642019-05-12 09:39:08 +00003108}
3109
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003110namespace {
Richard Smith3229b742013-05-05 21:17:10 +00003111/// A handle to a complete object (an object that is not a subobject of
3112/// another object).
3113struct CompleteObject {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003114 /// The identity of the object.
3115 APValue::LValueBase Base;
Richard Smith3229b742013-05-05 21:17:10 +00003116 /// The value of the complete object.
3117 APValue *Value;
3118 /// The type of the complete object.
3119 QualType Type;
3120
Craig Topper36250ad2014-05-12 05:36:57 +00003121 CompleteObject() : Value(nullptr) {}
Richard Smithdebad642019-05-12 09:39:08 +00003122 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3123 : Base(Base), Value(Value), Type(Type) {}
3124
Richard Smith2b4fa532019-09-29 05:08:46 +00003125 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
Richard Smithdebad642019-05-12 09:39:08 +00003126 // In C++14 onwards, it is permitted to read a mutable member whose
3127 // lifetime began within the evaluation.
3128 // FIXME: Should we also allow this in C++11?
3129 if (!Info.getLangOpts().CPlusPlus14)
3130 return false;
Richard Smith2b4fa532019-09-29 05:08:46 +00003131 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
Richard Smith3229b742013-05-05 21:17:10 +00003132 }
3133
Richard Smithdebad642019-05-12 09:39:08 +00003134 explicit operator bool() const { return !Type.isNull(); }
Richard Smith3229b742013-05-05 21:17:10 +00003135};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00003136} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00003137
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003138static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3139 bool IsMutable = false) {
3140 // C++ [basic.type.qualifier]p1:
3141 // - A const object is an object of type const T or a non-mutable subobject
3142 // of a const object.
3143 if (ObjType.isConstQualified() && !IsMutable)
3144 SubobjType.addConst();
3145 // - A volatile object is an object of type const T or a subobject of a
3146 // volatile object.
3147 if (ObjType.isVolatileQualified())
3148 SubobjType.addVolatile();
3149 return SubobjType;
3150}
3151
Richard Smith3da88fa2013-04-26 14:36:30 +00003152/// Find the designated sub-object of an rvalue.
3153template<typename SubobjectHandler>
3154typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00003155findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003156 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003157 if (Sub.Invalid)
3158 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00003159 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00003160 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003161 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00003162 Info.FFDiag(E, Sub.isOnePastTheEnd()
3163 ? diag::note_constexpr_access_past_end
3164 : diag::note_constexpr_access_unsized_array)
3165 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00003166 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003167 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003168 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00003169 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003170
Richard Smith3229b742013-05-05 21:17:10 +00003171 APValue *O = Obj.Value;
3172 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00003173 const FieldDecl *LastField = nullptr;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003174 const FieldDecl *VolatileField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00003175
Richard Smithd62306a2011-11-10 06:34:14 +00003176 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003177 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
Richard Smith31c69a32019-05-21 23:15:20 +00003178 // Reading an indeterminate value is undefined, but assigning over one is OK.
Richard Smithe381f332019-10-10 22:31:17 +00003179 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
Richard Smithb5426022019-10-03 00:39:35 +00003180 (O->isIndeterminate() && handler.AccessKind != AK_Construct &&
3181 handler.AccessKind != AK_Assign &&
Richard Smithc667cdc2019-09-18 17:37:44 +00003182 handler.AccessKind != AK_ReadObjectRepresentation)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003183 if (!Info.checkingPotentialConstantExpression())
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003184 Info.FFDiag(E, diag::note_constexpr_access_uninit)
Richard Smithe637cbe2019-05-21 23:15:18 +00003185 << handler.AccessKind << O->isIndeterminate();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003186 return handler.failed();
3187 }
3188
Richard Smith457226e2019-09-23 03:48:44 +00003189 // C++ [class.ctor]p5, C++ [class.dtor]p5:
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003190 // const and volatile semantics are not applied on an object under
Richard Smith457226e2019-09-23 03:48:44 +00003191 // {con,de}struction.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003192 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3193 ObjType->isRecordType() &&
Richard Smith457226e2019-09-23 03:48:44 +00003194 Info.isEvaluatingCtorDtor(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003195 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3196 Sub.Entries.begin() + I)) !=
3197 ConstructionPhase::None) {
3198 ObjType = Info.Ctx.getCanonicalType(ObjType);
3199 ObjType.removeLocalConst();
3200 ObjType.removeLocalVolatile();
3201 }
3202
3203 // If this is our last pass, check that the final object type is OK.
3204 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3205 // Accesses to volatile objects are prohibited.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003206 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003207 if (Info.getLangOpts().CPlusPlus) {
3208 int DiagKind;
3209 SourceLocation Loc;
3210 const NamedDecl *Decl = nullptr;
3211 if (VolatileField) {
3212 DiagKind = 2;
3213 Loc = VolatileField->getLocation();
3214 Decl = VolatileField;
3215 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3216 DiagKind = 1;
3217 Loc = VD->getLocation();
3218 Decl = VD;
3219 } else {
3220 DiagKind = 0;
3221 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3222 Loc = E->getExprLoc();
3223 }
3224 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3225 << handler.AccessKind << DiagKind << Decl;
3226 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3227 } else {
3228 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3229 }
3230 return handler.failed();
3231 }
3232
Richard Smithb01fe402014-09-16 01:24:02 +00003233 // If we are reading an object of class type, there may still be more
3234 // things we need to check: if there are any mutable subobjects, we
3235 // cannot perform this read. (This only happens when performing a trivial
3236 // copy or assignment.)
Richard Smith2b4fa532019-09-29 05:08:46 +00003237 if (ObjType->isRecordType() &&
3238 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3239 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00003240 return handler.failed();
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003241 }
Richard Smithb01fe402014-09-16 01:24:02 +00003242
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003243 if (I == N) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00003244 if (!handler.found(*O, ObjType))
3245 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003246
Richard Smith49ca8aa2013-08-06 07:09:20 +00003247 // If we modified a bit-field, truncate it to the right width.
Richard Smithdebad642019-05-12 09:39:08 +00003248 if (isModification(handler.AccessKind) &&
Richard Smith49ca8aa2013-08-06 07:09:20 +00003249 LastField && LastField->isBitField() &&
3250 !truncateBitfieldValue(Info, E, *O, LastField))
3251 return false;
3252
3253 return true;
3254 }
3255
Craig Topper36250ad2014-05-12 05:36:57 +00003256 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00003257 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00003258 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00003259 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003260 assert(CAT && "vla in literal type?");
Richard Smith5b5e27a2019-05-10 20:05:31 +00003261 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003262 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00003263 // Note, it should not be possible to form a pointer with a valid
3264 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00003265 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003266 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003267 << handler.AccessKind;
3268 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003269 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003270 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003271 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003272
3273 ObjType = CAT->getElementType();
3274
Richard Smith3da88fa2013-04-26 14:36:30 +00003275 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00003276 O = &O->getArrayInitializedElt(Index);
Richard Smithc667cdc2019-09-18 17:37:44 +00003277 else if (!isRead(handler.AccessKind)) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003278 expandArray(*O, Index);
3279 O = &O->getArrayInitializedElt(Index);
3280 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00003281 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00003282 } else if (ObjType->isAnyComplexType()) {
3283 // Next subobject is a complex number.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003284 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smith66c96992012-02-18 22:04:06 +00003285 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003286 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003287 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003288 << handler.AccessKind;
3289 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003290 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003291 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00003292 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003293
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003294 ObjType = getSubobjectType(
3295 ObjType, ObjType->castAs<ComplexType>()->getElementType());
Richard Smith3da88fa2013-04-26 14:36:30 +00003296
Richard Smith66c96992012-02-18 22:04:06 +00003297 assert(I == N - 1 && "extracting subobject of scalar?");
3298 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003299 return handler.found(Index ? O->getComplexIntImag()
3300 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003301 } else {
3302 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00003303 return handler.found(Index ? O->getComplexFloatImag()
3304 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003305 }
Richard Smithd62306a2011-11-10 06:34:14 +00003306 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith2b4fa532019-09-29 05:08:46 +00003307 if (Field->isMutable() &&
3308 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3309 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3310 << handler.AccessKind << Field;
Richard Smith5a294e62012-02-09 03:29:58 +00003311 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00003312 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00003313 }
3314
Richard Smithd62306a2011-11-10 06:34:14 +00003315 // Next subobject is a class, struct or union field.
3316 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3317 if (RD->isUnion()) {
3318 const FieldDecl *UnionField = O->getUnionField();
3319 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00003320 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithb5426022019-10-03 00:39:35 +00003321 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3322 // Placement new onto an inactive union member makes it active.
3323 O->setUnion(Field, APValue());
3324 } else {
3325 // FIXME: If O->getUnionValue() is absent, report that there's no
3326 // active union member rather than reporting the prior active union
3327 // member. We'll need to fix nullptr_t to not use APValue() as its
3328 // representation first.
3329 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3330 << handler.AccessKind << Field << !UnionField << UnionField;
3331 return handler.failed();
3332 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00003333 }
Richard Smithd62306a2011-11-10 06:34:14 +00003334 O = &O->getUnionValue();
3335 } else
3336 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00003337
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003338 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
Richard Smith49ca8aa2013-08-06 07:09:20 +00003339 LastField = Field;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003340 if (Field->getType().isVolatileQualified())
3341 VolatileField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00003342 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00003343 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00003344 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3345 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3346 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00003347
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003348 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
Richard Smithf3e9e432011-11-07 09:22:26 +00003349 }
3350 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003351}
3352
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003353namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003354struct ExtractSubobjectHandler {
3355 EvalInfo &Info;
Richard Smithc667cdc2019-09-18 17:37:44 +00003356 const Expr *E;
Richard Smith3229b742013-05-05 21:17:10 +00003357 APValue &Result;
Richard Smithc667cdc2019-09-18 17:37:44 +00003358 const AccessKinds AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00003359
3360 typedef bool result_type;
3361 bool failed() { return false; }
3362 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003363 Result = Subobj;
Richard Smithc667cdc2019-09-18 17:37:44 +00003364 if (AccessKind == AK_ReadObjectRepresentation)
3365 return true;
3366 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
Richard Smith3da88fa2013-04-26 14:36:30 +00003367 }
3368 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003369 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003370 return true;
3371 }
3372 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003373 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003374 return true;
3375 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003376};
Richard Smith3229b742013-05-05 21:17:10 +00003377} // end anonymous namespace
3378
Richard Smith3da88fa2013-04-26 14:36:30 +00003379/// Extract the designated sub-object of an rvalue.
3380static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003381 const CompleteObject &Obj,
Richard Smithc667cdc2019-09-18 17:37:44 +00003382 const SubobjectDesignator &Sub, APValue &Result,
3383 AccessKinds AK = AK_Read) {
3384 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3385 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
Richard Smith3229b742013-05-05 21:17:10 +00003386 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003387}
3388
Richard Smith3229b742013-05-05 21:17:10 +00003389namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003390struct ModifySubobjectHandler {
3391 EvalInfo &Info;
3392 APValue &NewVal;
3393 const Expr *E;
3394
3395 typedef bool result_type;
3396 static const AccessKinds AccessKind = AK_Assign;
3397
3398 bool checkConst(QualType QT) {
3399 // Assigning to a const object has undefined behavior.
3400 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003401 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003402 return false;
3403 }
3404 return true;
3405 }
3406
3407 bool failed() { return false; }
3408 bool found(APValue &Subobj, QualType SubobjType) {
3409 if (!checkConst(SubobjType))
3410 return false;
3411 // We've been given ownership of NewVal, so just swap it in.
3412 Subobj.swap(NewVal);
3413 return true;
3414 }
3415 bool found(APSInt &Value, QualType SubobjType) {
3416 if (!checkConst(SubobjType))
3417 return false;
3418 if (!NewVal.isInt()) {
3419 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003420 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003421 return false;
3422 }
3423 Value = NewVal.getInt();
3424 return true;
3425 }
3426 bool found(APFloat &Value, QualType SubobjType) {
3427 if (!checkConst(SubobjType))
3428 return false;
3429 Value = NewVal.getFloat();
3430 return true;
3431 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003432};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003433} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003434
Richard Smith3229b742013-05-05 21:17:10 +00003435const AccessKinds ModifySubobjectHandler::AccessKind;
3436
Richard Smith3da88fa2013-04-26 14:36:30 +00003437/// Update the designated sub-object of an rvalue to the given value.
3438static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003439 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003440 const SubobjectDesignator &Sub,
3441 APValue &NewVal) {
3442 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003443 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003444}
3445
Richard Smith84f6dcf2012-02-02 01:16:57 +00003446/// Find the position where two subobject designators diverge, or equivalently
3447/// the length of the common initial subsequence.
3448static unsigned FindDesignatorMismatch(QualType ObjType,
3449 const SubobjectDesignator &A,
3450 const SubobjectDesignator &B,
3451 bool &WasArrayIndex) {
3452 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3453 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003454 if (!ObjType.isNull() &&
3455 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003456 // Next subobject is an array element.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003457 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003458 WasArrayIndex = true;
3459 return I;
3460 }
Richard Smith66c96992012-02-18 22:04:06 +00003461 if (ObjType->isAnyComplexType())
3462 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3463 else
3464 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003465 } else {
Richard Smith5b5e27a2019-05-10 20:05:31 +00003466 if (A.Entries[I].getAsBaseOrMember() !=
3467 B.Entries[I].getAsBaseOrMember()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003468 WasArrayIndex = false;
3469 return I;
3470 }
3471 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3472 // Next subobject is a field.
3473 ObjType = FD->getType();
3474 else
3475 // Next subobject is a base class.
3476 ObjType = QualType();
3477 }
3478 }
3479 WasArrayIndex = false;
3480 return I;
3481}
3482
3483/// Determine whether the given subobject designators refer to elements of the
3484/// same array object.
3485static bool AreElementsOfSameArray(QualType ObjType,
3486 const SubobjectDesignator &A,
3487 const SubobjectDesignator &B) {
3488 if (A.Entries.size() != B.Entries.size())
3489 return false;
3490
George Burgess IVa51c4072015-10-16 01:49:01 +00003491 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003492 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3493 // A is a subobject of the array element.
3494 return false;
3495
3496 // If A (and B) designates an array element, the last entry will be the array
3497 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3498 // of length 1' case, and the entire path must match.
3499 bool WasArrayIndex;
3500 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3501 return CommonLength >= A.Entries.size() - IsArray;
3502}
3503
Richard Smith3229b742013-05-05 21:17:10 +00003504/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003505static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3506 AccessKinds AK, const LValue &LVal,
3507 QualType LValType) {
Richard Smith51ce8442019-05-17 08:01:34 +00003508 if (LVal.InvalidBase) {
3509 Info.FFDiag(E);
3510 return CompleteObject();
3511 }
3512
Richard Smith3229b742013-05-05 21:17:10 +00003513 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003514 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003515 return CompleteObject();
3516 }
3517
Craig Topper36250ad2014-05-12 05:36:57 +00003518 CallStackFrame *Frame = nullptr;
Richard Smith37be3362019-05-04 04:00:45 +00003519 unsigned Depth = 0;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003520 if (LVal.getLValueCallIndex()) {
Richard Smith37be3362019-05-04 04:00:45 +00003521 std::tie(Frame, Depth) =
3522 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003523 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003524 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003525 << AK << LVal.Base.is<const ValueDecl*>();
3526 NoteLValueLocation(Info, LVal.Base);
3527 return CompleteObject();
3528 }
Richard Smith3229b742013-05-05 21:17:10 +00003529 }
3530
Richard Smith61422f92019-09-27 20:24:36 +00003531 bool IsAccess = isAnyAccess(AK);
Richard Smith7bd54ab2019-05-15 20:22:21 +00003532
Richard Smith3229b742013-05-05 21:17:10 +00003533 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3534 // is not a constant expression (even if the object is non-volatile). We also
3535 // apply this rule to C++98, in order to conform to the expected 'volatile'
3536 // semantics.
Richard Smith61422f92019-09-27 20:24:36 +00003537 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003538 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003539 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003540 << AK << LValType;
3541 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003542 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003543 return CompleteObject();
3544 }
3545
3546 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003547 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003548 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00003549
3550 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3551 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3552 // In C++11, constexpr, non-volatile variables initialized with constant
3553 // expressions are constant expressions too. Inside constexpr functions,
3554 // parameters are constant expressions even if they're non-const.
3555 // In C++1y, objects local to a constant expression (those with a Frame) are
3556 // both readable and writable inside constant expressions.
3557 // In C, such things can also be folded, although they are not ICEs.
3558 const VarDecl *VD = dyn_cast<VarDecl>(D);
3559 if (VD) {
3560 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3561 VD = VDef;
3562 }
3563 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003564 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003565 return CompleteObject();
3566 }
3567
Richard Smith3229b742013-05-05 21:17:10 +00003568 // Unless we're looking at a local variable or argument in a constexpr call,
3569 // the variable we're reading must be const.
3570 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003571 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith2b4fa532019-09-29 05:08:46 +00003572 lifetimeStartedInEvaluation(Info, LVal.Base)) {
Richard Smith7525ff62013-05-09 07:14:00 +00003573 // OK, we can read and modify an object if we're in the process of
3574 // evaluating its initializer, because its lifetime began in this
3575 // evaluation.
Richard Smithdebad642019-05-12 09:39:08 +00003576 } else if (isModification(AK)) {
3577 // All the remaining cases do not permit modification of the object.
Faisal Valie690b7a2016-07-02 22:34:24 +00003578 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003579 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003580 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003581 // OK, we can read this variable.
3582 } else if (BaseType->isIntegralOrEnumerationType()) {
Richard Smithdebad642019-05-12 09:39:08 +00003583 // In OpenCL if a variable is in constant address space it is a const
3584 // value.
Xiuli Pan244e3f62016-06-07 04:34:00 +00003585 if (!(BaseType.isConstQualified() ||
3586 (Info.getLangOpts().OpenCL &&
3587 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003588 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003589 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003590 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003591 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003592 Info.Note(VD->getLocation(), diag::note_declared_at);
3593 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003594 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003595 }
3596 return CompleteObject();
3597 }
Richard Smith7bd54ab2019-05-15 20:22:21 +00003598 } else if (!IsAccess) {
Richard Smithdebad642019-05-12 09:39:08 +00003599 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003600 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3601 // We support folding of const floating-point types, in order to make
3602 // static const data members of such types (supported as an extension)
3603 // more useful.
3604 if (Info.getLangOpts().CPlusPlus11) {
3605 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3606 Info.Note(VD->getLocation(), diag::note_declared_at);
3607 } else {
3608 Info.CCEDiag(E);
3609 }
George Burgess IVb5316982016-12-27 05:33:20 +00003610 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3611 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3612 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003613 } else {
3614 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003615 if (Info.checkingPotentialConstantExpression() &&
3616 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3617 // The definition of this variable could be constexpr. We can't
3618 // access it right now, but may be able to in future.
3619 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003620 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003621 Info.Note(VD->getLocation(), diag::note_declared_at);
3622 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003623 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003624 }
3625 return CompleteObject();
3626 }
3627 }
3628
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003629 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003630 return CompleteObject();
Richard Smithda1b4342019-09-27 01:26:47 +00003631 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
Richard Smith19ad5232019-10-03 00:39:33 +00003632 Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
Richard Smithda1b4342019-09-27 01:26:47 +00003633 if (!Alloc) {
3634 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3635 return CompleteObject();
3636 }
3637 return CompleteObject(LVal.Base, &(*Alloc)->Value,
3638 LVal.Base.getDynamicAllocType());
Richard Smith3229b742013-05-05 21:17:10 +00003639 } else {
3640 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3641
3642 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003643 if (const MaterializeTemporaryExpr *MTE =
Richard Smithee0ce3022019-05-17 07:06:46 +00003644 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
Richard Smithe6c01442013-06-05 00:46:14 +00003645 assert(MTE->getStorageDuration() == SD_Static &&
3646 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003647
Richard Smithe6c01442013-06-05 00:46:14 +00003648 // Per C++1y [expr.const]p2:
3649 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3650 // - a [...] glvalue of integral or enumeration type that refers to
3651 // a non-volatile const object [...]
3652 // [...]
3653 // - a [...] glvalue of literal type that refers to a non-volatile
3654 // object whose lifetime began within the evaluation of e.
3655 //
3656 // C++11 misses the 'began within the evaluation of e' check and
3657 // instead allows all temporaries, including things like:
3658 // int &&r = 1;
3659 // int x = ++r;
3660 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003661 // Therefore we use the C++14 rules in C++11 too.
Richard Smith2b4fa532019-09-29 05:08:46 +00003662 //
3663 // Note that temporaries whose lifetimes began while evaluating a
3664 // variable's constructor are not usable while evaluating the
3665 // corresponding destructor, not even if they're of const-qualified
3666 // types.
Richard Smithe6c01442013-06-05 00:46:14 +00003667 if (!(BaseType.isConstQualified() &&
3668 BaseType->isIntegralOrEnumerationType()) &&
Richard Smith2b4fa532019-09-29 05:08:46 +00003669 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003670 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003671 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Faisal Valie690b7a2016-07-02 22:34:24 +00003672 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003673 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3674 return CompleteObject();
3675 }
3676
Tykerb0561b32019-11-17 11:41:55 +01003677 BaseVal = MTE->getOrCreateValue(false);
Richard Smithe6c01442013-06-05 00:46:14 +00003678 assert(BaseVal && "got reference to unevaluated temporary");
3679 } else {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003680 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003681 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smithee0ce3022019-05-17 07:06:46 +00003682 APValue Val;
3683 LVal.moveInto(Val);
3684 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3685 << AK
3686 << Val.getAsString(Info.Ctx,
3687 Info.Ctx.getLValueReferenceType(LValType));
3688 NoteLValueLocation(Info, LVal.Base);
Richard Smithe6c01442013-06-05 00:46:14 +00003689 return CompleteObject();
3690 }
3691 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003692 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003693 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003694 }
Richard Smith7525ff62013-05-09 07:14:00 +00003695 }
3696
Richard Smith9defb7d2018-02-21 03:38:30 +00003697 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003698 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003699 //
3700 // FIXME: Not all local state is mutable. Allow local constant subobjects
3701 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003702 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3703 Info.EvalStatus.HasSideEffects) ||
Richard Smithdebad642019-05-12 09:39:08 +00003704 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
Richard Smith3229b742013-05-05 21:17:10 +00003705 return CompleteObject();
3706
Richard Smithdebad642019-05-12 09:39:08 +00003707 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003708}
3709
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003710/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003711/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3712/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003713///
3714/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003715/// \param Conv - The expression for which we are performing the conversion.
3716/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003717/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3718/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003719/// \param LVal - The glvalue on which we are attempting to perform this action.
3720/// \param RVal - The produced value will be placed here.
Richard Smithc667cdc2019-09-18 17:37:44 +00003721/// \param WantObjectRepresentation - If true, we're looking for the object
3722/// representation rather than the value, and in particular,
3723/// there is no requirement that the result be fully initialized.
3724static bool
3725handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3726 const LValue &LVal, APValue &RVal,
3727 bool WantObjectRepresentation = false) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003728 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003729 return false;
3730
Richard Smith3229b742013-05-05 21:17:10 +00003731 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003732 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Eric Fiselier708afb52019-05-16 21:04:15 +00003733
Richard Smithc667cdc2019-09-18 17:37:44 +00003734 AccessKinds AK =
3735 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3736
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003737 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003738 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3739 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3740 // initializer until now for such expressions. Such an expression can't be
3741 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003742 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003743 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003744 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003745 }
Richard Smith3229b742013-05-05 21:17:10 +00003746 APValue Lit;
3747 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3748 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003749 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
Richard Smithc667cdc2019-09-18 17:37:44 +00003750 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
Alexey Bataevec474782014-10-09 08:45:04 +00003751 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00003752 // Special-case character extraction so we don't have to construct an
3753 // APValue for the whole string.
Eli Friedman041adb02019-02-09 02:22:17 +00003754 assert(LVal.Designator.Entries.size() <= 1 &&
Eli Friedman3bf72d72019-02-08 21:18:46 +00003755 "Can only read characters from string literals");
Eli Friedman041adb02019-02-09 02:22:17 +00003756 if (LVal.Designator.Entries.empty()) {
3757 // Fail for now for LValue to RValue conversion of an array.
3758 // (This shouldn't show up in C/C++, but it could be triggered by a
3759 // weird EvaluateAsRValue call from a tool.)
3760 Info.FFDiag(Conv);
3761 return false;
3762 }
Eli Friedman3bf72d72019-02-08 21:18:46 +00003763 if (LVal.Designator.isOnePastTheEnd()) {
3764 if (Info.getLangOpts().CPlusPlus11)
Richard Smithc667cdc2019-09-18 17:37:44 +00003765 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
Eli Friedman3bf72d72019-02-08 21:18:46 +00003766 else
3767 Info.FFDiag(Conv);
3768 return false;
3769 }
Richard Smith5b5e27a2019-05-10 20:05:31 +00003770 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
Eli Friedman3bf72d72019-02-08 21:18:46 +00003771 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3772 return true;
Richard Smith96e0c102011-11-04 02:25:55 +00003773 }
Richard Smith11562c52011-10-28 17:51:58 +00003774 }
3775
Richard Smithc667cdc2019-09-18 17:37:44 +00003776 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
3777 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
Richard Smith3da88fa2013-04-26 14:36:30 +00003778}
3779
3780/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003781static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003782 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003783 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003784 return false;
3785
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003786 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003787 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003788 return false;
3789 }
3790
Richard Smith3229b742013-05-05 21:17:10 +00003791 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003792 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3793}
3794
3795namespace {
3796struct CompoundAssignSubobjectHandler {
3797 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003798 const Expr *E;
3799 QualType PromotedLHSType;
3800 BinaryOperatorKind Opcode;
3801 const APValue &RHS;
3802
3803 static const AccessKinds AccessKind = AK_Assign;
3804
3805 typedef bool result_type;
3806
3807 bool checkConst(QualType QT) {
3808 // Assigning to a const object has undefined behavior.
3809 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003810 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003811 return false;
3812 }
3813 return true;
3814 }
3815
3816 bool failed() { return false; }
3817 bool found(APValue &Subobj, QualType SubobjType) {
3818 switch (Subobj.getKind()) {
3819 case APValue::Int:
3820 return found(Subobj.getInt(), SubobjType);
3821 case APValue::Float:
3822 return found(Subobj.getFloat(), SubobjType);
3823 case APValue::ComplexInt:
3824 case APValue::ComplexFloat:
3825 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003826 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003827 return false;
3828 case APValue::LValue:
3829 return foundPointer(Subobj, SubobjType);
3830 default:
3831 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003832 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003833 return false;
3834 }
3835 }
3836 bool found(APSInt &Value, QualType SubobjType) {
3837 if (!checkConst(SubobjType))
3838 return false;
3839
Tan S. B.9f935e82018-12-18 07:38:06 +00003840 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003841 // We don't support compound assignment on integer-cast-to-pointer
3842 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003843 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003844 return false;
3845 }
3846
Tan S. B.9f935e82018-12-18 07:38:06 +00003847 if (RHS.isInt()) {
3848 APSInt LHS =
3849 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3850 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3851 return false;
3852 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3853 return true;
3854 } else if (RHS.isFloat()) {
3855 APFloat FValue(0.0);
3856 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3857 FValue) &&
3858 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3859 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3860 Value);
3861 }
3862
3863 Info.FFDiag(E);
3864 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003865 }
3866 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003867 return checkConst(SubobjType) &&
3868 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3869 Value) &&
3870 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3871 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003872 }
3873 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3874 if (!checkConst(SubobjType))
3875 return false;
3876
3877 QualType PointeeType;
3878 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3879 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003880
3881 if (PointeeType.isNull() || !RHS.isInt() ||
3882 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003883 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003884 return false;
3885 }
3886
Richard Smithd6cc1982017-01-31 02:23:02 +00003887 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003888 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003889 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003890
3891 LValue LVal;
3892 LVal.setFrom(Info.Ctx, Subobj);
3893 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3894 return false;
3895 LVal.moveInto(Subobj);
3896 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003897 }
Richard Smith43e77732013-05-07 04:50:00 +00003898};
3899} // end anonymous namespace
3900
3901const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3902
3903/// Perform a compound assignment of LVal <op>= RVal.
3904static bool handleCompoundAssignment(
3905 EvalInfo &Info, const Expr *E,
3906 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3907 BinaryOperatorKind Opcode, const APValue &RVal) {
3908 if (LVal.Designator.Invalid)
3909 return false;
3910
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003911 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003912 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003913 return false;
3914 }
3915
3916 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3917 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3918 RVal };
3919 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3920}
3921
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003922namespace {
3923struct IncDecSubobjectHandler {
3924 EvalInfo &Info;
3925 const UnaryOperator *E;
3926 AccessKinds AccessKind;
3927 APValue *Old;
3928
Richard Smith243ef902013-05-05 23:31:59 +00003929 typedef bool result_type;
3930
3931 bool checkConst(QualType QT) {
3932 // Assigning to a const object has undefined behavior.
3933 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003934 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003935 return false;
3936 }
3937 return true;
3938 }
3939
3940 bool failed() { return false; }
3941 bool found(APValue &Subobj, QualType SubobjType) {
3942 // Stash the old value. Also clear Old, so we don't clobber it later
3943 // if we're post-incrementing a complex.
3944 if (Old) {
3945 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003946 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003947 }
3948
3949 switch (Subobj.getKind()) {
3950 case APValue::Int:
3951 return found(Subobj.getInt(), SubobjType);
3952 case APValue::Float:
3953 return found(Subobj.getFloat(), SubobjType);
3954 case APValue::ComplexInt:
3955 return found(Subobj.getComplexIntReal(),
3956 SubobjType->castAs<ComplexType>()->getElementType()
3957 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3958 case APValue::ComplexFloat:
3959 return found(Subobj.getComplexFloatReal(),
3960 SubobjType->castAs<ComplexType>()->getElementType()
3961 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3962 case APValue::LValue:
3963 return foundPointer(Subobj, SubobjType);
3964 default:
3965 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003966 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003967 return false;
3968 }
3969 }
3970 bool found(APSInt &Value, QualType SubobjType) {
3971 if (!checkConst(SubobjType))
3972 return false;
3973
3974 if (!SubobjType->isIntegerType()) {
3975 // We don't support increment / decrement on integer-cast-to-pointer
3976 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003977 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003978 return false;
3979 }
3980
3981 if (Old) *Old = APValue(Value);
3982
3983 // bool arithmetic promotes to int, and the conversion back to bool
3984 // doesn't reduce mod 2^n, so special-case it.
3985 if (SubobjType->isBooleanType()) {
3986 if (AccessKind == AK_Increment)
3987 Value = 1;
3988 else
3989 Value = !Value;
3990 return true;
3991 }
3992
3993 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003994 if (AccessKind == AK_Increment) {
3995 ++Value;
3996
3997 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3998 APSInt ActualValue(Value, /*IsUnsigned*/true);
3999 return HandleOverflow(Info, E, ActualValue, SubobjType);
4000 }
4001 } else {
4002 --Value;
4003
4004 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4005 unsigned BitWidth = Value.getBitWidth();
4006 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4007 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00004008 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00004009 }
4010 }
4011 return true;
4012 }
4013 bool found(APFloat &Value, QualType SubobjType) {
4014 if (!checkConst(SubobjType))
4015 return false;
4016
4017 if (Old) *Old = APValue(Value);
4018
4019 APFloat One(Value.getSemantics(), 1);
4020 if (AccessKind == AK_Increment)
4021 Value.add(One, APFloat::rmNearestTiesToEven);
4022 else
4023 Value.subtract(One, APFloat::rmNearestTiesToEven);
4024 return true;
4025 }
4026 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4027 if (!checkConst(SubobjType))
4028 return false;
4029
4030 QualType PointeeType;
4031 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4032 PointeeType = PT->getPointeeType();
4033 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004034 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00004035 return false;
4036 }
4037
4038 LValue LVal;
4039 LVal.setFrom(Info.Ctx, Subobj);
4040 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4041 AccessKind == AK_Increment ? 1 : -1))
4042 return false;
4043 LVal.moveInto(Subobj);
4044 return true;
4045 }
Richard Smith243ef902013-05-05 23:31:59 +00004046};
4047} // end anonymous namespace
4048
4049/// Perform an increment or decrement on LVal.
4050static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4051 QualType LValType, bool IsIncrement, APValue *Old) {
4052 if (LVal.Designator.Invalid)
4053 return false;
4054
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004055 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004056 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00004057 return false;
4058 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00004059
4060 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4061 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4062 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4063 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4064}
4065
Richard Smithe97cbd72011-11-11 04:05:33 +00004066/// Build an lvalue for the object argument of a member function call.
4067static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4068 LValue &This) {
Richard Smith5e18f4d2019-10-02 01:13:57 +00004069 if (Object->getType()->isPointerType() && Object->isRValue())
Richard Smithe97cbd72011-11-11 04:05:33 +00004070 return EvaluatePointer(Object, This, Info);
4071
4072 if (Object->isGLValue())
4073 return EvaluateLValue(Object, This, Info);
4074
Richard Smithd9f663b2013-04-22 15:31:51 +00004075 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00004076 return EvaluateTemporary(Object, This, Info);
4077
Faisal Valie690b7a2016-07-02 22:34:24 +00004078 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004079 return false;
4080}
4081
4082/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4083/// lvalue referring to the result.
4084///
4085/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00004086/// \param LV - An lvalue referring to the base of the member pointer.
4087/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00004088/// \param IncludeMember - Specifies whether the member itself is included in
4089/// the resulting LValue subobject designator. This is not possible when
4090/// creating a bound member function.
4091/// \return The field or method declaration to which the member pointer refers,
4092/// or 0 if evaluation fails.
4093static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00004094 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00004095 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00004096 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00004097 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00004098 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00004099 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00004100 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004101
4102 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4103 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00004104 if (!MemPtr.getDecl()) {
4105 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00004106 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00004107 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004108 }
Richard Smith253c2a32012-01-27 01:14:48 +00004109
Richard Smith027bf112011-11-17 22:56:20 +00004110 if (MemPtr.isDerivedMember()) {
4111 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00004112 // The end of the derived-to-base path for the base object must match the
4113 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00004114 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00004115 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004116 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00004117 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004118 }
Richard Smith027bf112011-11-17 22:56:20 +00004119 unsigned PathLengthToMember =
4120 LV.Designator.Entries.size() - MemPtr.Path.size();
4121 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4122 const CXXRecordDecl *LVDecl = getAsBaseClass(
4123 LV.Designator.Entries[PathLengthToMember + I]);
4124 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00004125 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004126 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00004127 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004128 }
Richard Smith027bf112011-11-17 22:56:20 +00004129 }
4130
4131 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00004132 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00004133 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00004134 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004135 } else if (!MemPtr.Path.empty()) {
4136 // Extend the LValue path with the member pointer's path.
4137 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4138 MemPtr.Path.size() + IncludeMember);
4139
4140 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00004141 if (const PointerType *PT = LVType->getAs<PointerType>())
4142 LVType = PT->getPointeeType();
4143 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4144 assert(RD && "member pointer access on non-class-type expression");
4145 // The first class in the path is that of the lvalue.
4146 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4147 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00004148 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00004149 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004150 RD = Base;
4151 }
4152 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00004153 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4154 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00004155 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004156 }
4157
4158 // Add the member. Note that we cannot build bound member functions here.
4159 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00004160 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00004161 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00004162 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00004163 } else if (const IndirectFieldDecl *IFD =
4164 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00004165 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00004166 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00004167 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004168 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00004169 }
Richard Smith027bf112011-11-17 22:56:20 +00004170 }
4171
4172 return MemPtr.getDecl();
4173}
4174
Richard Smith84401042013-06-03 05:03:02 +00004175static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4176 const BinaryOperator *BO,
4177 LValue &LV,
4178 bool IncludeMember = true) {
4179 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4180
4181 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00004182 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00004183 MemberPtr MemPtr;
4184 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4185 }
Craig Topper36250ad2014-05-12 05:36:57 +00004186 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00004187 }
4188
4189 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4190 BO->getRHS(), IncludeMember);
4191}
4192
Richard Smith027bf112011-11-17 22:56:20 +00004193/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4194/// the provided lvalue, which currently refers to the base object.
4195static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4196 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00004197 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00004198 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00004199 return false;
4200
Richard Smitha8105bc2012-01-06 16:39:00 +00004201 QualType TargetQT = E->getType();
4202 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4203 TargetQT = PT->getPointeeType();
4204
4205 // Check this cast lands within the final derived-to-base subobject path.
4206 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004207 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004208 << D.MostDerivedType << TargetQT;
4209 return false;
4210 }
4211
Richard Smith027bf112011-11-17 22:56:20 +00004212 // Check the type of the final cast. We don't need to check the path,
4213 // since a cast can only be formed if the path is unique.
4214 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00004215 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4216 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00004217 if (NewEntriesSize == D.MostDerivedPathLength)
4218 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4219 else
Richard Smith027bf112011-11-17 22:56:20 +00004220 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00004221 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004222 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004223 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00004224 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004225 }
Richard Smith027bf112011-11-17 22:56:20 +00004226
4227 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00004228 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00004229}
4230
Richard Smithc667cdc2019-09-18 17:37:44 +00004231/// Get the value to use for a default-initialized object of type T.
4232static APValue getDefaultInitValue(QualType T) {
4233 if (auto *RD = T->getAsCXXRecordDecl()) {
4234 if (RD->isUnion())
4235 return APValue((const FieldDecl*)nullptr);
4236
4237 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4238 std::distance(RD->field_begin(), RD->field_end()));
4239
4240 unsigned Index = 0;
4241 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4242 End = RD->bases_end(); I != End; ++I, ++Index)
4243 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4244
4245 for (const auto *I : RD->fields()) {
4246 if (I->isUnnamedBitfield())
4247 continue;
4248 Struct.getStructField(I->getFieldIndex()) =
4249 getDefaultInitValue(I->getType());
4250 }
4251 return Struct;
4252 }
4253
4254 if (auto *AT =
4255 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4256 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4257 if (Array.hasArrayFiller())
4258 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4259 return Array;
4260 }
4261
4262 return APValue::IndeterminateValue();
4263}
4264
Mike Stump876387b2009-10-27 22:09:17 +00004265namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00004266enum EvalStmtResult {
4267 /// Evaluation failed.
4268 ESR_Failed,
4269 /// Hit a 'return' statement.
4270 ESR_Returned,
4271 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00004272 ESR_Succeeded,
4273 /// Hit a 'continue' statement.
4274 ESR_Continue,
4275 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00004276 ESR_Break,
4277 /// Still scanning for 'case' or 'default' statement.
4278 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00004279};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004280}
Richard Smith254a73d2011-10-28 22:34:42 +00004281
Richard Smith97fcf4b2016-08-14 23:15:52 +00004282static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4283 // We don't need to evaluate the initializer for a static local.
4284 if (!VD->hasLocalStorage())
4285 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00004286
Richard Smith97fcf4b2016-08-14 23:15:52 +00004287 LValue Result;
Richard Smith457226e2019-09-23 03:48:44 +00004288 APValue &Val =
4289 Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
Richard Smithd9f663b2013-04-22 15:31:51 +00004290
Richard Smith97fcf4b2016-08-14 23:15:52 +00004291 const Expr *InitE = VD->getInit();
4292 if (!InitE) {
Richard Smithc667cdc2019-09-18 17:37:44 +00004293 Val = getDefaultInitValue(VD->getType());
4294 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00004295 }
Richard Smith51f03172013-06-20 03:00:05 +00004296
Richard Smith97fcf4b2016-08-14 23:15:52 +00004297 if (InitE->isValueDependent())
4298 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00004299
Richard Smith97fcf4b2016-08-14 23:15:52 +00004300 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4301 // Wipe out any partially-computed value, to allow tracking that this
4302 // evaluation failed.
4303 Val = APValue();
4304 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00004305 }
4306
4307 return true;
4308}
4309
Richard Smith97fcf4b2016-08-14 23:15:52 +00004310static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4311 bool OK = true;
4312
4313 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4314 OK &= EvaluateVarDecl(Info, VD);
4315
4316 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4317 for (auto *BD : DD->bindings())
4318 if (auto *VD = BD->getHoldingVar())
4319 OK &= EvaluateDecl(Info, VD);
4320
4321 return OK;
4322}
4323
4324
Richard Smith4e18ca52013-05-06 05:56:11 +00004325/// Evaluate a condition (either a variable declaration or an expression).
4326static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4327 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004328 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004329 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4330 return false;
Richard Smith457226e2019-09-23 03:48:44 +00004331 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4332 return false;
4333 return Scope.destroy();
Richard Smith4e18ca52013-05-06 05:56:11 +00004334}
4335
Richard Smith89210072016-04-04 23:29:43 +00004336namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004337/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00004338/// statement should be stored.
4339struct StmtResult {
4340 /// The APValue that should be filled in with the returned value.
4341 APValue &Value;
4342 /// The location containing the result, if any (used to support RVO).
4343 const LValue *Slot;
4344};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004345
4346struct TempVersionRAII {
4347 CallStackFrame &Frame;
4348
4349 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4350 Frame.pushTempVersion();
4351 }
4352
4353 ~TempVersionRAII() {
4354 Frame.popTempVersion();
4355 }
4356};
4357
Richard Smith89210072016-04-04 23:29:43 +00004358}
Richard Smith52a980a2015-08-28 02:43:42 +00004359
4360static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00004361 const Stmt *S,
4362 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00004363
4364/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00004365static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004366 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00004367 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004368 BlockScopeRAII Scope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004369
4370 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4371 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4372 ESR = ESR_Failed;
4373
4374 switch (ESR) {
Richard Smith4e18ca52013-05-06 05:56:11 +00004375 case ESR_Break:
4376 return ESR_Succeeded;
4377 case ESR_Succeeded:
4378 case ESR_Continue:
4379 return ESR_Continue;
4380 case ESR_Failed:
4381 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00004382 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00004383 return ESR;
4384 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00004385 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00004386}
4387
Richard Smith496ddcf2013-05-12 17:32:42 +00004388/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004389static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004390 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004391 BlockScopeRAII Scope(Info);
4392
Richard Smith496ddcf2013-05-12 17:32:42 +00004393 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00004394 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004395 {
Richard Smitha547eb22016-07-14 00:11:03 +00004396 if (const Stmt *Init = SS->getInit()) {
4397 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
Richard Smith457226e2019-09-23 03:48:44 +00004398 if (ESR != ESR_Succeeded) {
4399 if (ESR != ESR_Failed && !Scope.destroy())
4400 ESR = ESR_Failed;
Richard Smitha547eb22016-07-14 00:11:03 +00004401 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004402 }
Richard Smitha547eb22016-07-14 00:11:03 +00004403 }
Richard Smith457226e2019-09-23 03:48:44 +00004404
4405 FullExpressionRAII CondScope(Info);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004406 if (SS->getConditionVariable() &&
4407 !EvaluateDecl(Info, SS->getConditionVariable()))
4408 return ESR_Failed;
4409 if (!EvaluateInteger(SS->getCond(), Value, Info))
4410 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004411 if (!CondScope.destroy())
4412 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004413 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004414
4415 // Find the switch case corresponding to the value of the condition.
4416 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00004417 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004418 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4419 SC = SC->getNextSwitchCase()) {
4420 if (isa<DefaultStmt>(SC)) {
4421 Found = SC;
4422 continue;
4423 }
4424
4425 const CaseStmt *CS = cast<CaseStmt>(SC);
4426 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4427 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4428 : LHS;
4429 if (LHS <= Value && Value <= RHS) {
4430 Found = SC;
4431 break;
4432 }
4433 }
4434
4435 if (!Found)
Richard Smith61dadfc2019-10-15 22:23:11 +00004436 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004437
4438 // Search the switch body for the switch case and evaluate it from there.
Richard Smith457226e2019-09-23 03:48:44 +00004439 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4440 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4441 return ESR_Failed;
4442
4443 switch (ESR) {
Richard Smith496ddcf2013-05-12 17:32:42 +00004444 case ESR_Break:
4445 return ESR_Succeeded;
4446 case ESR_Succeeded:
4447 case ESR_Continue:
4448 case ESR_Failed:
4449 case ESR_Returned:
4450 return ESR;
4451 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004452 // This can only happen if the switch case is nested within a statement
4453 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004454 Info.FFDiag(Found->getBeginLoc(),
4455 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004456 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004457 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004458 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004459}
4460
Richard Smith254a73d2011-10-28 22:34:42 +00004461// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004462static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004463 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004464 if (!Info.nextStep(S))
4465 return ESR_Failed;
4466
Richard Smith496ddcf2013-05-12 17:32:42 +00004467 // If we're hunting down a 'case' or 'default' label, recurse through
4468 // substatements until we hit the label.
4469 if (Case) {
Richard Smith496ddcf2013-05-12 17:32:42 +00004470 switch (S->getStmtClass()) {
4471 case Stmt::CompoundStmtClass:
4472 // FIXME: Precompute which substatement of a compound statement we
4473 // would jump to, and go straight there rather than performing a
4474 // linear scan each time.
4475 case Stmt::LabelStmtClass:
4476 case Stmt::AttributedStmtClass:
4477 case Stmt::DoStmtClass:
4478 break;
4479
4480 case Stmt::CaseStmtClass:
4481 case Stmt::DefaultStmtClass:
4482 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004483 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004484 break;
4485
4486 case Stmt::IfStmtClass: {
4487 // FIXME: Precompute which side of an 'if' we would jump to, and go
4488 // straight there rather than scanning both sides.
4489 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004490
4491 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4492 // preceded by our switch label.
4493 BlockScopeRAII Scope(Info);
4494
Richard Smith397a6862019-09-20 23:08:59 +00004495 // Step into the init statement in case it brings an (uninitialized)
4496 // variable into scope.
4497 if (const Stmt *Init = IS->getInit()) {
4498 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4499 if (ESR != ESR_CaseNotFound) {
4500 assert(ESR != ESR_Succeeded);
4501 return ESR;
4502 }
4503 }
4504
4505 // Condition variable must be initialized if it exists.
4506 // FIXME: We can skip evaluating the body if there's a condition
4507 // variable, as there can't be any case labels within it.
4508 // (The same is true for 'for' statements.)
4509
Richard Smith496ddcf2013-05-12 17:32:42 +00004510 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
Richard Smith457226e2019-09-23 03:48:44 +00004511 if (ESR == ESR_Failed)
Richard Smith496ddcf2013-05-12 17:32:42 +00004512 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004513 if (ESR != ESR_CaseNotFound)
4514 return Scope.destroy() ? ESR : ESR_Failed;
4515 if (!IS->getElse())
4516 return ESR_CaseNotFound;
4517
4518 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4519 if (ESR == ESR_Failed)
4520 return ESR;
4521 if (ESR != ESR_CaseNotFound)
4522 return Scope.destroy() ? ESR : ESR_Failed;
4523 return ESR_CaseNotFound;
Richard Smith496ddcf2013-05-12 17:32:42 +00004524 }
4525
4526 case Stmt::WhileStmtClass: {
4527 EvalStmtResult ESR =
4528 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4529 if (ESR != ESR_Continue)
4530 return ESR;
4531 break;
4532 }
4533
4534 case Stmt::ForStmtClass: {
4535 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith397a6862019-09-20 23:08:59 +00004536 BlockScopeRAII Scope(Info);
4537
4538 // Step into the init statement in case it brings an (uninitialized)
4539 // variable into scope.
4540 if (const Stmt *Init = FS->getInit()) {
4541 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4542 if (ESR != ESR_CaseNotFound) {
4543 assert(ESR != ESR_Succeeded);
4544 return ESR;
4545 }
4546 }
4547
Richard Smith496ddcf2013-05-12 17:32:42 +00004548 EvalStmtResult ESR =
4549 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4550 if (ESR != ESR_Continue)
4551 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004552 if (FS->getInc()) {
4553 FullExpressionRAII IncScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004554 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004555 return ESR_Failed;
4556 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004557 break;
4558 }
4559
Richard Smithc667cdc2019-09-18 17:37:44 +00004560 case Stmt::DeclStmtClass: {
4561 // Start the lifetime of any uninitialized variables we encounter. They
4562 // might be used by the selected branch of the switch.
4563 const DeclStmt *DS = cast<DeclStmt>(S);
4564 for (const auto *D : DS->decls()) {
4565 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4566 if (VD->hasLocalStorage() && !VD->getInit())
4567 if (!EvaluateVarDecl(Info, VD))
4568 return ESR_Failed;
4569 // FIXME: If the variable has initialization that can't be jumped
4570 // over, bail out of any immediately-surrounding compound-statement
4571 // too. There can't be any case labels here.
4572 }
4573 }
4574 return ESR_CaseNotFound;
4575 }
4576
Richard Smith496ddcf2013-05-12 17:32:42 +00004577 default:
4578 return ESR_CaseNotFound;
4579 }
4580 }
4581
Richard Smith254a73d2011-10-28 22:34:42 +00004582 switch (S->getStmtClass()) {
4583 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004584 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004585 // Don't bother evaluating beyond an expression-statement which couldn't
4586 // be evaluated.
Richard Smith457226e2019-09-23 03:48:44 +00004587 // FIXME: Do we need the FullExpressionRAII object here?
4588 // VisitExprWithCleanups should create one when necessary.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004589 FullExpressionRAII Scope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004590 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
Richard Smithd9f663b2013-04-22 15:31:51 +00004591 return ESR_Failed;
4592 return ESR_Succeeded;
4593 }
4594
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004595 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004596 return ESR_Failed;
4597
4598 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004599 return ESR_Succeeded;
4600
Richard Smithd9f663b2013-04-22 15:31:51 +00004601 case Stmt::DeclStmtClass: {
4602 const DeclStmt *DS = cast<DeclStmt>(S);
Richard Smithc667cdc2019-09-18 17:37:44 +00004603 for (const auto *D : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004604 // Each declaration initialization is its own full-expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004605 FullExpressionRAII Scope(Info);
Richard Smithc667cdc2019-09-18 17:37:44 +00004606 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004607 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004608 if (!Scope.destroy())
4609 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004610 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004611 return ESR_Succeeded;
4612 }
4613
Richard Smith357362d2011-12-13 06:39:58 +00004614 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004615 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004616 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004617 if (RetExpr &&
4618 !(Result.Slot
4619 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4620 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004621 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004622 return Scope.destroy() ? ESR_Returned : ESR_Failed;
Richard Smith357362d2011-12-13 06:39:58 +00004623 }
Richard Smith254a73d2011-10-28 22:34:42 +00004624
4625 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004626 BlockScopeRAII Scope(Info);
4627
Richard Smith254a73d2011-10-28 22:34:42 +00004628 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004629 for (const auto *BI : CS->body()) {
4630 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004631 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004632 Case = nullptr;
Richard Smith457226e2019-09-23 03:48:44 +00004633 else if (ESR != ESR_CaseNotFound) {
4634 if (ESR != ESR_Failed && !Scope.destroy())
4635 return ESR_Failed;
Richard Smith254a73d2011-10-28 22:34:42 +00004636 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004637 }
Richard Smith254a73d2011-10-28 22:34:42 +00004638 }
Richard Smith457226e2019-09-23 03:48:44 +00004639 if (Case)
4640 return ESR_CaseNotFound;
4641 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith254a73d2011-10-28 22:34:42 +00004642 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004643
4644 case Stmt::IfStmtClass: {
4645 const IfStmt *IS = cast<IfStmt>(S);
4646
4647 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004648 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004649 if (const Stmt *Init = IS->getInit()) {
4650 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
Richard Smith457226e2019-09-23 03:48:44 +00004651 if (ESR != ESR_Succeeded) {
4652 if (ESR != ESR_Failed && !Scope.destroy())
4653 return ESR_Failed;
Richard Smitha547eb22016-07-14 00:11:03 +00004654 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004655 }
Richard Smitha547eb22016-07-14 00:11:03 +00004656 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004657 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004658 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004659 return ESR_Failed;
4660
4661 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4662 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
Richard Smith457226e2019-09-23 03:48:44 +00004663 if (ESR != ESR_Succeeded) {
4664 if (ESR != ESR_Failed && !Scope.destroy())
4665 return ESR_Failed;
Richard Smithd9f663b2013-04-22 15:31:51 +00004666 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004667 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004668 }
Richard Smith457226e2019-09-23 03:48:44 +00004669 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smithd9f663b2013-04-22 15:31:51 +00004670 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004671
4672 case Stmt::WhileStmtClass: {
4673 const WhileStmt *WS = cast<WhileStmt>(S);
4674 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004675 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004676 bool Continue;
4677 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4678 Continue))
4679 return ESR_Failed;
4680 if (!Continue)
4681 break;
4682
4683 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
Richard Smith457226e2019-09-23 03:48:44 +00004684 if (ESR != ESR_Continue) {
4685 if (ESR != ESR_Failed && !Scope.destroy())
4686 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004687 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004688 }
4689 if (!Scope.destroy())
4690 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004691 }
4692 return ESR_Succeeded;
4693 }
4694
4695 case Stmt::DoStmtClass: {
4696 const DoStmt *DS = cast<DoStmt>(S);
4697 bool Continue;
4698 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004699 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004700 if (ESR != ESR_Continue)
4701 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004702 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004703
Richard Smith08d6a2c2013-07-24 07:11:57 +00004704 FullExpressionRAII CondScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004705 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
4706 !CondScope.destroy())
Richard Smith4e18ca52013-05-06 05:56:11 +00004707 return ESR_Failed;
4708 } while (Continue);
4709 return ESR_Succeeded;
4710 }
4711
4712 case Stmt::ForStmtClass: {
4713 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith457226e2019-09-23 03:48:44 +00004714 BlockScopeRAII ForScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004715 if (FS->getInit()) {
4716 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
Richard Smith457226e2019-09-23 03:48:44 +00004717 if (ESR != ESR_Succeeded) {
4718 if (ESR != ESR_Failed && !ForScope.destroy())
4719 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004720 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004721 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004722 }
4723 while (true) {
Richard Smith457226e2019-09-23 03:48:44 +00004724 BlockScopeRAII IterScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004725 bool Continue = true;
4726 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4727 FS->getCond(), Continue))
4728 return ESR_Failed;
4729 if (!Continue)
4730 break;
4731
4732 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
Richard Smith457226e2019-09-23 03:48:44 +00004733 if (ESR != ESR_Continue) {
4734 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
4735 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004736 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004737 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004738
Richard Smith08d6a2c2013-07-24 07:11:57 +00004739 if (FS->getInc()) {
4740 FullExpressionRAII IncScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00004741 if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004742 return ESR_Failed;
4743 }
Richard Smith457226e2019-09-23 03:48:44 +00004744
4745 if (!IterScope.destroy())
4746 return ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004747 }
Richard Smith457226e2019-09-23 03:48:44 +00004748 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith4e18ca52013-05-06 05:56:11 +00004749 }
4750
Richard Smith896e0d72013-05-06 06:51:17 +00004751 case Stmt::CXXForRangeStmtClass: {
4752 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004753 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004754
Richard Smith8baa5002018-09-28 18:44:09 +00004755 // Evaluate the init-statement if present.
4756 if (FS->getInit()) {
4757 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
Richard Smith457226e2019-09-23 03:48:44 +00004758 if (ESR != ESR_Succeeded) {
4759 if (ESR != ESR_Failed && !Scope.destroy())
4760 return ESR_Failed;
Richard Smith8baa5002018-09-28 18:44:09 +00004761 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004762 }
Richard Smith8baa5002018-09-28 18:44:09 +00004763 }
4764
Richard Smith896e0d72013-05-06 06:51:17 +00004765 // Initialize the __range variable.
4766 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004767 if (ESR != ESR_Succeeded) {
4768 if (ESR != ESR_Failed && !Scope.destroy())
4769 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004770 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004771 }
Richard Smith896e0d72013-05-06 06:51:17 +00004772
4773 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004774 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004775 if (ESR != ESR_Succeeded) {
4776 if (ESR != ESR_Failed && !Scope.destroy())
4777 return ESR_Failed;
Richard Smith01694c32016-03-20 10:33:40 +00004778 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004779 }
Richard Smith01694c32016-03-20 10:33:40 +00004780 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004781 if (ESR != ESR_Succeeded) {
4782 if (ESR != ESR_Failed && !Scope.destroy())
4783 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004784 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004785 }
Richard Smith896e0d72013-05-06 06:51:17 +00004786
4787 while (true) {
4788 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004789 {
4790 bool Continue = true;
4791 FullExpressionRAII CondExpr(Info);
4792 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4793 return ESR_Failed;
4794 if (!Continue)
4795 break;
4796 }
Richard Smith896e0d72013-05-06 06:51:17 +00004797
4798 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004799 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004800 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
Richard Smith457226e2019-09-23 03:48:44 +00004801 if (ESR != ESR_Succeeded) {
4802 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4803 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004804 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004805 }
Richard Smith896e0d72013-05-06 06:51:17 +00004806
4807 // Loop body.
4808 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
Richard Smith457226e2019-09-23 03:48:44 +00004809 if (ESR != ESR_Continue) {
4810 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4811 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004812 return ESR;
Richard Smith457226e2019-09-23 03:48:44 +00004813 }
Richard Smith896e0d72013-05-06 06:51:17 +00004814
4815 // Increment: ++__begin
4816 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4817 return ESR_Failed;
Richard Smith457226e2019-09-23 03:48:44 +00004818
4819 if (!InnerScope.destroy())
4820 return ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004821 }
4822
Richard Smith457226e2019-09-23 03:48:44 +00004823 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
Richard Smith896e0d72013-05-06 06:51:17 +00004824 }
4825
Richard Smith496ddcf2013-05-12 17:32:42 +00004826 case Stmt::SwitchStmtClass:
4827 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4828
Richard Smith4e18ca52013-05-06 05:56:11 +00004829 case Stmt::ContinueStmtClass:
4830 return ESR_Continue;
4831
4832 case Stmt::BreakStmtClass:
4833 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004834
4835 case Stmt::LabelStmtClass:
4836 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4837
4838 case Stmt::AttributedStmtClass:
4839 // As a general principle, C++11 attributes can be ignored without
4840 // any semantic impact.
4841 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4842 Case);
4843
4844 case Stmt::CaseStmtClass:
4845 case Stmt::DefaultStmtClass:
4846 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004847 case Stmt::CXXTryStmtClass:
4848 // Evaluate try blocks by evaluating all sub statements.
4849 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004850 }
4851}
4852
Richard Smithcc36f692011-12-22 02:22:31 +00004853/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4854/// default constructor. If so, we'll fold it whether or not it's marked as
4855/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4856/// so we need special handling.
4857static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004858 const CXXConstructorDecl *CD,
4859 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004860 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4861 return false;
4862
Richard Smith66e05fe2012-01-18 05:21:49 +00004863 // Value-initialization does not call a trivial default constructor, so such a
4864 // call is a core constant expression whether or not the constructor is
4865 // constexpr.
4866 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004867 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004868 // FIXME: If DiagDecl is an implicitly-declared special member function,
4869 // we should be much more explicit about why it's not constexpr.
4870 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4871 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4872 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004873 } else {
4874 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4875 }
4876 }
4877 return true;
4878}
4879
Richard Smith357362d2011-12-13 06:39:58 +00004880/// CheckConstexprFunction - Check that a function can be called in a constant
4881/// expression.
4882static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4883 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004884 const FunctionDecl *Definition,
4885 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004886 // Potential constant expressions can contain calls to declared, but not yet
4887 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004888 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004889 Declaration->isConstexpr())
4890 return false;
4891
James Y Knightc7d3e602018-10-05 17:49:48 +00004892 // Bail out if the function declaration itself is invalid. We will
4893 // have produced a relevant diagnostic while parsing it, so just
4894 // note the problematic sub-expression.
4895 if (Declaration->isInvalidDecl()) {
4896 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004897 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004898 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004899
Richard Smithd9c6b032019-05-09 19:45:49 +00004900 // DR1872: An instantiated virtual constexpr function can't be called in a
Richard Smith921f1322019-05-13 23:35:21 +00004901 // constant expression (prior to C++20). We can still constant-fold such a
4902 // call.
4903 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4904 cast<CXXMethodDecl>(Declaration)->isVirtual())
4905 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4906
4907 if (Definition && Definition->isInvalidDecl()) {
4908 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd9c6b032019-05-09 19:45:49 +00004909 return false;
4910 }
4911
Richard Smith357362d2011-12-13 06:39:58 +00004912 // Can we evaluate this function call?
Richard Smith921f1322019-05-13 23:35:21 +00004913 if (Definition && Definition->isConstexpr() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004914 return true;
4915
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004916 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004917 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004918
Richard Smith5179eb72016-06-28 19:03:57 +00004919 // If this function is not constexpr because it is an inherited
4920 // non-constexpr constructor, diagnose that directly.
4921 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4922 if (CD && CD->isInheritingConstructor()) {
4923 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004924 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004925 DiagDecl = CD = Inherited;
4926 }
4927
4928 // FIXME: If DiagDecl is an implicitly-declared special member function
4929 // or an inheriting constructor, we should be much more explicit about why
4930 // it's not constexpr.
4931 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004932 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004933 << CD->getInheritedConstructor().getConstructor()->getParent();
4934 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004935 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004936 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004937 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4938 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004939 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004940 }
4941 return false;
4942}
4943
Richard Smithdebad642019-05-12 09:39:08 +00004944namespace {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004945struct CheckDynamicTypeHandler {
4946 AccessKinds AccessKind;
Richard Smithdebad642019-05-12 09:39:08 +00004947 typedef bool result_type;
4948 bool failed() { return false; }
4949 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4950 bool found(APSInt &Value, QualType SubobjType) { return true; }
4951 bool found(APFloat &Value, QualType SubobjType) { return true; }
4952};
4953} // end anonymous namespace
4954
Richard Smith7bd54ab2019-05-15 20:22:21 +00004955/// Check that we can access the notional vptr of an object / determine its
4956/// dynamic type.
4957static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4958 AccessKinds AK, bool Polymorphic) {
Richard Smithdab287b2019-05-13 07:51:29 +00004959 if (This.Designator.Invalid)
4960 return false;
4961
Richard Smith7bd54ab2019-05-15 20:22:21 +00004962 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
Richard Smithdebad642019-05-12 09:39:08 +00004963
4964 if (!Obj)
4965 return false;
4966
4967 if (!Obj.Value) {
4968 // The object is not usable in constant expressions, so we can't inspect
4969 // its value to see if it's in-lifetime or what the active union members
4970 // are. We can still check for a one-past-the-end lvalue.
4971 if (This.Designator.isOnePastTheEnd() ||
4972 This.Designator.isMostDerivedAnUnsizedArray()) {
4973 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4974 ? diag::note_constexpr_access_past_end
4975 : diag::note_constexpr_access_unsized_array)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004976 << AK;
Richard Smithdebad642019-05-12 09:39:08 +00004977 return false;
Richard Smith7bd54ab2019-05-15 20:22:21 +00004978 } else if (Polymorphic) {
4979 // Conservatively refuse to perform a polymorphic operation if we would
Richard Smith921f1322019-05-13 23:35:21 +00004980 // not be able to read a notional 'vptr' value.
4981 APValue Val;
4982 This.moveInto(Val);
4983 QualType StarThisType =
4984 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
Richard Smith7bd54ab2019-05-15 20:22:21 +00004985 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4986 << AK << Val.getAsString(Info.Ctx, StarThisType);
Richard Smith921f1322019-05-13 23:35:21 +00004987 return false;
Richard Smithdebad642019-05-12 09:39:08 +00004988 }
4989 return true;
4990 }
4991
Richard Smith7bd54ab2019-05-15 20:22:21 +00004992 CheckDynamicTypeHandler Handler{AK};
Richard Smithdebad642019-05-12 09:39:08 +00004993 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4994}
4995
Richard Smith7bd54ab2019-05-15 20:22:21 +00004996/// Check that the pointee of the 'this' pointer in a member function call is
4997/// either within its lifetime or in its period of construction or destruction.
Richard Smith61422f92019-09-27 20:24:36 +00004998static bool
4999checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5000 const LValue &This,
5001 const CXXMethodDecl *NamedMember) {
5002 return checkDynamicType(
5003 Info, E, This,
5004 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
Richard Smith7bd54ab2019-05-15 20:22:21 +00005005}
5006
Richard Smith921f1322019-05-13 23:35:21 +00005007struct DynamicType {
5008 /// The dynamic class type of the object.
5009 const CXXRecordDecl *Type;
5010 /// The corresponding path length in the lvalue.
5011 unsigned PathLength;
5012};
5013
5014static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5015 unsigned PathLength) {
5016 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5017 Designator.Entries.size() && "invalid path length");
5018 return (PathLength == Designator.MostDerivedPathLength)
5019 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5020 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5021}
5022
5023/// Determine the dynamic type of an object.
Richard Smith7bd54ab2019-05-15 20:22:21 +00005024static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5025 LValue &This, AccessKinds AK) {
Richard Smith921f1322019-05-13 23:35:21 +00005026 // If we don't have an lvalue denoting an object of class type, there is no
5027 // meaningful dynamic type. (We consider objects of non-class type to have no
5028 // dynamic type.)
Richard Smith7bd54ab2019-05-15 20:22:21 +00005029 if (!checkDynamicType(Info, E, This, AK, true))
Richard Smith921f1322019-05-13 23:35:21 +00005030 return None;
5031
Richard Smith7bd54ab2019-05-15 20:22:21 +00005032 // Refuse to compute a dynamic type in the presence of virtual bases. This
5033 // shouldn't happen other than in constant-folding situations, since literal
5034 // types can't have virtual bases.
5035 //
5036 // Note that consumers of DynamicType assume that the type has no virtual
5037 // bases, and will need modifications if this restriction is relaxed.
5038 const CXXRecordDecl *Class =
5039 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5040 if (!Class || Class->getNumVBases()) {
5041 Info.FFDiag(E);
5042 return None;
5043 }
5044
Richard Smith921f1322019-05-13 23:35:21 +00005045 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5046 // binary search here instead. But the overwhelmingly common case is that
5047 // we're not in the middle of a constructor, so it probably doesn't matter
5048 // in practice.
5049 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5050 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5051 PathLength <= Path.size(); ++PathLength) {
Richard Smith457226e2019-09-23 03:48:44 +00005052 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5053 Path.slice(0, PathLength))) {
Richard Smith921f1322019-05-13 23:35:21 +00005054 case ConstructionPhase::Bases:
Richard Smith457226e2019-09-23 03:48:44 +00005055 case ConstructionPhase::DestroyingBases:
5056 // We're constructing or destroying a base class. This is not the dynamic
5057 // type.
Richard Smith921f1322019-05-13 23:35:21 +00005058 break;
5059
5060 case ConstructionPhase::None:
5061 case ConstructionPhase::AfterBases:
Richard Smith457226e2019-09-23 03:48:44 +00005062 case ConstructionPhase::Destroying:
5063 // We've finished constructing the base classes and not yet started
5064 // destroying them again, so this is the dynamic type.
Richard Smith921f1322019-05-13 23:35:21 +00005065 return DynamicType{getBaseClassType(This.Designator, PathLength),
5066 PathLength};
5067 }
5068 }
5069
5070 // CWG issue 1517: we're constructing a base class of the object described by
5071 // 'This', so that object has not yet begun its period of construction and
5072 // any polymorphic operation on it results in undefined behavior.
Richard Smith7bd54ab2019-05-15 20:22:21 +00005073 Info.FFDiag(E);
Richard Smith921f1322019-05-13 23:35:21 +00005074 return None;
5075}
5076
5077/// Perform virtual dispatch.
5078static const CXXMethodDecl *HandleVirtualDispatch(
5079 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5080 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
Richard Smith61422f92019-09-27 20:24:36 +00005081 Optional<DynamicType> DynType = ComputeDynamicType(
5082 Info, E, This,
5083 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
Richard Smith7bd54ab2019-05-15 20:22:21 +00005084 if (!DynType)
Richard Smith921f1322019-05-13 23:35:21 +00005085 return nullptr;
Richard Smith921f1322019-05-13 23:35:21 +00005086
5087 // Find the final overrider. It must be declared in one of the classes on the
5088 // path from the dynamic type to the static type.
5089 // FIXME: If we ever allow literal types to have virtual base classes, that
5090 // won't be true.
5091 const CXXMethodDecl *Callee = Found;
5092 unsigned PathLength = DynType->PathLength;
5093 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5094 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
Richard Smith921f1322019-05-13 23:35:21 +00005095 const CXXMethodDecl *Overrider =
5096 Found->getCorrespondingMethodDeclaredInClass(Class, false);
5097 if (Overrider) {
5098 Callee = Overrider;
5099 break;
5100 }
5101 }
5102
5103 // C++2a [class.abstract]p6:
5104 // the effect of making a virtual call to a pure virtual function [...] is
5105 // undefined
5106 if (Callee->isPure()) {
5107 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5108 Info.Note(Callee->getLocation(), diag::note_declared_at);
5109 return nullptr;
5110 }
5111
5112 // If necessary, walk the rest of the path to determine the sequence of
5113 // covariant adjustment steps to apply.
5114 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5115 Found->getReturnType())) {
5116 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5117 for (unsigned CovariantPathLength = PathLength + 1;
5118 CovariantPathLength != This.Designator.Entries.size();
5119 ++CovariantPathLength) {
5120 const CXXRecordDecl *NextClass =
5121 getBaseClassType(This.Designator, CovariantPathLength);
5122 const CXXMethodDecl *Next =
5123 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5124 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5125 Next->getReturnType(), CovariantAdjustmentPath.back()))
5126 CovariantAdjustmentPath.push_back(Next->getReturnType());
5127 }
5128 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5129 CovariantAdjustmentPath.back()))
5130 CovariantAdjustmentPath.push_back(Found->getReturnType());
5131 }
5132
5133 // Perform 'this' adjustment.
5134 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5135 return nullptr;
5136
5137 return Callee;
5138}
5139
5140/// Perform the adjustment from a value returned by a virtual function to
5141/// a value of the statically expected type, which may be a pointer or
5142/// reference to a base class of the returned type.
5143static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5144 APValue &Result,
5145 ArrayRef<QualType> Path) {
5146 assert(Result.isLValue() &&
5147 "unexpected kind of APValue for covariant return");
5148 if (Result.isNullPointer())
5149 return true;
5150
5151 LValue LVal;
5152 LVal.setFrom(Info.Ctx, Result);
5153
5154 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5155 for (unsigned I = 1; I != Path.size(); ++I) {
5156 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5157 assert(OldClass && NewClass && "unexpected kind of covariant return");
5158 if (OldClass != NewClass &&
5159 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5160 return false;
5161 OldClass = NewClass;
5162 }
5163
5164 LVal.moveInto(Result);
5165 return true;
5166}
5167
Richard Smith7bd54ab2019-05-15 20:22:21 +00005168/// Determine whether \p Base, which is known to be a direct base class of
5169/// \p Derived, is a public base class.
5170static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5171 const CXXRecordDecl *Base) {
5172 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5173 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5174 if (BaseClass && declaresSameEntity(BaseClass, Base))
5175 return BaseSpec.getAccessSpecifier() == AS_public;
5176 }
5177 llvm_unreachable("Base is not a direct base of Derived");
5178}
5179
5180/// Apply the given dynamic cast operation on the provided lvalue.
5181///
5182/// This implements the hard case of dynamic_cast, requiring a "runtime check"
5183/// to find a suitable target subobject.
5184static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5185 LValue &Ptr) {
5186 // We can't do anything with a non-symbolic pointer value.
5187 SubobjectDesignator &D = Ptr.Designator;
5188 if (D.Invalid)
5189 return false;
5190
5191 // C++ [expr.dynamic.cast]p6:
5192 // If v is a null pointer value, the result is a null pointer value.
5193 if (Ptr.isNullPointer() && !E->isGLValue())
5194 return true;
5195
5196 // For all the other cases, we need the pointer to point to an object within
5197 // its lifetime / period of construction / destruction, and we need to know
5198 // its dynamic type.
5199 Optional<DynamicType> DynType =
5200 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5201 if (!DynType)
5202 return false;
5203
5204 // C++ [expr.dynamic.cast]p7:
5205 // If T is "pointer to cv void", then the result is a pointer to the most
5206 // derived object
5207 if (E->getType()->isVoidPointerType())
5208 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5209
5210 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5211 assert(C && "dynamic_cast target is not void pointer nor class");
5212 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5213
5214 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5215 // C++ [expr.dynamic.cast]p9:
5216 if (!E->isGLValue()) {
5217 // The value of a failed cast to pointer type is the null pointer value
5218 // of the required result type.
Richard Smith19ad5232019-10-03 00:39:33 +00005219 Ptr.setNull(Info.Ctx, E->getType());
Richard Smith7bd54ab2019-05-15 20:22:21 +00005220 return true;
5221 }
5222
5223 // A failed cast to reference type throws [...] std::bad_cast.
5224 unsigned DiagKind;
5225 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5226 DynType->Type->isDerivedFrom(C)))
5227 DiagKind = 0;
5228 else if (!Paths || Paths->begin() == Paths->end())
5229 DiagKind = 1;
5230 else if (Paths->isAmbiguous(CQT))
5231 DiagKind = 2;
5232 else {
5233 assert(Paths->front().Access != AS_public && "why did the cast fail?");
5234 DiagKind = 3;
5235 }
5236 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5237 << DiagKind << Ptr.Designator.getType(Info.Ctx)
5238 << Info.Ctx.getRecordType(DynType->Type)
5239 << E->getType().getUnqualifiedType();
5240 return false;
5241 };
5242
5243 // Runtime check, phase 1:
5244 // Walk from the base subobject towards the derived object looking for the
5245 // target type.
5246 for (int PathLength = Ptr.Designator.Entries.size();
5247 PathLength >= (int)DynType->PathLength; --PathLength) {
5248 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5249 if (declaresSameEntity(Class, C))
5250 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5251 // We can only walk across public inheritance edges.
5252 if (PathLength > (int)DynType->PathLength &&
5253 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5254 Class))
5255 return RuntimeCheckFailed(nullptr);
5256 }
5257
5258 // Runtime check, phase 2:
5259 // Search the dynamic type for an unambiguous public base of type C.
5260 CXXBasePaths Paths(/*FindAmbiguities=*/true,
5261 /*RecordPaths=*/true, /*DetectVirtual=*/false);
5262 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5263 Paths.front().Access == AS_public) {
5264 // Downcast to the dynamic type...
5265 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5266 return false;
5267 // ... then upcast to the chosen base class subobject.
5268 for (CXXBasePathElement &Elem : Paths.front())
5269 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5270 return false;
5271 return true;
5272 }
5273
5274 // Otherwise, the runtime check fails.
5275 return RuntimeCheckFailed(&Paths);
5276}
5277
Richard Smith31c69a32019-05-21 23:15:20 +00005278namespace {
5279struct StartLifetimeOfUnionMemberHandler {
5280 const FieldDecl *Field;
5281
5282 static const AccessKinds AccessKind = AK_Assign;
5283
Richard Smith31c69a32019-05-21 23:15:20 +00005284 typedef bool result_type;
5285 bool failed() { return false; }
5286 bool found(APValue &Subobj, QualType SubobjType) {
5287 // We are supposed to perform no initialization but begin the lifetime of
5288 // the object. We interpret that as meaning to do what default
5289 // initialization of the object would do if all constructors involved were
5290 // trivial:
5291 // * All base, non-variant member, and array element subobjects' lifetimes
5292 // begin
5293 // * No variant members' lifetimes begin
5294 // * All scalar subobjects whose lifetimes begin have indeterminate values
5295 assert(SubobjType->isUnionType());
Richard Smith61422f92019-09-27 20:24:36 +00005296 if (!declaresSameEntity(Subobj.getUnionField(), Field) ||
5297 !Subobj.getUnionValue().hasValue())
Richard Smith31c69a32019-05-21 23:15:20 +00005298 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
5299 return true;
5300 }
5301 bool found(APSInt &Value, QualType SubobjType) {
5302 llvm_unreachable("wrong value kind for union object");
5303 }
5304 bool found(APFloat &Value, QualType SubobjType) {
5305 llvm_unreachable("wrong value kind for union object");
5306 }
5307};
5308} // end anonymous namespace
5309
5310const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5311
5312/// Handle a builtin simple-assignment or a call to a trivial assignment
5313/// operator whose left-hand side might involve a union member access. If it
5314/// does, implicitly start the lifetime of any accessed union elements per
5315/// C++20 [class.union]5.
5316static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5317 const LValue &LHS) {
5318 if (LHS.InvalidBase || LHS.Designator.Invalid)
5319 return false;
5320
5321 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5322 // C++ [class.union]p5:
5323 // define the set S(E) of subexpressions of E as follows:
Richard Smith31c69a32019-05-21 23:15:20 +00005324 unsigned PathLength = LHS.Designator.Entries.size();
Eric Fiselierffafdb92019-05-23 23:34:43 +00005325 for (const Expr *E = LHSExpr; E != nullptr;) {
Richard Smith31c69a32019-05-21 23:15:20 +00005326 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5327 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5328 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
Richard Smith9a84dc02019-10-01 00:07:14 +00005329 // Note that we can't implicitly start the lifetime of a reference,
5330 // so we don't need to proceed any further if we reach one.
5331 if (!FD || FD->getType()->isReferenceType())
Richard Smith31c69a32019-05-21 23:15:20 +00005332 break;
5333
Richard Smithfaee39b2019-10-27 12:26:36 -07005334 // ... and also contains A.B if B names a union member ...
5335 if (FD->getParent()->isUnion()) {
5336 // ... of a non-class, non-array type, or of a class type with a
5337 // trivial default constructor that is not deleted, or an array of
5338 // such types.
5339 auto *RD =
5340 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5341 if (!RD || RD->hasTrivialDefaultConstructor())
5342 UnionPathLengths.push_back({PathLength - 1, FD});
5343 }
Richard Smith31c69a32019-05-21 23:15:20 +00005344
5345 E = ME->getBase();
5346 --PathLength;
5347 assert(declaresSameEntity(FD,
5348 LHS.Designator.Entries[PathLength]
5349 .getAsBaseOrMember().getPointer()));
5350
5351 // -- If E is of the form A[B] and is interpreted as a built-in array
5352 // subscripting operator, S(E) is [S(the array operand, if any)].
5353 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5354 // Step over an ArrayToPointerDecay implicit cast.
5355 auto *Base = ASE->getBase()->IgnoreImplicit();
5356 if (!Base->getType()->isArrayType())
5357 break;
5358
5359 E = Base;
5360 --PathLength;
5361
5362 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5363 // Step over a derived-to-base conversion.
Eric Fiselierffafdb92019-05-23 23:34:43 +00005364 E = ICE->getSubExpr();
Richard Smith31c69a32019-05-21 23:15:20 +00005365 if (ICE->getCastKind() == CK_NoOp)
5366 continue;
5367 if (ICE->getCastKind() != CK_DerivedToBase &&
5368 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5369 break;
Richard Smitha481b012019-05-30 20:45:12 +00005370 // Walk path backwards as we walk up from the base to the derived class.
5371 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
Richard Smith31c69a32019-05-21 23:15:20 +00005372 --PathLength;
Dmitri Gribenkoa10fe832019-05-22 06:57:23 +00005373 (void)Elt;
Richard Smith31c69a32019-05-21 23:15:20 +00005374 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5375 LHS.Designator.Entries[PathLength]
5376 .getAsBaseOrMember().getPointer()));
5377 }
Richard Smith31c69a32019-05-21 23:15:20 +00005378
5379 // -- Otherwise, S(E) is empty.
5380 } else {
5381 break;
5382 }
5383 }
5384
5385 // Common case: no unions' lifetimes are started.
5386 if (UnionPathLengths.empty())
5387 return true;
5388
5389 // if modification of X [would access an inactive union member], an object
5390 // of the type of X is implicitly created
5391 CompleteObject Obj =
5392 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5393 if (!Obj)
5394 return false;
5395 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5396 llvm::reverse(UnionPathLengths)) {
5397 // Form a designator for the union object.
5398 SubobjectDesignator D = LHS.Designator;
5399 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5400
5401 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5402 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5403 return false;
5404 }
5405
5406 return true;
5407}
5408
Richard Smithbe6dd812014-11-19 21:27:17 +00005409/// Determine if a class has any fields that might need to be copied by a
5410/// trivial copy or move operation.
5411static bool hasFields(const CXXRecordDecl *RD) {
5412 if (!RD || RD->isEmpty())
5413 return false;
5414 for (auto *FD : RD->fields()) {
5415 if (FD->isUnnamedBitfield())
5416 continue;
5417 return true;
5418 }
5419 for (auto &Base : RD->bases())
5420 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5421 return true;
5422 return false;
5423}
5424
Richard Smithd62306a2011-11-10 06:34:14 +00005425namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00005426typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00005427}
5428
5429/// EvaluateArgs - Evaluate the arguments to a function call.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005430static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5431 EvalInfo &Info, const FunctionDecl *Callee) {
Richard Smith253c2a32012-01-27 01:14:48 +00005432 bool Success = true;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005433 llvm::SmallBitVector ForbiddenNullArgs;
5434 if (Callee->hasAttr<NonNullAttr>()) {
5435 ForbiddenNullArgs.resize(Args.size());
5436 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5437 if (!Attr->args_size()) {
5438 ForbiddenNullArgs.set();
5439 break;
5440 } else
5441 for (auto Idx : Attr->args()) {
5442 unsigned ASTIdx = Idx.getASTIndex();
5443 if (ASTIdx >= Args.size())
5444 continue;
5445 ForbiddenNullArgs[ASTIdx] = 1;
5446 }
5447 }
5448 }
Gauthier Harnisch59c6df92019-10-10 07:13:20 +00005449 for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
5450 if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) {
Richard Smith253c2a32012-01-27 01:14:48 +00005451 // If we're checking for a potential constant expression, evaluate all
5452 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005453 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005454 return false;
5455 Success = false;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005456 } else if (!ForbiddenNullArgs.empty() &&
Gauthier Harnisch59c6df92019-10-10 07:13:20 +00005457 ForbiddenNullArgs[Idx] &&
5458 ArgValues[Idx].isLValue() &&
5459 ArgValues[Idx].isNullPointer()) {
5460 Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005461 if (!Info.noteFailure())
5462 return false;
5463 Success = false;
Richard Smith253c2a32012-01-27 01:14:48 +00005464 }
5465 }
5466 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005467}
5468
Richard Smith254a73d2011-10-28 22:34:42 +00005469/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00005470static bool HandleFunctionCall(SourceLocation CallLoc,
5471 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005472 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00005473 EvalInfo &Info, APValue &Result,
5474 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00005475 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005476 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
Richard Smithd62306a2011-11-10 06:34:14 +00005477 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00005478
Richard Smith253c2a32012-01-27 01:14:48 +00005479 if (!Info.CheckCallLimit(CallLoc))
5480 return false;
5481
5482 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00005483
5484 // For a trivial copy or move assignment, perform an APValue copy. This is
5485 // essential for unions, where the operations performed by the assignment
5486 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00005487 //
5488 // Skip this for non-union classes with no fields; in that case, the defaulted
5489 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00005490 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00005491 if (MD && MD->isDefaulted() &&
5492 (MD->getParent()->isUnion() ||
5493 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00005494 assert(This &&
5495 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5496 LValue RHS;
5497 RHS.setFrom(Info.Ctx, ArgValues[0]);
5498 APValue RHSValue;
Richard Smithc667cdc2019-09-18 17:37:44 +00005499 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5500 RHSValue, MD->getParent()->isUnion()))
Richard Smith99005e62013-05-07 03:19:20 +00005501 return false;
Richard Smith31c69a32019-05-21 23:15:20 +00005502 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5503 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5504 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00005505 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00005506 RHSValue))
5507 return false;
5508 This->moveInto(Result);
5509 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00005510 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00005511 // We're in a lambda; determine the lambda capture field maps unless we're
5512 // just constexpr checking a lambda's call operator. constexpr checking is
5513 // done before the captures have been added to the closure object (unless
5514 // we're inferring constexpr-ness), so we don't have access to them in this
5515 // case. But since we don't need the captures to constexpr check, we can
5516 // just ignore them.
5517 if (!Info.checkingPotentialConstantExpression())
5518 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5519 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00005520 }
5521
Richard Smith52a980a2015-08-28 02:43:42 +00005522 StmtResult Ret = {Result, ResultSlot};
5523 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00005524 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00005525 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00005526 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005527 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00005528 }
Richard Smithd9f663b2013-04-22 15:31:51 +00005529 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00005530}
5531
Richard Smithd62306a2011-11-10 06:34:14 +00005532/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00005533static bool HandleConstructorCall(const Expr *E, const LValue &This,
5534 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00005535 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00005536 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00005537 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00005538 if (!Info.CheckCallLimit(CallLoc))
5539 return false;
5540
Richard Smith3607ffe2012-02-13 03:54:03 +00005541 const CXXRecordDecl *RD = Definition->getParent();
5542 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005543 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00005544 return false;
5545 }
5546
Erik Pilkington42925492017-10-04 00:18:55 +00005547 EvalInfo::EvaluatingConstructorRAII EvalObj(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005548 Info,
5549 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5550 RD->getNumBases());
Richard Smith5179eb72016-06-28 19:03:57 +00005551 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00005552
Richard Smith52a980a2015-08-28 02:43:42 +00005553 // FIXME: Creating an APValue just to hold a nonexistent return value is
5554 // wasteful.
5555 APValue RetVal;
5556 StmtResult Ret = {RetVal, nullptr};
5557
Richard Smith5179eb72016-06-28 19:03:57 +00005558 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00005559 if (Definition->isDelegatingConstructor()) {
5560 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00005561 {
5562 FullExpressionRAII InitScope(Info);
Richard Smith457226e2019-09-23 03:48:44 +00005563 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5564 !InitScope.destroy())
Richard Smith9ff62af2013-11-07 18:45:03 +00005565 return false;
5566 }
Richard Smith52a980a2015-08-28 02:43:42 +00005567 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005568 }
5569
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005570 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00005571 // essential for unions (or classes with anonymous union members), where the
5572 // operations performed by the constructor cannot be represented by
5573 // ctor-initializers.
5574 //
5575 // Skip this for empty non-union classes; we should not perform an
5576 // lvalue-to-rvalue conversion on them because their copy constructor does not
5577 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00005578 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00005579 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00005580 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005581 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00005582 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00005583 return handleLValueToRValueConversion(
5584 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
Richard Smithc667cdc2019-09-18 17:37:44 +00005585 RHS, Result, Definition->getParent()->isUnion());
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005586 }
5587
5588 // Reserve space for the struct members.
Richard Smithe637cbe2019-05-21 23:15:18 +00005589 if (!RD->isUnion() && !Result.hasValue())
Richard Smithd62306a2011-11-10 06:34:14 +00005590 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005591 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005592
John McCalld7bca762012-05-01 00:38:49 +00005593 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005594 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5595
Richard Smith08d6a2c2013-07-24 07:11:57 +00005596 // A scope for temporaries lifetime-extended by reference members.
5597 BlockScopeRAII LifetimeExtendedScope(Info);
5598
Richard Smith253c2a32012-01-27 01:14:48 +00005599 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005600 unsigned BasesSeen = 0;
5601#ifndef NDEBUG
5602 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5603#endif
Richard Smithc667cdc2019-09-18 17:37:44 +00005604 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5605 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5606 // We might be initializing the same field again if this is an indirect
5607 // field initialization.
5608 if (FieldIt == RD->field_end() ||
5609 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5610 assert(Indirect && "fields out of order?");
5611 return;
5612 }
5613
5614 // Default-initialize any fields with no explicit initializer.
5615 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5616 assert(FieldIt != RD->field_end() && "missing field?");
5617 if (!FieldIt->isUnnamedBitfield())
5618 Result.getStructField(FieldIt->getFieldIndex()) =
5619 getDefaultInitValue(FieldIt->getType());
5620 }
5621 ++FieldIt;
5622 };
Aaron Ballman0ad78302014-03-13 17:34:31 +00005623 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005624 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005625 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00005626 APValue *Value = &Result;
5627
5628 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00005629 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005630 if (I->isBaseInitializer()) {
5631 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00005632#ifndef NDEBUG
5633 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00005634 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00005635 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5636 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5637 "base class initializers not in expected order");
5638 ++BaseIt;
5639#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005640 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00005641 BaseType->getAsCXXRecordDecl(), &Layout))
5642 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005643 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00005644 } else if ((FD = I->getMember())) {
5645 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005646 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005647 if (RD->isUnion()) {
5648 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00005649 Value = &Result.getUnionValue();
5650 } else {
Richard Smithc667cdc2019-09-18 17:37:44 +00005651 SkipToField(FD, false);
Richard Smith253c2a32012-01-27 01:14:48 +00005652 Value = &Result.getStructField(FD->getFieldIndex());
5653 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00005654 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005655 // Walk the indirect field decl's chain to find the object to initialize,
5656 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005657 auto IndirectFieldChain = IFD->chain();
5658 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00005659 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005660 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5661 // Switch the union field if it differs. This happens if we had
5662 // preceding zero-initialization, and we're now initializing a union
5663 // subobject other than the first.
5664 // FIXME: In this case, the values of the other subobjects are
5665 // specified, since zero-initialization sets all padding bits to zero.
Richard Smithe637cbe2019-05-21 23:15:18 +00005666 if (!Value->hasValue() ||
Richard Smith1b78b3d2012-01-25 22:15:11 +00005667 (Value->isUnion() && Value->getUnionField() != FD)) {
5668 if (CD->isUnion())
5669 *Value = APValue(FD);
5670 else
Richard Smithc667cdc2019-09-18 17:37:44 +00005671 // FIXME: This immediately starts the lifetime of all members of an
5672 // anonymous struct. It would be preferable to strictly start member
5673 // lifetime in initialization order.
5674 *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
Richard Smith1b78b3d2012-01-25 22:15:11 +00005675 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005676 // Store Subobject as its parent before updating it for the last element
5677 // in the chain.
5678 if (C == IndirectFieldChain.back())
5679 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005680 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00005681 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005682 if (CD->isUnion())
5683 Value = &Value->getUnionValue();
Richard Smithc667cdc2019-09-18 17:37:44 +00005684 else {
5685 if (C == IndirectFieldChain.front() && !RD->isUnion())
5686 SkipToField(FD, true);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005687 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithc667cdc2019-09-18 17:37:44 +00005688 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00005689 }
Richard Smithd62306a2011-11-10 06:34:14 +00005690 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005691 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00005692 }
Richard Smith253c2a32012-01-27 01:14:48 +00005693
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005694 // Need to override This for implicit field initializers as in this case
5695 // This refers to innermost anonymous struct/union containing initializer,
5696 // not to currently constructed class.
5697 const Expr *Init = I->getInit();
5698 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5699 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00005700 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005701 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5702 (FD && FD->isBitField() &&
5703 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005704 // If we're checking for a potential constant expression, evaluate all
5705 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005706 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005707 return false;
5708 Success = false;
5709 }
Richard Smith921f1322019-05-13 23:35:21 +00005710
5711 // This is the point at which the dynamic type of the object becomes this
5712 // class type.
5713 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5714 EvalObj.finishedConstructingBases();
Richard Smithd62306a2011-11-10 06:34:14 +00005715 }
5716
Richard Smithc667cdc2019-09-18 17:37:44 +00005717 // Default-initialize any remaining fields.
5718 if (!RD->isUnion()) {
5719 for (; FieldIt != RD->field_end(); ++FieldIt) {
5720 if (!FieldIt->isUnnamedBitfield())
5721 Result.getStructField(FieldIt->getFieldIndex()) =
5722 getDefaultInitValue(FieldIt->getType());
5723 }
5724 }
5725
Richard Smithd9f663b2013-04-22 15:31:51 +00005726 return Success &&
Richard Smith457226e2019-09-23 03:48:44 +00005727 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
5728 LifetimeExtendedScope.destroy();
Richard Smithd62306a2011-11-10 06:34:14 +00005729}
5730
Richard Smith5179eb72016-06-28 19:03:57 +00005731static bool HandleConstructorCall(const Expr *E, const LValue &This,
5732 ArrayRef<const Expr*> Args,
5733 const CXXConstructorDecl *Definition,
5734 EvalInfo &Info, APValue &Result) {
5735 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005736 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
Richard Smith5179eb72016-06-28 19:03:57 +00005737 return false;
5738
5739 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5740 Info, Result);
5741}
5742
Richard Smith61422f92019-09-27 20:24:36 +00005743static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
5744 const LValue &This, APValue &Value,
5745 QualType T) {
Richard Smithda1b4342019-09-27 01:26:47 +00005746 // Objects can only be destroyed while they're within their lifetimes.
5747 // FIXME: We have no representation for whether an object of type nullptr_t
5748 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
5749 // as indeterminate instead?
5750 if (Value.isAbsent() && !T->isNullPtrType()) {
5751 APValue Printable;
5752 This.moveInto(Printable);
5753 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
5754 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
5755 return false;
5756 }
5757
Richard Smith457226e2019-09-23 03:48:44 +00005758 // Invent an expression for location purposes.
5759 // FIXME: We shouldn't need to do this.
5760 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
5761
5762 // For arrays, destroy elements right-to-left.
5763 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
5764 uint64_t Size = CAT->getSize().getZExtValue();
5765 QualType ElemT = CAT->getElementType();
5766
5767 LValue ElemLV = This;
5768 ElemLV.addArray(Info, &LocE, CAT);
5769 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
5770 return false;
5771
Richard Smithda1b4342019-09-27 01:26:47 +00005772 // Ensure that we have actual array elements available to destroy; the
5773 // destructors might mutate the value, so we can't run them on the array
5774 // filler.
5775 if (Size && Size > Value.getArrayInitializedElts())
5776 expandArray(Value, Value.getArraySize() - 1);
5777
Richard Smith457226e2019-09-23 03:48:44 +00005778 for (; Size != 0; --Size) {
5779 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
Richard Smithda1b4342019-09-27 01:26:47 +00005780 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
Richard Smith61422f92019-09-27 20:24:36 +00005781 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
Richard Smith457226e2019-09-23 03:48:44 +00005782 return false;
5783 }
5784
5785 // End the lifetime of this array now.
5786 Value = APValue();
5787 return true;
5788 }
5789
5790 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5791 if (!RD) {
5792 if (T.isDestructedType()) {
5793 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
5794 return false;
5795 }
5796
5797 Value = APValue();
5798 return true;
5799 }
5800
5801 if (RD->getNumVBases()) {
5802 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5803 return false;
5804 }
5805
5806 const CXXDestructorDecl *DD = RD->getDestructor();
Richard Smithda1b4342019-09-27 01:26:47 +00005807 if (!DD && !RD->hasTrivialDestructor()) {
Richard Smith457226e2019-09-23 03:48:44 +00005808 Info.FFDiag(CallLoc);
5809 return false;
5810 }
5811
Richard Smithda1b4342019-09-27 01:26:47 +00005812 if (!DD || DD->isTrivial() ||
Richard Smith457226e2019-09-23 03:48:44 +00005813 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
5814 // A trivial destructor just ends the lifetime of the object. Check for
5815 // this case before checking for a body, because we might not bother
5816 // building a body for a trivial destructor. Note that it doesn't matter
5817 // whether the destructor is constexpr in this case; all trivial
5818 // destructors are constexpr.
5819 //
5820 // If an anonymous union would be destroyed, some enclosing destructor must
5821 // have been explicitly defined, and the anonymous union destruction should
5822 // have no effect.
5823 Value = APValue();
5824 return true;
5825 }
5826
5827 if (!Info.CheckCallLimit(CallLoc))
5828 return false;
5829
Richard Smithda1b4342019-09-27 01:26:47 +00005830 const FunctionDecl *Definition = nullptr;
5831 const Stmt *Body = DD->getBody(Definition);
5832
Richard Smith457226e2019-09-23 03:48:44 +00005833 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
5834 return false;
5835
5836 CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
5837
5838 // We're now in the period of destruction of this object.
5839 unsigned BasesLeft = RD->getNumBases();
5840 EvalInfo::EvaluatingDestructorRAII EvalObj(
5841 Info,
5842 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
Richard Smithda1b4342019-09-27 01:26:47 +00005843 if (!EvalObj.DidInsert) {
5844 // C++2a [class.dtor]p19:
5845 // the behavior is undefined if the destructor is invoked for an object
5846 // whose lifetime has ended
5847 // (Note that formally the lifetime ends when the period of destruction
5848 // begins, even though certain uses of the object remain valid until the
5849 // period of destruction ends.)
5850 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
5851 return false;
5852 }
Richard Smith457226e2019-09-23 03:48:44 +00005853
5854 // FIXME: Creating an APValue just to hold a nonexistent return value is
5855 // wasteful.
5856 APValue RetVal;
5857 StmtResult Ret = {RetVal, nullptr};
5858 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
5859 return false;
5860
5861 // A union destructor does not implicitly destroy its members.
5862 if (RD->isUnion())
5863 return true;
5864
5865 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5866
5867 // We don't have a good way to iterate fields in reverse, so collect all the
5868 // fields first and then walk them backwards.
5869 SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
5870 for (const FieldDecl *FD : llvm::reverse(Fields)) {
5871 if (FD->isUnnamedBitfield())
5872 continue;
5873
5874 LValue Subobject = This;
5875 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
5876 return false;
5877
5878 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
Richard Smith61422f92019-09-27 20:24:36 +00005879 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5880 FD->getType()))
Richard Smith457226e2019-09-23 03:48:44 +00005881 return false;
5882 }
5883
5884 if (BasesLeft != 0)
5885 EvalObj.startedDestroyingBases();
5886
5887 // Destroy base classes in reverse order.
5888 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
5889 --BasesLeft;
5890
5891 QualType BaseType = Base.getType();
5892 LValue Subobject = This;
5893 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
5894 BaseType->getAsCXXRecordDecl(), &Layout))
5895 return false;
5896
5897 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
Richard Smith61422f92019-09-27 20:24:36 +00005898 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5899 BaseType))
Richard Smith457226e2019-09-23 03:48:44 +00005900 return false;
5901 }
5902 assert(BasesLeft == 0 && "NumBases was wrong?");
5903
5904 // The period of destruction ends now. The object is gone.
5905 Value = APValue();
5906 return true;
5907}
5908
Richard Smith61422f92019-09-27 20:24:36 +00005909namespace {
5910struct DestroyObjectHandler {
5911 EvalInfo &Info;
5912 const Expr *E;
5913 const LValue &This;
5914 const AccessKinds AccessKind;
5915
5916 typedef bool result_type;
5917 bool failed() { return false; }
5918 bool found(APValue &Subobj, QualType SubobjType) {
5919 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
5920 SubobjType);
5921 }
5922 bool found(APSInt &Value, QualType SubobjType) {
5923 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5924 return false;
5925 }
5926 bool found(APFloat &Value, QualType SubobjType) {
5927 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5928 return false;
5929 }
5930};
5931}
5932
5933/// Perform a destructor or pseudo-destructor call on the given object, which
5934/// might in general not be a complete object.
5935static bool HandleDestruction(EvalInfo &Info, const Expr *E,
5936 const LValue &This, QualType ThisType) {
5937 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
5938 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
5939 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5940}
5941
5942/// Destroy and end the lifetime of the given complete object.
5943static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
5944 APValue::LValueBase LVBase, APValue &Value,
5945 QualType T) {
Richard Smithda1b4342019-09-27 01:26:47 +00005946 // If we've had an unmodeled side-effect, we can't rely on mutable state
5947 // (such as the object we're about to destroy) being correct.
5948 if (Info.EvalStatus.HasSideEffects)
5949 return false;
Richard Smith457226e2019-09-23 03:48:44 +00005950
5951 LValue LV;
5952 LV.set({LVBase});
Richard Smith61422f92019-09-27 20:24:36 +00005953 return HandleDestructionImpl(Info, Loc, LV, Value, T);
Richard Smith457226e2019-09-23 03:48:44 +00005954}
5955
Richard Smith19ad5232019-10-03 00:39:33 +00005956/// Perform a call to 'perator new' or to `__builtin_operator_new'.
5957static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
5958 LValue &Result) {
5959 if (Info.checkingPotentialConstantExpression() ||
5960 Info.SpeculativeEvaluationDepth)
5961 return false;
5962
5963 // This is permitted only within a call to std::allocator<T>::allocate.
5964 auto Caller = Info.getStdAllocatorCaller("allocate");
5965 if (!Caller) {
5966 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus2a
5967 ? diag::note_constexpr_new_untyped
5968 : diag::note_constexpr_new);
5969 return false;
5970 }
5971
5972 QualType ElemType = Caller.ElemType;
5973 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
5974 Info.FFDiag(E->getExprLoc(),
5975 diag::note_constexpr_new_not_complete_object_type)
5976 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
5977 return false;
5978 }
5979
5980 APSInt ByteSize;
5981 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
5982 return false;
5983 bool IsNothrow = false;
5984 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
5985 EvaluateIgnoredValue(Info, E->getArg(I));
5986 IsNothrow |= E->getType()->isNothrowT();
5987 }
5988
5989 CharUnits ElemSize;
5990 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
5991 return false;
5992 APInt Size, Remainder;
5993 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
5994 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
5995 if (Remainder != 0) {
5996 // This likely indicates a bug in the implementation of 'std::allocator'.
5997 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
5998 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
5999 return false;
6000 }
6001
6002 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6003 if (IsNothrow) {
6004 Result.setNull(Info.Ctx, E->getType());
6005 return true;
6006 }
6007
6008 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6009 return false;
6010 }
6011
Richard Smith772e2662019-10-04 01:25:59 +00006012 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6013 ArrayType::Normal, 0);
Richard Smith19ad5232019-10-03 00:39:33 +00006014 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6015 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6016 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6017 return true;
6018}
6019
6020static bool hasVirtualDestructor(QualType T) {
6021 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6022 if (CXXDestructorDecl *DD = RD->getDestructor())
6023 return DD->isVirtual();
6024 return false;
6025}
6026
Richard Smithdf3761f2019-10-07 03:14:28 +00006027static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6028 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6029 if (CXXDestructorDecl *DD = RD->getDestructor())
6030 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6031 return nullptr;
6032}
6033
Richard Smith19ad5232019-10-03 00:39:33 +00006034/// Check that the given object is a suitable pointer to a heap allocation that
6035/// still exists and is of the right kind for the purpose of a deletion.
6036///
6037/// On success, returns the heap allocation to deallocate. On failure, produces
6038/// a diagnostic and returns None.
6039static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6040 const LValue &Pointer,
6041 DynAlloc::Kind DeallocKind) {
6042 auto PointerAsString = [&] {
6043 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6044 };
6045
6046 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6047 if (!DA) {
6048 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6049 << PointerAsString();
6050 if (Pointer.Base)
6051 NoteLValueLocation(Info, Pointer.Base);
6052 return None;
6053 }
6054
6055 Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6056 if (!Alloc) {
6057 Info.FFDiag(E, diag::note_constexpr_double_delete);
6058 return None;
6059 }
6060
6061 QualType AllocType = Pointer.Base.getDynamicAllocType();
6062 if (DeallocKind != (*Alloc)->getKind()) {
6063 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6064 << DeallocKind << (*Alloc)->getKind() << AllocType;
6065 NoteLValueLocation(Info, Pointer.Base);
6066 return None;
6067 }
6068
6069 bool Subobject = false;
6070 if (DeallocKind == DynAlloc::New) {
6071 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6072 Pointer.Designator.isOnePastTheEnd();
6073 } else {
6074 Subobject = Pointer.Designator.Entries.size() != 1 ||
6075 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6076 }
6077 if (Subobject) {
6078 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6079 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6080 return None;
6081 }
6082
6083 return Alloc;
6084}
6085
6086// Perform a call to 'operator delete' or '__builtin_operator_delete'.
6087bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6088 if (Info.checkingPotentialConstantExpression() ||
6089 Info.SpeculativeEvaluationDepth)
6090 return false;
6091
6092 // This is permitted only within a call to std::allocator<T>::deallocate.
6093 if (!Info.getStdAllocatorCaller("deallocate")) {
6094 Info.FFDiag(E->getExprLoc());
6095 return true;
6096 }
6097
6098 LValue Pointer;
6099 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6100 return false;
6101 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6102 EvaluateIgnoredValue(Info, E->getArg(I));
6103
6104 if (Pointer.Designator.Invalid)
6105 return false;
6106
6107 // Deleting a null pointer has no effect.
6108 if (Pointer.isNullPointer())
6109 return true;
6110
6111 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6112 return false;
6113
6114 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6115 return true;
6116}
6117
Eli Friedman9a156e52008-11-12 09:44:48 +00006118//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00006119// Generic Evaluation
6120//===----------------------------------------------------------------------===//
6121namespace {
6122
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006123class BitCastBuffer {
6124 // FIXME: We're going to need bit-level granularity when we support
6125 // bit-fields.
6126 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6127 // we don't support a host or target where that is the case. Still, we should
6128 // use a more generic type in case we ever do.
6129 SmallVector<Optional<unsigned char>, 32> Bytes;
6130
6131 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6132 "Need at least 8 bit unsigned char");
6133
6134 bool TargetIsLittleEndian;
6135
6136public:
6137 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6138 : Bytes(Width.getQuantity()),
6139 TargetIsLittleEndian(TargetIsLittleEndian) {}
6140
6141 LLVM_NODISCARD
6142 bool readObject(CharUnits Offset, CharUnits Width,
6143 SmallVectorImpl<unsigned char> &Output) const {
6144 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6145 // If a byte of an integer is uninitialized, then the whole integer is
6146 // uninitalized.
6147 if (!Bytes[I.getQuantity()])
6148 return false;
6149 Output.push_back(*Bytes[I.getQuantity()]);
6150 }
6151 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6152 std::reverse(Output.begin(), Output.end());
6153 return true;
6154 }
6155
6156 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6157 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6158 std::reverse(Input.begin(), Input.end());
6159
6160 size_t Index = 0;
6161 for (unsigned char Byte : Input) {
6162 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6163 Bytes[Offset.getQuantity() + Index] = Byte;
6164 ++Index;
6165 }
6166 }
6167
6168 size_t size() { return Bytes.size(); }
6169};
6170
6171/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6172/// target would represent the value at runtime.
6173class APValueToBufferConverter {
6174 EvalInfo &Info;
6175 BitCastBuffer Buffer;
6176 const CastExpr *BCE;
6177
6178 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6179 const CastExpr *BCE)
6180 : Info(Info),
6181 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6182 BCE(BCE) {}
6183
6184 bool visit(const APValue &Val, QualType Ty) {
6185 return visit(Val, Ty, CharUnits::fromQuantity(0));
6186 }
6187
6188 // Write out Val with type Ty into Buffer starting at Offset.
6189 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6190 assert((size_t)Offset.getQuantity() <= Buffer.size());
6191
6192 // As a special case, nullptr_t has an indeterminate value.
6193 if (Ty->isNullPtrType())
6194 return true;
6195
6196 // Dig through Src to find the byte at SrcOffset.
6197 switch (Val.getKind()) {
6198 case APValue::Indeterminate:
6199 case APValue::None:
6200 return true;
6201
6202 case APValue::Int:
6203 return visitInt(Val.getInt(), Ty, Offset);
6204 case APValue::Float:
6205 return visitFloat(Val.getFloat(), Ty, Offset);
6206 case APValue::Array:
6207 return visitArray(Val, Ty, Offset);
6208 case APValue::Struct:
6209 return visitRecord(Val, Ty, Offset);
6210
6211 case APValue::ComplexInt:
6212 case APValue::ComplexFloat:
6213 case APValue::Vector:
6214 case APValue::FixedPoint:
6215 // FIXME: We should support these.
6216
6217 case APValue::Union:
6218 case APValue::MemberPointer:
6219 case APValue::AddrLabelDiff: {
6220 Info.FFDiag(BCE->getBeginLoc(),
6221 diag::note_constexpr_bit_cast_unsupported_type)
6222 << Ty;
6223 return false;
6224 }
6225
6226 case APValue::LValue:
6227 llvm_unreachable("LValue subobject in bit_cast?");
6228 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00006229 llvm_unreachable("Unhandled APValue::ValueKind");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006230 }
6231
6232 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6233 const RecordDecl *RD = Ty->getAsRecordDecl();
6234 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6235
6236 // Visit the base classes.
6237 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6238 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6239 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6240 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6241
6242 if (!visitRecord(Val.getStructBase(I), BS.getType(),
6243 Layout.getBaseClassOffset(BaseDecl) + Offset))
6244 return false;
6245 }
6246 }
6247
6248 // Visit the fields.
6249 unsigned FieldIdx = 0;
6250 for (FieldDecl *FD : RD->fields()) {
6251 if (FD->isBitField()) {
6252 Info.FFDiag(BCE->getBeginLoc(),
6253 diag::note_constexpr_bit_cast_unsupported_bitfield);
6254 return false;
6255 }
6256
6257 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6258
6259 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6260 "only bit-fields can have sub-char alignment");
6261 CharUnits FieldOffset =
6262 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6263 QualType FieldTy = FD->getType();
6264 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6265 return false;
6266 ++FieldIdx;
6267 }
6268
6269 return true;
6270 }
6271
6272 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6273 const auto *CAT =
6274 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6275 if (!CAT)
6276 return false;
6277
6278 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6279 unsigned NumInitializedElts = Val.getArrayInitializedElts();
6280 unsigned ArraySize = Val.getArraySize();
6281 // First, initialize the initialized elements.
6282 for (unsigned I = 0; I != NumInitializedElts; ++I) {
6283 const APValue &SubObj = Val.getArrayInitializedElt(I);
6284 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6285 return false;
6286 }
6287
6288 // Next, initialize the rest of the array using the filler.
6289 if (Val.hasArrayFiller()) {
6290 const APValue &Filler = Val.getArrayFiller();
6291 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6292 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6293 return false;
6294 }
6295 }
6296
6297 return true;
6298 }
6299
6300 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6301 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
6302 SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
6303 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
6304 Buffer.writeObject(Offset, Bytes);
6305 return true;
6306 }
6307
6308 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6309 APSInt AsInt(Val.bitcastToAPInt());
6310 return visitInt(AsInt, Ty, Offset);
6311 }
6312
6313public:
6314 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6315 const CastExpr *BCE) {
6316 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6317 APValueToBufferConverter Converter(Info, DstSize, BCE);
6318 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6319 return None;
6320 return Converter.Buffer;
6321 }
6322};
6323
6324/// Write an BitCastBuffer into an APValue.
6325class BufferToAPValueConverter {
6326 EvalInfo &Info;
6327 const BitCastBuffer &Buffer;
6328 const CastExpr *BCE;
6329
6330 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6331 const CastExpr *BCE)
6332 : Info(Info), Buffer(Buffer), BCE(BCE) {}
6333
6334 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6335 // with an invalid type, so anything left is a deficiency on our part (FIXME).
6336 // Ideally this will be unreachable.
6337 llvm::NoneType unsupportedType(QualType Ty) {
6338 Info.FFDiag(BCE->getBeginLoc(),
6339 diag::note_constexpr_bit_cast_unsupported_type)
6340 << Ty;
6341 return None;
6342 }
6343
6344 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6345 const EnumType *EnumSugar = nullptr) {
6346 if (T->isNullPtrType()) {
6347 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6348 return APValue((Expr *)nullptr,
6349 /*Offset=*/CharUnits::fromQuantity(NullValue),
6350 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6351 }
6352
6353 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6354 SmallVector<uint8_t, 8> Bytes;
6355 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6356 // If this is std::byte or unsigned char, then its okay to store an
6357 // indeterminate value.
6358 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6359 bool IsUChar =
6360 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6361 T->isSpecificBuiltinType(BuiltinType::Char_U));
6362 if (!IsStdByte && !IsUChar) {
Simon Pilgrimbc7f30e82019-07-03 12:20:28 +00006363 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006364 Info.FFDiag(BCE->getExprLoc(),
6365 diag::note_constexpr_bit_cast_indet_dest)
6366 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6367 return None;
6368 }
6369
6370 return APValue::IndeterminateValue();
6371 }
6372
6373 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6374 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6375
6376 if (T->isIntegralOrEnumerationType()) {
6377 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6378 return APValue(Val);
6379 }
6380
6381 if (T->isRealFloatingType()) {
6382 const llvm::fltSemantics &Semantics =
6383 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6384 return APValue(APFloat(Semantics, Val));
6385 }
6386
6387 return unsupportedType(QualType(T, 0));
6388 }
6389
6390 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6391 const RecordDecl *RD = RTy->getAsRecordDecl();
6392 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6393
6394 unsigned NumBases = 0;
6395 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6396 NumBases = CXXRD->getNumBases();
6397
6398 APValue ResultVal(APValue::UninitStruct(), NumBases,
6399 std::distance(RD->field_begin(), RD->field_end()));
6400
6401 // Visit the base classes.
6402 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6403 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6404 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6405 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6406 if (BaseDecl->isEmpty() ||
6407 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6408 continue;
6409
6410 Optional<APValue> SubObj = visitType(
6411 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6412 if (!SubObj)
6413 return None;
6414 ResultVal.getStructBase(I) = *SubObj;
6415 }
6416 }
6417
6418 // Visit the fields.
6419 unsigned FieldIdx = 0;
6420 for (FieldDecl *FD : RD->fields()) {
6421 // FIXME: We don't currently support bit-fields. A lot of the logic for
6422 // this is in CodeGen, so we need to factor it around.
6423 if (FD->isBitField()) {
6424 Info.FFDiag(BCE->getBeginLoc(),
6425 diag::note_constexpr_bit_cast_unsupported_bitfield);
6426 return None;
6427 }
6428
6429 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6430 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6431
6432 CharUnits FieldOffset =
6433 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6434 Offset;
6435 QualType FieldTy = FD->getType();
6436 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6437 if (!SubObj)
6438 return None;
6439 ResultVal.getStructField(FieldIdx) = *SubObj;
6440 ++FieldIdx;
6441 }
6442
6443 return ResultVal;
6444 }
6445
6446 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6447 QualType RepresentationType = Ty->getDecl()->getIntegerType();
6448 assert(!RepresentationType.isNull() &&
6449 "enum forward decl should be caught by Sema");
Simon Pilgrimc15b38e2019-10-03 15:08:30 +00006450 const auto *AsBuiltin =
6451 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006452 // Recurse into the underlying type. Treat std::byte transparently as
6453 // unsigned char.
6454 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6455 }
6456
6457 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6458 size_t Size = Ty->getSize().getLimitedValue();
6459 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6460
6461 APValue ArrayValue(APValue::UninitArray(), Size, Size);
6462 for (size_t I = 0; I != Size; ++I) {
6463 Optional<APValue> ElementValue =
6464 visitType(Ty->getElementType(), Offset + I * ElementWidth);
6465 if (!ElementValue)
6466 return None;
6467 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6468 }
6469
6470 return ArrayValue;
6471 }
6472
6473 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6474 return unsupportedType(QualType(Ty, 0));
6475 }
6476
6477 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6478 QualType Can = Ty.getCanonicalType();
6479
6480 switch (Can->getTypeClass()) {
6481#define TYPE(Class, Base) \
6482 case Type::Class: \
6483 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6484#define ABSTRACT_TYPE(Class, Base)
6485#define NON_CANONICAL_TYPE(Class, Base) \
6486 case Type::Class: \
6487 llvm_unreachable("non-canonical type should be impossible!");
6488#define DEPENDENT_TYPE(Class, Base) \
6489 case Type::Class: \
6490 llvm_unreachable( \
6491 "dependent types aren't supported in the constant evaluator!");
6492#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
6493 case Type::Class: \
6494 llvm_unreachable("either dependent or not canonical!");
John McCall36b12a82019-10-02 06:35:23 +00006495#include "clang/AST/TypeNodes.inc"
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006496 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00006497 llvm_unreachable("Unhandled Type::TypeClass");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006498 }
6499
6500public:
6501 // Pull out a full value of type DstType.
6502 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6503 const CastExpr *BCE) {
6504 BufferToAPValueConverter Converter(Info, Buffer, BCE);
6505 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6506 }
6507};
6508
6509static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6510 QualType Ty, EvalInfo *Info,
6511 const ASTContext &Ctx,
6512 bool CheckingDest) {
6513 Ty = Ty.getCanonicalType();
6514
6515 auto diag = [&](int Reason) {
6516 if (Info)
6517 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6518 << CheckingDest << (Reason == 4) << Reason;
6519 return false;
6520 };
6521 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6522 if (Info)
6523 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6524 << NoteTy << Construct << Ty;
6525 return false;
6526 };
6527
6528 if (Ty->isUnionType())
6529 return diag(0);
6530 if (Ty->isPointerType())
6531 return diag(1);
6532 if (Ty->isMemberPointerType())
6533 return diag(2);
6534 if (Ty.isVolatileQualified())
6535 return diag(3);
6536
6537 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6538 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6539 for (CXXBaseSpecifier &BS : CXXRD->bases())
6540 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6541 CheckingDest))
6542 return note(1, BS.getType(), BS.getBeginLoc());
6543 }
6544 for (FieldDecl *FD : Record->fields()) {
6545 if (FD->getType()->isReferenceType())
6546 return diag(4);
6547 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6548 CheckingDest))
6549 return note(0, FD->getType(), FD->getBeginLoc());
6550 }
6551 }
6552
6553 if (Ty->isArrayType() &&
6554 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6555 Info, Ctx, CheckingDest))
6556 return false;
6557
6558 return true;
6559}
6560
6561static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6562 const ASTContext &Ctx,
6563 const CastExpr *BCE) {
6564 bool DestOK = checkBitCastConstexprEligibilityType(
6565 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6566 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6567 BCE->getBeginLoc(),
6568 BCE->getSubExpr()->getType(), Info, Ctx, false);
6569 return SourceOK;
6570}
6571
6572static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6573 APValue &SourceValue,
6574 const CastExpr *BCE) {
6575 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6576 "no host or target supports non 8-bit chars");
6577 assert(SourceValue.isLValue() &&
6578 "LValueToRValueBitcast requires an lvalue operand!");
6579
6580 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6581 return false;
6582
6583 LValue SourceLValue;
6584 APValue SourceRValue;
6585 SourceLValue.setFrom(Info.Ctx, SourceValue);
Richard Smithc667cdc2019-09-18 17:37:44 +00006586 if (!handleLValueToRValueConversion(
6587 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6588 SourceRValue, /*WantObjectRepresentation=*/true))
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006589 return false;
6590
6591 // Read out SourceValue into a char buffer.
6592 Optional<BitCastBuffer> Buffer =
6593 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6594 if (!Buffer)
6595 return false;
6596
6597 // Write out the buffer into a new APValue.
6598 Optional<APValue> MaybeDestValue =
6599 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6600 if (!MaybeDestValue)
6601 return false;
6602
6603 DestValue = std::move(*MaybeDestValue);
6604 return true;
6605}
6606
Aaron Ballman68af21c2014-01-03 19:26:43 +00006607template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00006608class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00006609 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00006610private:
Richard Smith52a980a2015-08-28 02:43:42 +00006611 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006612 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006613 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006614 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006615 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006616 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006617 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006618
Richard Smith17100ba2012-02-16 02:46:34 +00006619 // Check whether a conditional operator with a non-constant condition is a
6620 // potential constant expression. If neither arm is a potential constant
6621 // expression, then the conditional operator is not either.
6622 template<typename ConditionalOperator>
6623 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00006624 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00006625
6626 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00006627 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00006628 {
Richard Smith17100ba2012-02-16 02:46:34 +00006629 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00006630 StmtVisitorTy::Visit(E->getFalseExpr());
6631 if (Diag.empty())
6632 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00006633 }
Richard Smith17100ba2012-02-16 02:46:34 +00006634
George Burgess IV8c892b52016-05-25 22:31:54 +00006635 {
6636 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00006637 Diag.clear();
6638 StmtVisitorTy::Visit(E->getTrueExpr());
6639 if (Diag.empty())
6640 return;
6641 }
6642
6643 Error(E, diag::note_constexpr_conditional_never_const);
6644 }
6645
6646
6647 template<typename ConditionalOperator>
6648 bool HandleConditionalOperator(const ConditionalOperator *E) {
6649 bool BoolResult;
6650 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00006651 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00006652 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00006653 return false;
6654 }
6655 if (Info.noteFailure()) {
6656 StmtVisitorTy::Visit(E->getTrueExpr());
6657 StmtVisitorTy::Visit(E->getFalseExpr());
6658 }
Richard Smith17100ba2012-02-16 02:46:34 +00006659 return false;
6660 }
6661
6662 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
6663 return StmtVisitorTy::Visit(EvalExpr);
6664 }
6665
Peter Collingbournee9200682011-05-13 03:29:01 +00006666protected:
6667 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00006668 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00006669 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
6670
Richard Smith92b1ce02011-12-12 09:28:41 +00006671 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006672 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006673 }
6674
Aaron Ballman68af21c2014-01-03 19:26:43 +00006675 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006676
6677public:
6678 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
6679
6680 EvalInfo &getEvalInfo() { return Info; }
6681
Richard Smithf57d8cb2011-12-09 22:58:01 +00006682 /// Report an evaluation error. This should only be called when an error is
6683 /// first discovered. When propagating an error, just return false.
6684 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006685 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006686 return false;
6687 }
6688 bool Error(const Expr *E) {
6689 return Error(E, diag::note_invalid_subexpr_in_const_expr);
6690 }
6691
Aaron Ballman68af21c2014-01-03 19:26:43 +00006692 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00006693 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00006694 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006695 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006696 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006697 }
6698
Bill Wendling8003edc2018-11-09 00:41:36 +00006699 bool VisitConstantExpr(const ConstantExpr *E)
6700 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006701 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006702 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006703 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006704 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006705 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006706 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006707 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00006708 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006709 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00006710 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006711 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00006712 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006713 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
6714 TempVersionRAII RAII(*Info.CurrentCall);
Eric Fiselier708afb52019-05-16 21:04:15 +00006715 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006716 return StmtVisitorTy::Visit(E->getExpr());
6717 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006718 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006719 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00006720 // The initializer may not have been parsed yet, or might be erroneous.
6721 if (!E->getExpr())
6722 return Error(E);
Eric Fiselier708afb52019-05-16 21:04:15 +00006723 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Richard Smith17e32462013-09-13 20:51:45 +00006724 return StmtVisitorTy::Visit(E->getExpr());
6725 }
Eric Fiselier708afb52019-05-16 21:04:15 +00006726
Richard Smith457226e2019-09-23 03:48:44 +00006727 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
6728 FullExpressionRAII Scope(Info);
6729 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
6730 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006731
Richard Smith3b69bcc2019-10-01 00:41:16 +00006732 // Temporaries are registered when created, so we don't care about
6733 // CXXBindTemporaryExpr.
6734 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
6735 return StmtVisitorTy::Visit(E->getSubExpr());
6736 }
6737
Aaron Ballman68af21c2014-01-03 19:26:43 +00006738 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006739 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
6740 return static_cast<Derived*>(this)->VisitCastExpr(E);
6741 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006742 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00006743 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
6744 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
Richard Smith6d6ecc32011-12-12 12:46:16 +00006745 return static_cast<Derived*>(this)->VisitCastExpr(E);
6746 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006747 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
6748 return static_cast<Derived*>(this)->VisitCastExpr(E);
6749 }
Richard Smith6d6ecc32011-12-12 12:46:16 +00006750
Aaron Ballman68af21c2014-01-03 19:26:43 +00006751 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006752 switch (E->getOpcode()) {
6753 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006754 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006755
6756 case BO_Comma:
6757 VisitIgnoredValue(E->getLHS());
6758 return StmtVisitorTy::Visit(E->getRHS());
6759
6760 case BO_PtrMemD:
6761 case BO_PtrMemI: {
6762 LValue Obj;
6763 if (!HandleMemberPointerAccess(Info, E, Obj))
6764 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006765 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00006766 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00006767 return false;
6768 return DerivedSuccess(Result, E);
6769 }
6770 }
6771 }
6772
Richard Smith778dc0f2019-10-19 00:04:38 +00006773 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
6774 return StmtVisitorTy::Visit(E->getSemanticForm());
6775 }
6776
Aaron Ballman68af21c2014-01-03 19:26:43 +00006777 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00006778 // Evaluate and cache the common expression. We treat it as a temporary,
6779 // even though it's not quite the same thing.
Richard Smith457226e2019-09-23 03:48:44 +00006780 LValue CommonLV;
6781 if (!Evaluate(Info.CurrentCall->createTemporary(
Richard Smith61422f92019-09-27 20:24:36 +00006782 E->getOpaqueValue(),
6783 getStorageType(Info.Ctx, E->getOpaqueValue()), false,
6784 CommonLV),
Richard Smith26d4cc12012-06-26 08:12:11 +00006785 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006786 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00006787
Richard Smith17100ba2012-02-16 02:46:34 +00006788 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006789 }
6790
Aaron Ballman68af21c2014-01-03 19:26:43 +00006791 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006792 bool IsBcpCall = false;
6793 // If the condition (ignoring parens) is a __builtin_constant_p call,
6794 // the result is a constant expression if it can be folded without
6795 // side-effects. This is an important GNU extension. See GCC PR38377
6796 // for discussion.
6797 if (const CallExpr *CallCE =
6798 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00006799 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00006800 IsBcpCall = true;
6801
6802 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6803 // constant expression; we can't check whether it's potentially foldable.
Richard Smith045b2272019-09-10 21:24:09 +00006804 // FIXME: We should instead treat __builtin_constant_p as non-constant if
6805 // it would return 'false' in this mode.
Richard Smith6d4c6582013-11-05 22:18:15 +00006806 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00006807 return false;
6808
Richard Smith6d4c6582013-11-05 22:18:15 +00006809 FoldConstant Fold(Info, IsBcpCall);
6810 if (!HandleConditionalOperator(E)) {
6811 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00006812 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00006813 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00006814
6815 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00006816 }
6817
Aaron Ballman68af21c2014-01-03 19:26:43 +00006818 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006819 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00006820 return DerivedSuccess(*Value, E);
6821
6822 const Expr *Source = E->getSourceExpr();
6823 if (!Source)
6824 return Error(E);
6825 if (Source == E) { // sanity checking.
6826 assert(0 && "OpaqueValueExpr recursively refers to itself");
6827 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00006828 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00006829 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00006830 }
Richard Smith4ce706a2011-10-11 21:43:33 +00006831
Aaron Ballman68af21c2014-01-03 19:26:43 +00006832 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006833 APValue Result;
6834 if (!handleCallExpr(E, Result, nullptr))
6835 return false;
6836 return DerivedSuccess(Result, E);
6837 }
6838
6839 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00006840 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00006841 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00006842 QualType CalleeType = Callee->getType();
6843
Craig Topper36250ad2014-05-12 05:36:57 +00006844 const FunctionDecl *FD = nullptr;
6845 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00006846 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith921f1322019-05-13 23:35:21 +00006847 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00006848
Richard Smithe97cbd72011-11-11 04:05:33 +00006849 // Extract function decl and 'this' pointer from the callee.
6850 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smith921f1322019-05-13 23:35:21 +00006851 const CXXMethodDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00006852 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6853 // Explicit bound member calls, such as x.f() or p->g();
6854 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006855 return false;
Richard Smith921f1322019-05-13 23:35:21 +00006856 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6857 if (!Member)
6858 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006859 This = &ThisVal;
Richard Smith921f1322019-05-13 23:35:21 +00006860 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00006861 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6862 // Indirect bound member calls ('.*' or '->*').
Richard Smith52582022019-10-03 01:20:27 +00006863 const ValueDecl *D =
6864 HandleMemberPointerAccess(Info, BE, ThisVal, false);
6865 if (!D)
6866 return false;
6867 Member = dyn_cast<CXXMethodDecl>(D);
Richard Smith921f1322019-05-13 23:35:21 +00006868 if (!Member)
6869 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006870 This = &ThisVal;
Richard Smith61422f92019-09-27 20:24:36 +00006871 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
6872 if (!Info.getLangOpts().CPlusPlus2a)
6873 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
6874 // FIXME: If pseudo-destructor calls ever start ending the lifetime of
6875 // their callee, we should start calling HandleDestruction here.
6876 // For now, we just evaluate the object argument and discard it.
6877 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal);
Richard Smith027bf112011-11-17 22:56:20 +00006878 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006879 return Error(Callee);
Richard Smith921f1322019-05-13 23:35:21 +00006880 FD = Member;
Richard Smithe97cbd72011-11-11 04:05:33 +00006881 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00006882 LValue Call;
6883 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006884 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00006885
Richard Smitha8105bc2012-01-06 16:39:00 +00006886 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006887 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00006888 FD = dyn_cast_or_null<FunctionDecl>(
6889 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00006890 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006891 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00006892 // Don't call function pointers which have been cast to some other type.
6893 // Per DR (no number yet), the caller and callee can differ in noexcept.
6894 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6895 CalleeType->getPointeeType(), FD->getType())) {
6896 return Error(E);
6897 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006898
6899 // Overloaded operator calls to member functions are represented as normal
6900 // calls with '*this' as the first argument.
6901 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6902 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006903 // FIXME: When selecting an implicit conversion for an overloaded
6904 // operator delete, we sometimes try to evaluate calls to conversion
6905 // operators without a 'this' parameter!
6906 if (Args.empty())
6907 return Error(E);
6908
Nick Lewycky13073a62017-06-12 21:15:44 +00006909 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00006910 return false;
6911 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00006912 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00006913 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00006914 // Map the static invoker for the lambda back to the call operator.
6915 // Conveniently, we don't have to slice out the 'this' argument (as is
6916 // being done for the non-static case), since a static member function
6917 // doesn't have an implicit argument passed in.
6918 const CXXRecordDecl *ClosureClass = MD->getParent();
6919 assert(
6920 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6921 "Number of captures must be zero for conversion to function-ptr");
6922
6923 const CXXMethodDecl *LambdaCallOp =
6924 ClosureClass->getLambdaCallOperator();
6925
6926 // Set 'FD', the function that will be called below, to the call
6927 // operator. If the closure object represents a generic lambda, find
6928 // the corresponding specialization of the call operator.
6929
6930 if (ClosureClass->isGenericLambda()) {
6931 assert(MD->isFunctionTemplateSpecialization() &&
6932 "A generic lambda's static-invoker function must be a "
6933 "template specialization");
6934 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6935 FunctionTemplateDecl *CallOpTemplate =
6936 LambdaCallOp->getDescribedFunctionTemplate();
6937 void *InsertPos = nullptr;
6938 FunctionDecl *CorrespondingCallOpSpecialization =
6939 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6940 assert(CorrespondingCallOpSpecialization &&
6941 "We must always have a function call operator specialization "
6942 "that corresponds to our static invoker specialization");
6943 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6944 } else
6945 FD = LambdaCallOp;
Richard Smith19ad5232019-10-03 00:39:33 +00006946 } else if (FD->isReplaceableGlobalAllocationFunction()) {
6947 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
6948 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
6949 LValue Ptr;
6950 if (!HandleOperatorNewCall(Info, E, Ptr))
6951 return false;
6952 Ptr.moveInto(Result);
6953 return true;
6954 } else {
6955 return HandleOperatorDeleteCall(Info, E);
6956 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006957 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006958 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006959 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00006960
Richard Smith921f1322019-05-13 23:35:21 +00006961 SmallVector<QualType, 4> CovariantAdjustmentPath;
6962 if (This) {
6963 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006964 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
6965 // Perform virtual dispatch, if necessary.
6966 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6967 CovariantAdjustmentPath);
6968 if (!FD)
6969 return false;
6970 } else {
6971 // Check that the 'this' pointer points to an object of the right type.
Richard Smith61422f92019-09-27 20:24:36 +00006972 // FIXME: If this is an assignment operator call, we may need to change
6973 // the active union member before we check this.
6974 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
Richard Smith7bd54ab2019-05-15 20:22:21 +00006975 return false;
6976 }
Richard Smith921f1322019-05-13 23:35:21 +00006977 }
Richard Smith47b34932012-02-01 02:39:43 +00006978
Richard Smith61422f92019-09-27 20:24:36 +00006979 // Destructor calls are different enough that they have their own codepath.
6980 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
6981 assert(This && "no 'this' pointer for destructor call");
6982 return HandleDestruction(Info, E, *This,
6983 Info.Ctx.getRecordType(DD->getParent()));
6984 }
6985
Craig Topper36250ad2014-05-12 05:36:57 +00006986 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00006987 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00006988
Nick Lewycky13073a62017-06-12 21:15:44 +00006989 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
6990 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00006991 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006992 return false;
6993
Richard Smith921f1322019-05-13 23:35:21 +00006994 if (!CovariantAdjustmentPath.empty() &&
6995 !HandleCovariantReturnAdjustment(Info, E, Result,
6996 CovariantAdjustmentPath))
6997 return false;
6998
Richard Smith52a980a2015-08-28 02:43:42 +00006999 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00007000 }
7001
Aaron Ballman68af21c2014-01-03 19:26:43 +00007002 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007003 return StmtVisitorTy::Visit(E->getInitializer());
7004 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00007005 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00007006 if (E->getNumInits() == 0)
7007 return DerivedZeroInitialization(E);
7008 if (E->getNumInits() == 1)
7009 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00007010 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00007011 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00007012 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007013 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00007014 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00007015 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007016 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00007017 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00007018 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007019 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00007020 }
Richard Smith4ce706a2011-10-11 21:43:33 +00007021
Richard Smithd62306a2011-11-10 06:34:14 +00007022 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00007023 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007024 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7025 "missing temporary materialization conversion");
Richard Smithd62306a2011-11-10 06:34:14 +00007026 assert(!E->isArrow() && "missing call to bound member function?");
7027
Richard Smith2e312c82012-03-03 22:46:17 +00007028 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00007029 if (!Evaluate(Val, Info, E->getBase()))
7030 return false;
7031
7032 QualType BaseTy = E->getBase()->getType();
7033
7034 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00007035 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007036 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00007037 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00007038 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7039
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007040 // Note: there is no lvalue base here. But this case should only ever
7041 // happen in C or in C++98, where we cannot be evaluating a constexpr
7042 // constructor, which is the only case the base matters.
Richard Smithdebad642019-05-12 09:39:08 +00007043 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00007044 SubobjectDesignator Designator(BaseTy);
7045 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00007046
Richard Smith3229b742013-05-05 21:17:10 +00007047 APValue Result;
7048 return extractSubobject(Info, E, Obj, Designator, Result) &&
7049 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00007050 }
7051
Aaron Ballman68af21c2014-01-03 19:26:43 +00007052 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007053 switch (E->getCastKind()) {
7054 default:
7055 break;
7056
Richard Smitha23ab512013-05-23 00:30:41 +00007057 case CK_AtomicToNonAtomic: {
7058 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00007059 // This does not need to be done in place even for class/array types:
7060 // atomic-to-non-atomic conversion implies copying the object
7061 // representation.
7062 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00007063 return false;
7064 return DerivedSuccess(AtomicVal, E);
7065 }
7066
Richard Smith11562c52011-10-28 17:51:58 +00007067 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00007068 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00007069 return StmtVisitorTy::Visit(E->getSubExpr());
7070
7071 case CK_LValueToRValue: {
7072 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007073 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7074 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007075 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00007076 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00007077 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00007078 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007079 return false;
7080 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00007081 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00007082 case CK_LValueToRValueBitCast: {
7083 APValue DestValue, SourceValue;
7084 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7085 return false;
7086 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7087 return false;
7088 return DerivedSuccess(DestValue, E);
7089 }
Richard Smith11562c52011-10-28 17:51:58 +00007090 }
7091
Richard Smithf57d8cb2011-12-09 22:58:01 +00007092 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00007093 }
7094
Aaron Ballman68af21c2014-01-03 19:26:43 +00007095 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00007096 return VisitUnaryPostIncDec(UO);
7097 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00007098 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00007099 return VisitUnaryPostIncDec(UO);
7100 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00007101 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007102 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007103 return Error(UO);
7104
7105 LValue LVal;
7106 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7107 return false;
7108 APValue RVal;
7109 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7110 UO->isIncrementOp(), &RVal))
7111 return false;
7112 return DerivedSuccess(RVal, UO);
7113 }
7114
Aaron Ballman68af21c2014-01-03 19:26:43 +00007115 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00007116 // We will have checked the full-expressions inside the statement expression
7117 // when they were completed, and don't need to check them again now.
Richard Smith045b2272019-09-10 21:24:09 +00007118 if (Info.checkingForUndefinedBehavior())
Richard Smith51f03172013-06-20 03:00:05 +00007119 return Error(E);
7120
7121 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00007122 if (CS->body_empty())
7123 return true;
7124
Richard Smith457226e2019-09-23 03:48:44 +00007125 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00007126 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7127 BE = CS->body_end();
7128 /**/; ++BI) {
7129 if (BI + 1 == BE) {
7130 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7131 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007132 Info.FFDiag((*BI)->getBeginLoc(),
7133 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00007134 return false;
7135 }
Richard Smith457226e2019-09-23 03:48:44 +00007136 return this->Visit(FinalExpr) && Scope.destroy();
Richard Smith51f03172013-06-20 03:00:05 +00007137 }
7138
7139 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00007140 StmtResult Result = { ReturnValue, nullptr };
7141 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00007142 if (ESR != ESR_Succeeded) {
7143 // FIXME: If the statement-expression terminated due to 'return',
7144 // 'break', or 'continue', it would be nice to propagate that to
7145 // the outer statement evaluation rather than bailing out.
7146 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007147 Info.FFDiag((*BI)->getBeginLoc(),
7148 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00007149 return false;
7150 }
7151 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00007152
7153 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00007154 }
7155
Richard Smith4a678122011-10-24 18:44:57 +00007156 /// Visit a value which is evaluated, but whose value is ignored.
7157 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00007158 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00007159 }
David Majnemere9807b22016-02-26 04:23:19 +00007160
7161 /// Potentially visit a MemberExpr's base expression.
7162 void VisitIgnoredBaseExpression(const Expr *E) {
7163 // While MSVC doesn't evaluate the base expression, it does diagnose the
7164 // presence of side-effecting behavior.
7165 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7166 return;
7167 VisitIgnoredValue(E);
7168 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007169};
7170
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007171} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00007172
7173//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00007174// Common base class for lvalue and temporary evaluation.
7175//===----------------------------------------------------------------------===//
7176namespace {
7177template<class Derived>
7178class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00007179 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00007180protected:
7181 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007182 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00007183 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00007184 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00007185
7186 bool Success(APValue::LValueBase B) {
7187 Result.set(B);
7188 return true;
7189 }
7190
George Burgess IVf9013bf2017-02-10 22:52:29 +00007191 bool evaluatePointer(const Expr *E, LValue &Result) {
7192 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7193 }
7194
Richard Smith027bf112011-11-17 22:56:20 +00007195public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007196 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7197 : ExprEvaluatorBaseTy(Info), Result(Result),
7198 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00007199
Richard Smith2e312c82012-03-03 22:46:17 +00007200 bool Success(const APValue &V, const Expr *E) {
7201 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00007202 return true;
7203 }
Richard Smith027bf112011-11-17 22:56:20 +00007204
Richard Smith027bf112011-11-17 22:56:20 +00007205 bool VisitMemberExpr(const MemberExpr *E) {
7206 // Handle non-static data members.
7207 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00007208 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00007209 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007210 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00007211 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00007212 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00007213 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00007214 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00007215 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00007216 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00007217 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00007218 BaseTy = E->getBase()->getType();
7219 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00007220 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007221 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007222 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00007223 Result.setInvalid(E);
7224 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00007225 }
Richard Smith027bf112011-11-17 22:56:20 +00007226
Richard Smith1b78b3d2012-01-25 22:15:11 +00007227 const ValueDecl *MD = E->getMemberDecl();
7228 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00007229 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smith1b78b3d2012-01-25 22:15:11 +00007230 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7231 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00007232 if (!HandleLValueMember(this->Info, E, Result, FD))
7233 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00007234 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00007235 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7236 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00007237 } else
7238 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007239
Richard Smith1b78b3d2012-01-25 22:15:11 +00007240 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00007241 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00007242 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00007243 RefValue))
7244 return false;
7245 return Success(RefValue, E);
7246 }
7247 return true;
7248 }
7249
7250 bool VisitBinaryOperator(const BinaryOperator *E) {
7251 switch (E->getOpcode()) {
7252 default:
7253 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7254
7255 case BO_PtrMemD:
7256 case BO_PtrMemI:
7257 return HandleMemberPointerAccess(this->Info, E, Result);
7258 }
7259 }
7260
7261 bool VisitCastExpr(const CastExpr *E) {
7262 switch (E->getCastKind()) {
7263 default:
7264 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7265
7266 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00007267 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00007268 if (!this->Visit(E->getSubExpr()))
7269 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007270
7271 // Now figure out the necessary offset to add to the base LV to get from
7272 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00007273 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7274 Result);
Richard Smith027bf112011-11-17 22:56:20 +00007275 }
7276 }
7277};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007278}
Richard Smith027bf112011-11-17 22:56:20 +00007279
7280//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00007281// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007282//
7283// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7284// function designators (in C), decl references to void objects (in C), and
7285// temporaries (if building with -Wno-address-of-temporary).
7286//
7287// LValue evaluation produces values comprising a base expression of one of the
7288// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00007289// - Declarations
7290// * VarDecl
7291// * FunctionDecl
7292// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00007293// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00007294// * StringLiteral
7295// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00007296// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00007297// * ObjCEncodeExpr
7298// * AddrLabelExpr
7299// * BlockExpr
7300// * CallExpr for a MakeStringConstant builtin
Richard Smithee0ce3022019-05-17 07:06:46 +00007301// - typeid(T) expressions, as TypeInfoLValues
Richard Smithce40ad62011-11-12 22:28:03 +00007302// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00007303// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00007304// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00007305// was evaluated, for cases where the MaterializeTemporaryExpr is missing
7306// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00007307// * A MaterializeTemporaryExpr that has static storage duration, with no
7308// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00007309// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00007310//===----------------------------------------------------------------------===//
7311namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007312class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00007313 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00007314public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007315 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7316 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00007317
Richard Smith11562c52011-10-28 17:51:58 +00007318 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00007319 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00007320
Peter Collingbournee9200682011-05-13 03:29:01 +00007321 bool VisitDeclRefExpr(const DeclRefExpr *E);
7322 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00007323 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007324 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7325 bool VisitMemberExpr(const MemberExpr *E);
7326 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7327 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00007328 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00007329 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007330 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7331 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00007332 bool VisitUnaryReal(const UnaryOperator *E);
7333 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00007334 bool VisitUnaryPreInc(const UnaryOperator *UO) {
7335 return VisitUnaryPreIncDec(UO);
7336 }
7337 bool VisitUnaryPreDec(const UnaryOperator *UO) {
7338 return VisitUnaryPreIncDec(UO);
7339 }
Richard Smith3229b742013-05-05 21:17:10 +00007340 bool VisitBinAssign(const BinaryOperator *BO);
7341 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00007342
Peter Collingbournee9200682011-05-13 03:29:01 +00007343 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00007344 switch (E->getCastKind()) {
7345 default:
Richard Smith027bf112011-11-17 22:56:20 +00007346 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00007347
Eli Friedmance3e02a2011-10-11 00:13:24 +00007348 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00007349 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00007350 if (!Visit(E->getSubExpr()))
7351 return false;
7352 Result.Designator.setInvalid();
7353 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00007354
Richard Smith027bf112011-11-17 22:56:20 +00007355 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00007356 if (!Visit(E->getSubExpr()))
7357 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007358 return HandleBaseToDerivedCast(Info, E, Result);
Richard Smith7bd54ab2019-05-15 20:22:21 +00007359
7360 case CK_Dynamic:
7361 if (!Visit(E->getSubExpr()))
7362 return false;
7363 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00007364 }
7365 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007366};
7367} // end anonymous namespace
7368
Richard Smith11562c52011-10-28 17:51:58 +00007369/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00007370/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00007371/// * function designators in C, and
7372/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00007373/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00007374static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7375 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00007376 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00007377 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00007378 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007379}
7380
Peter Collingbournee9200682011-05-13 03:29:01 +00007381bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00007382 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00007383 return Success(FD);
7384 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00007385 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00007386 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00007387 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00007388 return Error(E);
7389}
Richard Smith733237d2011-10-24 23:14:33 +00007390
Faisal Vali0528a312016-11-13 06:09:16 +00007391
Richard Smith11562c52011-10-28 17:51:58 +00007392bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00007393
7394 // If we are within a lambda's call operator, check whether the 'VD' referred
7395 // to within 'E' actually represents a lambda-capture that maps to a
7396 // data-member/field within the closure object, and if so, evaluate to the
7397 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00007398 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7399 isa<DeclRefExpr>(E) &&
7400 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7401 // We don't always have a complete capture-map when checking or inferring if
7402 // the function call operator meets the requirements of a constexpr function
7403 // - but we don't need to evaluate the captures to determine constexprness
7404 // (dcl.constexpr C++17).
7405 if (Info.checkingPotentialConstantExpression())
7406 return false;
7407
Faisal Vali051e3a22017-02-16 04:12:21 +00007408 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00007409 // Start with 'Result' referring to the complete closure object...
7410 Result = *Info.CurrentCall->This;
7411 // ... then update it to refer to the field of the closure object
7412 // that represents the capture.
7413 if (!HandleLValueMember(Info, E, Result, FD))
7414 return false;
7415 // And if the field is of reference type, update 'Result' to refer to what
7416 // the field refers to.
7417 if (FD->getType()->isReferenceType()) {
7418 APValue RVal;
7419 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7420 RVal))
7421 return false;
7422 Result.setFrom(Info.Ctx, RVal);
7423 }
7424 return true;
7425 }
7426 }
Craig Topper36250ad2014-05-12 05:36:57 +00007427 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00007428 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7429 // Only if a local variable was declared in the function currently being
7430 // evaluated, do we expect to be able to find its value in the current
7431 // frame. (Otherwise it was likely declared in an enclosing context and
7432 // could either have a valid evaluatable value (for e.g. a constexpr
7433 // variable) or be ill-formed (and trigger an appropriate evaluation
7434 // diagnostic)).
7435 if (Info.CurrentCall->Callee &&
7436 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7437 Frame = Info.CurrentCall;
7438 }
7439 }
Richard Smith3229b742013-05-05 21:17:10 +00007440
Richard Smithfec09922011-11-01 16:57:24 +00007441 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00007442 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007443 Result.set({VD, Frame->Index,
7444 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00007445 return true;
7446 }
Richard Smithce40ad62011-11-12 22:28:03 +00007447 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00007448 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00007449
Richard Smith3229b742013-05-05 21:17:10 +00007450 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007451 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007452 return false;
Richard Smithe637cbe2019-05-21 23:15:18 +00007453 if (!V->hasValue()) {
7454 // FIXME: Is it possible for V to be indeterminate here? If so, we should
7455 // adjust the diagnostic to say that.
Richard Smith6d4c6582013-11-05 22:18:15 +00007456 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00007457 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00007458 return false;
7459 }
Richard Smith3229b742013-05-05 21:17:10 +00007460 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00007461}
7462
Richard Smith4e4c78ff2011-10-31 05:52:43 +00007463bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7464 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00007465 // Walk through the expression to find the materialized temporary itself.
7466 SmallVector<const Expr *, 2> CommaLHSs;
7467 SmallVector<SubobjectAdjustment, 2> Adjustments;
Tykerb0561b32019-11-17 11:41:55 +01007468 const Expr *Inner =
7469 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00007470
Richard Smith84401042013-06-03 05:03:02 +00007471 // If we passed any comma operators, evaluate their LHSs.
7472 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7473 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7474 return false;
7475
Richard Smithe6c01442013-06-05 00:46:14 +00007476 // A materialized temporary with static storage duration can appear within the
7477 // result of a constant expression evaluation, so we need to preserve its
7478 // value for use outside this evaluation.
7479 APValue *Value;
7480 if (E->getStorageDuration() == SD_Static) {
Tykerb0561b32019-11-17 11:41:55 +01007481 Value = E->getOrCreateValue(true);
Richard Smitha509f2f2013-06-14 03:07:01 +00007482 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00007483 Result.set(E);
7484 } else {
Richard Smith457226e2019-09-23 03:48:44 +00007485 Value = &Info.CurrentCall->createTemporary(
7486 E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
Richard Smithe6c01442013-06-05 00:46:14 +00007487 }
7488
Richard Smithea4ad5d2013-06-06 08:19:16 +00007489 QualType Type = Inner->getType();
7490
Richard Smith84401042013-06-03 05:03:02 +00007491 // Materialize the temporary itself.
Richard Smith4566f872019-09-29 05:58:31 +00007492 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
Richard Smithea4ad5d2013-06-06 08:19:16 +00007493 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00007494 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00007495 }
Richard Smith84401042013-06-03 05:03:02 +00007496
7497 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00007498 for (unsigned I = Adjustments.size(); I != 0; /**/) {
7499 --I;
7500 switch (Adjustments[I].Kind) {
7501 case SubobjectAdjustment::DerivedToBaseAdjustment:
7502 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7503 Type, Result))
7504 return false;
7505 Type = Adjustments[I].DerivedToBase.BasePath->getType();
7506 break;
7507
7508 case SubobjectAdjustment::FieldAdjustment:
7509 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7510 return false;
7511 Type = Adjustments[I].Field->getType();
7512 break;
7513
7514 case SubobjectAdjustment::MemberPointerAdjustment:
7515 if (!HandleMemberPointerAccess(this->Info, Type, Result,
7516 Adjustments[I].Ptr.RHS))
7517 return false;
7518 Type = Adjustments[I].Ptr.MPT->getPointeeType();
7519 break;
7520 }
7521 }
7522
7523 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00007524}
7525
Peter Collingbournee9200682011-05-13 03:29:01 +00007526bool
7527LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00007528 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
7529 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00007530 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
7531 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00007532 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007533}
7534
Richard Smith6e525142011-12-27 12:18:28 +00007535bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smitha9330302019-05-17 19:19:28 +00007536 TypeInfoLValue TypeInfo;
7537
Richard Smithee0ce3022019-05-17 07:06:46 +00007538 if (!E->isPotentiallyEvaluated()) {
Richard Smithee0ce3022019-05-17 07:06:46 +00007539 if (E->isTypeOperand())
7540 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
7541 else
7542 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
Richard Smitha9330302019-05-17 19:19:28 +00007543 } else {
7544 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
7545 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7546 << E->getExprOperand()->getType()
7547 << E->getExprOperand()->getSourceRange();
7548 }
7549
7550 if (!Visit(E->getExprOperand()))
7551 return false;
7552
7553 Optional<DynamicType> DynType =
7554 ComputeDynamicType(Info, E, Result, AK_TypeId);
7555 if (!DynType)
7556 return false;
7557
7558 TypeInfo =
7559 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
Richard Smithee0ce3022019-05-17 07:06:46 +00007560 }
Richard Smith6f3d4352012-10-17 23:52:07 +00007561
Richard Smitha9330302019-05-17 19:19:28 +00007562 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
Richard Smith6e525142011-12-27 12:18:28 +00007563}
7564
Francois Pichet0066db92012-04-16 04:08:35 +00007565bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7566 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00007567}
Francois Pichet0066db92012-04-16 04:08:35 +00007568
Peter Collingbournee9200682011-05-13 03:29:01 +00007569bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007570 // Handle static data members.
7571 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007572 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00007573 return VisitVarDecl(E, VD);
7574 }
7575
Richard Smith254a73d2011-10-28 22:34:42 +00007576 // Handle static member functions.
7577 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
7578 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00007579 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00007580 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00007581 }
7582 }
7583
Richard Smithd62306a2011-11-10 06:34:14 +00007584 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00007585 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007586}
7587
Peter Collingbournee9200682011-05-13 03:29:01 +00007588bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00007589 // FIXME: Deal with vectors as array subscript bases.
7590 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007591 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00007592
Nick Lewyckyad888682017-04-27 07:27:36 +00007593 bool Success = true;
7594 if (!evaluatePointer(E->getBase(), Result)) {
7595 if (!Info.noteFailure())
7596 return false;
7597 Success = false;
7598 }
Mike Stump11289f42009-09-09 15:08:12 +00007599
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007600 APSInt Index;
7601 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00007602 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007603
Nick Lewyckyad888682017-04-27 07:27:36 +00007604 return Success &&
7605 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007606}
Eli Friedman9a156e52008-11-12 09:44:48 +00007607
Peter Collingbournee9200682011-05-13 03:29:01 +00007608bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007609 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00007610}
7611
Richard Smith66c96992012-02-18 22:04:06 +00007612bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7613 if (!Visit(E->getSubExpr()))
7614 return false;
7615 // __real is a no-op on scalar lvalues.
7616 if (E->getSubExpr()->getType()->isAnyComplexType())
7617 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
7618 return true;
7619}
7620
7621bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7622 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
7623 "lvalue __imag__ on scalar?");
7624 if (!Visit(E->getSubExpr()))
7625 return false;
7626 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
7627 return true;
7628}
7629
Richard Smith243ef902013-05-05 23:31:59 +00007630bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007631 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00007632 return Error(UO);
7633
7634 if (!this->Visit(UO->getSubExpr()))
7635 return false;
7636
Richard Smith243ef902013-05-05 23:31:59 +00007637 return handleIncDec(
7638 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00007639 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00007640}
7641
7642bool LValueExprEvaluator::VisitCompoundAssignOperator(
7643 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007644 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00007645 return Error(CAO);
7646
Richard Smith3229b742013-05-05 21:17:10 +00007647 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00007648
7649 // The overall lvalue result is the result of evaluating the LHS.
7650 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00007651 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007652 Evaluate(RHS, this->Info, CAO->getRHS());
7653 return false;
7654 }
7655
Richard Smith3229b742013-05-05 21:17:10 +00007656 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
7657 return false;
7658
Richard Smith43e77732013-05-07 04:50:00 +00007659 return handleCompoundAssignment(
7660 this->Info, CAO,
7661 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
7662 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00007663}
7664
7665bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00007666 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007667 return Error(E);
7668
Richard Smith3229b742013-05-05 21:17:10 +00007669 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00007670
7671 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00007672 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00007673 Evaluate(NewVal, this->Info, E->getRHS());
7674 return false;
7675 }
7676
Richard Smith3229b742013-05-05 21:17:10 +00007677 if (!Evaluate(NewVal, this->Info, E->getRHS()))
7678 return false;
Richard Smith243ef902013-05-05 23:31:59 +00007679
Richard Smith31c69a32019-05-21 23:15:20 +00007680 if (Info.getLangOpts().CPlusPlus2a &&
7681 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
7682 return false;
7683
Richard Smith243ef902013-05-05 23:31:59 +00007684 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00007685 NewVal);
7686}
7687
Eli Friedman9a156e52008-11-12 09:44:48 +00007688//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007689// Pointer Evaluation
7690//===----------------------------------------------------------------------===//
7691
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007692/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00007693/// returned by a function with the alloc_size attribute. Returns true if we
7694/// were successful. Places an unsigned number into `Result`.
7695///
7696/// This expects the given CallExpr to be a call to a function with an
7697/// alloc_size attribute.
7698static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7699 const CallExpr *Call,
7700 llvm::APInt &Result) {
7701 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
7702
Joel E. Denny81508102018-03-13 14:51:22 +00007703 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
7704 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00007705 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
7706 if (Call->getNumArgs() <= SizeArgNo)
7707 return false;
7708
7709 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00007710 Expr::EvalResult ExprResult;
7711 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00007712 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00007713 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00007714 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
7715 return false;
7716 Into = Into.zextOrSelf(BitsInSizeT);
7717 return true;
7718 };
7719
7720 APSInt SizeOfElem;
7721 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
7722 return false;
7723
Joel E. Denny81508102018-03-13 14:51:22 +00007724 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007725 Result = std::move(SizeOfElem);
7726 return true;
7727 }
7728
7729 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00007730 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00007731 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
7732 return false;
7733
7734 bool Overflow;
7735 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
7736 if (Overflow)
7737 return false;
7738
7739 Result = std::move(BytesAvailable);
7740 return true;
7741}
7742
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007743/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00007744/// function.
7745static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7746 const LValue &LVal,
7747 llvm::APInt &Result) {
7748 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7749 "Can't get the size of a non alloc_size function");
7750 const auto *Base = LVal.getLValueBase().get<const Expr *>();
7751 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
7752 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
7753}
7754
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007755/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00007756/// a function with the alloc_size attribute. If it was possible to do so, this
7757/// function will return true, make Result's Base point to said function call,
7758/// and mark Result's Base as invalid.
7759static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
7760 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007761 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00007762 return false;
7763
7764 // Because we do no form of static analysis, we only support const variables.
7765 //
7766 // Additionally, we can't support parameters, nor can we support static
7767 // variables (in the latter case, use-before-assign isn't UB; in the former,
7768 // we have no clue what they'll be assigned to).
7769 const auto *VD =
7770 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
7771 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
7772 return false;
7773
7774 const Expr *Init = VD->getAnyInitializer();
7775 if (!Init)
7776 return false;
7777
7778 const Expr *E = Init->IgnoreParens();
7779 if (!tryUnwrapAllocSizeCall(E))
7780 return false;
7781
7782 // Store E instead of E unwrapped so that the type of the LValue's base is
7783 // what the user wanted.
7784 Result.setInvalid(E);
7785
7786 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00007787 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00007788 return true;
7789}
7790
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007791namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007792class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007793 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00007794 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007795 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00007796
Peter Collingbournee9200682011-05-13 03:29:01 +00007797 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00007798 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00007799 return true;
7800 }
George Burgess IVe3763372016-12-22 02:50:20 +00007801
George Burgess IVf9013bf2017-02-10 22:52:29 +00007802 bool evaluateLValue(const Expr *E, LValue &Result) {
7803 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7804 }
7805
7806 bool evaluatePointer(const Expr *E, LValue &Result) {
7807 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7808 }
7809
George Burgess IVe3763372016-12-22 02:50:20 +00007810 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007811public:
Mike Stump11289f42009-09-09 15:08:12 +00007812
George Burgess IVf9013bf2017-02-10 22:52:29 +00007813 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7814 : ExprEvaluatorBaseTy(info), Result(Result),
7815 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007816
Richard Smith2e312c82012-03-03 22:46:17 +00007817 bool Success(const APValue &V, const Expr *E) {
7818 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00007819 return true;
7820 }
Richard Smithfddd3842011-12-30 21:15:51 +00007821 bool ZeroInitialization(const Expr *E) {
Richard Smith19ad5232019-10-03 00:39:33 +00007822 Result.setNull(Info.Ctx, E->getType());
Yaxun Liu402804b2016-12-15 08:09:08 +00007823 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00007824 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007825
John McCall45d55e42010-05-07 21:00:08 +00007826 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007827 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00007828 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007829 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00007830 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00007831 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00007832 if (E->isExpressibleAsConstantInitializer())
7833 return Success(E);
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00007834 if (Info.noteFailure())
7835 EvaluateIgnoredValue(Info, E->getSubExpr());
7836 return Error(E);
7837 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007838 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00007839 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00007840 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007841 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00007842 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00007843 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00007844 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007845 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00007846 }
Richard Smithd62306a2011-11-10 06:34:14 +00007847 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00007848 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00007849 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00007850 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00007851 if (!Info.CurrentCall->This) {
7852 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00007853 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00007854 else
Faisal Valie690b7a2016-07-02 22:34:24 +00007855 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00007856 return false;
7857 }
Richard Smithd62306a2011-11-10 06:34:14 +00007858 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00007859 // If we are inside a lambda's call operator, the 'this' expression refers
7860 // to the enclosing '*this' object (either by value or reference) which is
7861 // either copied into the closure object's field that represents the '*this'
7862 // or refers to '*this'.
7863 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7864 // Update 'Result' to refer to the data member/field of the closure object
7865 // that represents the '*this' capture.
7866 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00007867 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00007868 return false;
7869 // If we captured '*this' by reference, replace the field with its referent.
7870 if (Info.CurrentCall->LambdaThisCaptureField->getType()
7871 ->isPointerType()) {
7872 APValue RVal;
7873 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7874 RVal))
7875 return false;
7876
7877 Result.setFrom(Info.Ctx, RVal);
7878 }
7879 }
Richard Smithd62306a2011-11-10 06:34:14 +00007880 return true;
7881 }
John McCallc07a0c72011-02-17 10:25:35 +00007882
Richard Smithda1b4342019-09-27 01:26:47 +00007883 bool VisitCXXNewExpr(const CXXNewExpr *E);
7884
Eric Fiselier708afb52019-05-16 21:04:15 +00007885 bool VisitSourceLocExpr(const SourceLocExpr *E) {
7886 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7887 APValue LValResult = E->EvaluateInContext(
7888 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7889 Result.setFrom(Info.Ctx, LValResult);
7890 return true;
7891 }
7892
Eli Friedman449fe542009-03-23 04:56:01 +00007893 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007894};
Chris Lattner05706e882008-07-11 18:11:29 +00007895} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007896
George Burgess IVf9013bf2017-02-10 22:52:29 +00007897static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7898 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00007899 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00007900 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00007901}
7902
John McCall45d55e42010-05-07 21:00:08 +00007903bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00007904 if (E->getOpcode() != BO_Add &&
7905 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00007906 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00007907
Chris Lattner05706e882008-07-11 18:11:29 +00007908 const Expr *PExp = E->getLHS();
7909 const Expr *IExp = E->getRHS();
7910 if (IExp->getType()->isPointerType())
7911 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00007912
George Burgess IVf9013bf2017-02-10 22:52:29 +00007913 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00007914 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00007915 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007916
John McCall45d55e42010-05-07 21:00:08 +00007917 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00007918 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00007919 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007920
Richard Smith96e0c102011-11-04 02:25:55 +00007921 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00007922 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007923
Ted Kremenek28831752012-08-23 20:46:57 +00007924 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00007925 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007926}
Eli Friedman9a156e52008-11-12 09:44:48 +00007927
John McCall45d55e42010-05-07 21:00:08 +00007928bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007929 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007930}
Mike Stump11289f42009-09-09 15:08:12 +00007931
Richard Smith81dfef92018-07-11 00:29:05 +00007932bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7933 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00007934
Eli Friedman847a2bc2009-12-27 05:43:15 +00007935 switch (E->getCastKind()) {
7936 default:
7937 break;
John McCalle3027922010-08-25 11:45:40 +00007938 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00007939 case CK_CPointerToObjCPointerCast:
7940 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00007941 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007942 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00007943 if (!Visit(SubExpr))
7944 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00007945 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7946 // permitted in constant expressions in C++11. Bitcasts from cv void* are
7947 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00007948 if (!E->getType()->isVoidPointerType()) {
Richard Smith19ad5232019-10-03 00:39:33 +00007949 if (!Result.InvalidBase && !Result.Designator.Invalid &&
7950 !Result.IsNullPtr &&
7951 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
7952 E->getType()->getPointeeType()) &&
7953 Info.getStdAllocatorCaller("allocate")) {
7954 // Inside a call to std::allocator::allocate and friends, we permit
7955 // casting from void* back to cv1 T* for a pointer that points to a
7956 // cv2 T.
7957 } else {
7958 Result.Designator.setInvalid();
7959 if (SubExpr->getType()->isVoidPointerType())
7960 CCEDiag(E, diag::note_constexpr_invalid_cast)
7961 << 3 << SubExpr->getType();
7962 else
7963 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7964 }
Richard Smithff07af12011-12-12 19:10:03 +00007965 }
Yaxun Liu402804b2016-12-15 08:09:08 +00007966 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7967 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00007968 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00007969
Anders Carlsson18275092010-10-31 20:41:46 +00007970 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00007971 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007972 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00007973 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007974 if (!Result.Base && Result.Offset.isZero())
7975 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00007976
Richard Smithd62306a2011-11-10 06:34:14 +00007977 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00007978 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00007979 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7980 castAs<PointerType>()->getPointeeType(),
7981 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00007982
Richard Smith027bf112011-11-17 22:56:20 +00007983 case CK_BaseToDerived:
7984 if (!Visit(E->getSubExpr()))
7985 return false;
7986 if (!Result.Base && Result.Offset.isZero())
7987 return true;
7988 return HandleBaseToDerivedCast(Info, E, Result);
7989
Richard Smith7bd54ab2019-05-15 20:22:21 +00007990 case CK_Dynamic:
7991 if (!Visit(E->getSubExpr()))
7992 return false;
7993 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7994
Richard Smith0b0a0b62011-10-29 20:57:55 +00007995 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007996 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007997 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00007998
John McCalle3027922010-08-25 11:45:40 +00007999 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008000 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8001
Richard Smith2e312c82012-03-03 22:46:17 +00008002 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00008003 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00008004 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00008005
John McCall45d55e42010-05-07 21:00:08 +00008006 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00008007 unsigned Size = Info.Ctx.getTypeSize(E->getType());
8008 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00008009 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00008010 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00008011 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00008012 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00008013 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00008014 return true;
8015 } else {
8016 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00008017 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00008018 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00008019 }
8020 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00008021
8022 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00008023 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00008024 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00008025 return false;
8026 } else {
Richard Smith457226e2019-09-23 03:48:44 +00008027 APValue &Value = Info.CurrentCall->createTemporary(
8028 SubExpr, SubExpr->getType(), false, Result);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00008029 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00008030 return false;
8031 }
Richard Smith96e0c102011-11-04 02:25:55 +00008032 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00008033 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8034 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00008035 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00008036 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00008037 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00008038 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00008039 }
Richard Smithdd785442011-10-31 20:57:44 +00008040
John McCalle3027922010-08-25 11:45:40 +00008041 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00008042 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00008043
8044 case CK_LValueToRValue: {
8045 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00008046 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00008047 return false;
8048
8049 APValue RVal;
8050 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8051 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8052 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00008053 return InvalidBaseOK &&
8054 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00008055 return Success(RVal, E);
8056 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008057 }
8058
Richard Smith11562c52011-10-28 17:51:58 +00008059 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00008060}
Chris Lattner05706e882008-07-11 18:11:29 +00008061
Richard Smith6822bd72018-10-26 19:26:45 +00008062static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8063 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00008064 // C++ [expr.alignof]p3:
8065 // When alignof is applied to a reference type, the result is the
8066 // alignment of the referenced type.
8067 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8068 T = Ref->getPointeeType();
8069
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00008070 if (T.getQualifiers().hasUnaligned())
8071 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00008072
8073 const bool AlignOfReturnsPreferred =
8074 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8075
8076 // __alignof is defined to return the preferred alignment.
8077 // Before 8, clang returned the preferred alignment for alignof and _Alignof
8078 // as well.
8079 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8080 return Info.Ctx.toCharUnitsFromBits(
8081 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8082 // alignof and _Alignof are defined to return the ABI alignment.
8083 else if (ExprKind == UETT_AlignOf)
8084 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8085 else
8086 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00008087}
8088
Richard Smith6822bd72018-10-26 19:26:45 +00008089static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8090 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00008091 E = E->IgnoreParens();
8092
8093 // The kinds of expressions that we have special-case logic here for
8094 // should be kept up to date with the special checks for those
8095 // expressions in Sema.
8096
8097 // alignof decl is always accepted, even if it doesn't make sense: we default
8098 // to 1 in those cases.
8099 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8100 return Info.Ctx.getDeclAlign(DRE->getDecl(),
8101 /*RefAsPointee*/true);
8102
8103 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8104 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8105 /*RefAsPointee*/true);
8106
Richard Smith6822bd72018-10-26 19:26:45 +00008107 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00008108}
8109
George Burgess IVe3763372016-12-22 02:50:20 +00008110// To be clear: this happily visits unsupported builtins. Better name welcomed.
8111bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8112 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8113 return true;
8114
George Burgess IVf9013bf2017-02-10 22:52:29 +00008115 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00008116 return false;
8117
8118 Result.setInvalid(E);
8119 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00008120 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00008121 return true;
8122}
8123
Peter Collingbournee9200682011-05-13 03:29:01 +00008124bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00008125 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00008126 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00008127
Richard Smith6328cbd2016-11-16 00:57:23 +00008128 if (unsigned BuiltinOp = E->getBuiltinCallee())
8129 return VisitBuiltinCallExpr(E, BuiltinOp);
8130
George Burgess IVe3763372016-12-22 02:50:20 +00008131 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00008132}
8133
8134bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8135 unsigned BuiltinOp) {
8136 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00008137 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00008138 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00008139 case Builtin::BI__builtin_assume_aligned: {
8140 // We need to be very careful here because: if the pointer does not have the
8141 // asserted alignment, then the behavior is undefined, and undefined
8142 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00008143 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00008144 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00008145
Hal Finkel0dd05d42014-10-03 17:18:37 +00008146 LValue OffsetResult(Result);
8147 APSInt Alignment;
8148 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
8149 return false;
Richard Smith642a2362017-01-30 23:30:26 +00008150 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00008151
8152 if (E->getNumArgs() > 2) {
8153 APSInt Offset;
8154 if (!EvaluateInteger(E->getArg(2), Offset, Info))
8155 return false;
8156
Richard Smith642a2362017-01-30 23:30:26 +00008157 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00008158 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8159 }
8160
8161 // If there is a base object, then it must have the correct alignment.
8162 if (OffsetResult.Base) {
8163 CharUnits BaseAlignment;
8164 if (const ValueDecl *VD =
8165 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
8166 BaseAlignment = Info.Ctx.getDeclAlign(VD);
Richard Smithee0ce3022019-05-17 07:06:46 +00008167 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
8168 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00008169 } else {
Richard Smithee0ce3022019-05-17 07:06:46 +00008170 BaseAlignment = GetAlignOfType(
8171 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00008172 }
8173
8174 if (BaseAlignment < Align) {
8175 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00008176 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00008177 CCEDiag(E->getArg(0),
8178 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00008179 << (unsigned)BaseAlignment.getQuantity()
8180 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00008181 return false;
8182 }
8183 }
8184
8185 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00008186 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00008187 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00008188
Richard Smith642a2362017-01-30 23:30:26 +00008189 (OffsetResult.Base
8190 ? CCEDiag(E->getArg(0),
8191 diag::note_constexpr_baa_insufficient_alignment) << 1
8192 : CCEDiag(E->getArg(0),
8193 diag::note_constexpr_baa_value_insufficient_alignment))
8194 << (int)OffsetResult.Offset.getQuantity()
8195 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00008196 return false;
8197 }
8198
8199 return true;
8200 }
Richard Smith19ad5232019-10-03 00:39:33 +00008201 case Builtin::BI__builtin_operator_new:
8202 return HandleOperatorNewCall(Info, E, Result);
Eric Fiselier26187502018-12-14 21:11:28 +00008203 case Builtin::BI__builtin_launder:
8204 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00008205 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00008206 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00008207 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00008208 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00008209 if (Info.getLangOpts().CPlusPlus11)
8210 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8211 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00008212 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00008213 else
8214 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008215 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00008216 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00008217 case Builtin::BI__builtin_wcschr:
8218 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00008219 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00008220 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00008221 if (!Visit(E->getArg(0)))
8222 return false;
8223 APSInt Desired;
8224 if (!EvaluateInteger(E->getArg(1), Desired, Info))
8225 return false;
8226 uint64_t MaxLength = uint64_t(-1);
8227 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008228 BuiltinOp != Builtin::BIwcschr &&
8229 BuiltinOp != Builtin::BI__builtin_strchr &&
8230 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00008231 APSInt N;
8232 if (!EvaluateInteger(E->getArg(2), N, Info))
8233 return false;
8234 MaxLength = N.getExtValue();
8235 }
Hubert Tong147b7432018-12-12 16:53:43 +00008236 // We cannot find the value if there are no candidates to match against.
8237 if (MaxLength == 0u)
8238 return ZeroInitialization(E);
8239 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8240 Result.Designator.Invalid)
8241 return false;
8242 QualType CharTy = Result.Designator.getType(Info.Ctx);
8243 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8244 BuiltinOp == Builtin::BI__builtin_memchr;
8245 assert(IsRawByte ||
8246 Info.Ctx.hasSameUnqualifiedType(
8247 CharTy, E->getArg(0)->getType()->getPointeeType()));
8248 // Pointers to const void may point to objects of incomplete type.
8249 if (IsRawByte && CharTy->isIncompleteType()) {
8250 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
8251 return false;
8252 }
8253 // Give up on byte-oriented matching against multibyte elements.
8254 // FIXME: We can compare the bytes in the correct order.
8255 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
8256 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00008257 // Figure out what value we're actually looking for (after converting to
8258 // the corresponding unsigned type if necessary).
8259 uint64_t DesiredVal;
8260 bool StopAtNull = false;
8261 switch (BuiltinOp) {
8262 case Builtin::BIstrchr:
8263 case Builtin::BI__builtin_strchr:
8264 // strchr compares directly to the passed integer, and therefore
8265 // always fails if given an int that is not a char.
8266 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
8267 E->getArg(1)->getType(),
8268 Desired),
8269 Desired))
8270 return ZeroInitialization(E);
8271 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008272 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008273 case Builtin::BImemchr:
8274 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00008275 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00008276 // memchr compares by converting both sides to unsigned char. That's also
8277 // correct for strchr if we get this far (to cope with plain char being
8278 // unsigned in the strchr case).
8279 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8280 break;
Richard Smithe9507952016-11-12 01:39:56 +00008281
Richard Smith8110c9d2016-11-29 19:45:17 +00008282 case Builtin::BIwcschr:
8283 case Builtin::BI__builtin_wcschr:
8284 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008285 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008286 case Builtin::BIwmemchr:
8287 case Builtin::BI__builtin_wmemchr:
8288 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8289 DesiredVal = Desired.getZExtValue();
8290 break;
8291 }
Richard Smithe9507952016-11-12 01:39:56 +00008292
8293 for (; MaxLength; --MaxLength) {
8294 APValue Char;
8295 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8296 !Char.isInt())
8297 return false;
8298 if (Char.getInt().getZExtValue() == DesiredVal)
8299 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00008300 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00008301 break;
8302 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8303 return false;
8304 }
8305 // Not found: return nullptr.
8306 return ZeroInitialization(E);
8307 }
8308
Richard Smith06f71b52018-08-04 00:57:17 +00008309 case Builtin::BImemcpy:
8310 case Builtin::BImemmove:
8311 case Builtin::BIwmemcpy:
8312 case Builtin::BIwmemmove:
8313 if (Info.getLangOpts().CPlusPlus11)
8314 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8315 << /*isConstexpr*/0 << /*isConstructor*/0
8316 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8317 else
8318 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8319 LLVM_FALLTHROUGH;
8320 case Builtin::BI__builtin_memcpy:
8321 case Builtin::BI__builtin_memmove:
8322 case Builtin::BI__builtin_wmemcpy:
8323 case Builtin::BI__builtin_wmemmove: {
8324 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8325 BuiltinOp == Builtin::BIwmemmove ||
8326 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8327 BuiltinOp == Builtin::BI__builtin_wmemmove;
8328 bool Move = BuiltinOp == Builtin::BImemmove ||
8329 BuiltinOp == Builtin::BIwmemmove ||
8330 BuiltinOp == Builtin::BI__builtin_memmove ||
8331 BuiltinOp == Builtin::BI__builtin_wmemmove;
8332
8333 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00008334 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00008335 return false;
8336 LValue Dest = Result;
8337
8338 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00008339 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00008340 return false;
8341
8342 APSInt N;
8343 if (!EvaluateInteger(E->getArg(2), N, Info))
8344 return false;
8345 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8346
8347 // If the size is zero, we treat this as always being a valid no-op.
8348 // (Even if one of the src and dest pointers is null.)
8349 if (!N)
8350 return true;
8351
Richard Smith128719c2018-09-13 22:47:33 +00008352 // Otherwise, if either of the operands is null, we can't proceed. Don't
8353 // try to determine the type of the copied objects, because there aren't
8354 // any.
8355 if (!Src.Base || !Dest.Base) {
8356 APValue Val;
8357 (!Src.Base ? Src : Dest).moveInto(Val);
8358 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8359 << Move << WChar << !!Src.Base
8360 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8361 return false;
8362 }
8363 if (Src.Designator.Invalid || Dest.Designator.Invalid)
8364 return false;
8365
Richard Smith06f71b52018-08-04 00:57:17 +00008366 // We require that Src and Dest are both pointers to arrays of
8367 // trivially-copyable type. (For the wide version, the designator will be
8368 // invalid if the designated object is not a wchar_t.)
8369 QualType T = Dest.Designator.getType(Info.Ctx);
8370 QualType SrcT = Src.Designator.getType(Info.Ctx);
8371 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8372 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8373 return false;
8374 }
Petr Pavlued083f22018-10-04 09:25:44 +00008375 if (T->isIncompleteType()) {
8376 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8377 return false;
8378 }
Richard Smith06f71b52018-08-04 00:57:17 +00008379 if (!T.isTriviallyCopyableType(Info.Ctx)) {
8380 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8381 return false;
8382 }
8383
8384 // Figure out how many T's we're copying.
8385 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8386 if (!WChar) {
8387 uint64_t Remainder;
8388 llvm::APInt OrigN = N;
8389 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8390 if (Remainder) {
8391 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8392 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8393 << (unsigned)TSize;
8394 return false;
8395 }
8396 }
8397
8398 // Check that the copying will remain within the arrays, just so that we
8399 // can give a more meaningful diagnostic. This implicitly also checks that
8400 // N fits into 64 bits.
8401 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8402 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8403 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8404 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8405 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8406 << N.toString(10, /*Signed*/false);
8407 return false;
8408 }
8409 uint64_t NElems = N.getZExtValue();
8410 uint64_t NBytes = NElems * TSize;
8411
8412 // Check for overlap.
8413 int Direction = 1;
8414 if (HasSameBase(Src, Dest)) {
8415 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8416 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8417 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8418 // Dest is inside the source region.
8419 if (!Move) {
8420 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8421 return false;
8422 }
8423 // For memmove and friends, copy backwards.
8424 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8425 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8426 return false;
8427 Direction = -1;
8428 } else if (!Move && SrcOffset >= DestOffset &&
8429 SrcOffset - DestOffset < NBytes) {
8430 // Src is inside the destination region for memcpy: invalid.
8431 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8432 return false;
8433 }
8434 }
8435
8436 while (true) {
8437 APValue Val;
Richard Smithc667cdc2019-09-18 17:37:44 +00008438 // FIXME: Set WantObjectRepresentation to true if we're copying a
8439 // char-like type?
Richard Smith06f71b52018-08-04 00:57:17 +00008440 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8441 !handleAssignment(Info, E, Dest, T, Val))
8442 return false;
8443 // Do not iterate past the last element; if we're copying backwards, that
8444 // might take us off the start of the array.
8445 if (--NElems == 0)
8446 return true;
8447 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8448 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8449 return false;
8450 }
8451 }
8452
Richard Smith6cbd65d2013-07-11 02:27:57 +00008453 default:
Richard Smith19ad5232019-10-03 00:39:33 +00008454 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00008455 }
Richard Smith19ad5232019-10-03 00:39:33 +00008456
8457 return visitNonBuiltinCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008458}
Chris Lattner05706e882008-07-11 18:11:29 +00008459
Richard Smithda1b4342019-09-27 01:26:47 +00008460static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8461 APValue &Result, const InitListExpr *ILE,
8462 QualType AllocType);
8463
8464bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
Richard Smith62a95562019-09-27 01:26:49 +00008465 if (!Info.getLangOpts().CPlusPlus2a)
8466 Info.CCEDiag(E, diag::note_constexpr_new);
8467
Richard Smithda1b4342019-09-27 01:26:47 +00008468 // We cannot speculatively evaluate a delete expression.
8469 if (Info.SpeculativeEvaluationDepth)
8470 return false;
8471
8472 FunctionDecl *OperatorNew = E->getOperatorNew();
Richard Smithb5426022019-10-03 00:39:35 +00008473
8474 bool IsNothrow = false;
8475 bool IsPlacement = false;
8476 if (OperatorNew->isReservedGlobalPlacementOperator() &&
8477 Info.CurrentCall->isStdFunction() && !E->isArray()) {
8478 // FIXME Support array placement new.
8479 assert(E->getNumPlacementArgs() == 1);
8480 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
8481 return false;
8482 if (Result.Designator.Invalid)
8483 return false;
8484 IsPlacement = true;
8485 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
Richard Smithda1b4342019-09-27 01:26:47 +00008486 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
8487 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
8488 return false;
Richard Smithb5426022019-10-03 00:39:35 +00008489 } else if (E->getNumPlacementArgs()) {
Richard Smith62a95562019-09-27 01:26:49 +00008490 // The only new-placement list we support is of the form (std::nothrow).
8491 //
8492 // FIXME: There is no restriction on this, but it's not clear that any
8493 // other form makes any sense. We get here for cases such as:
8494 //
8495 // new (std::align_val_t{N}) X(int)
8496 //
8497 // (which should presumably be valid only if N is a multiple of
8498 // alignof(int), and in any case can't be deallocated unless N is
8499 // alignof(X) and X has new-extended alignment).
8500 if (E->getNumPlacementArgs() != 1 ||
8501 !E->getPlacementArg(0)->getType()->isNothrowT())
8502 return Error(E, diag::note_constexpr_new_placement);
8503
8504 LValue Nothrow;
8505 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
8506 return false;
8507 IsNothrow = true;
8508 }
Richard Smithda1b4342019-09-27 01:26:47 +00008509
8510 const Expr *Init = E->getInitializer();
8511 const InitListExpr *ResizedArrayILE = nullptr;
8512
8513 QualType AllocType = E->getAllocatedType();
8514 if (Optional<const Expr*> ArraySize = E->getArraySize()) {
8515 const Expr *Stripped = *ArraySize;
8516 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
8517 Stripped = ICE->getSubExpr())
8518 if (ICE->getCastKind() != CK_NoOp &&
8519 ICE->getCastKind() != CK_IntegralCast)
8520 break;
8521
8522 llvm::APSInt ArrayBound;
8523 if (!EvaluateInteger(Stripped, ArrayBound, Info))
8524 return false;
8525
8526 // C++ [expr.new]p9:
8527 // The expression is erroneous if:
8528 // -- [...] its value before converting to size_t [or] applying the
8529 // second standard conversion sequence is less than zero
8530 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
Richard Smith62a95562019-09-27 01:26:49 +00008531 if (IsNothrow)
8532 return ZeroInitialization(E);
8533
Richard Smithda1b4342019-09-27 01:26:47 +00008534 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
8535 << ArrayBound << (*ArraySize)->getSourceRange();
8536 return false;
8537 }
8538
8539 // -- its value is such that the size of the allocated object would
8540 // exceed the implementation-defined limit
8541 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
8542 ArrayBound) >
8543 ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
Richard Smith62a95562019-09-27 01:26:49 +00008544 if (IsNothrow)
8545 return ZeroInitialization(E);
8546
Richard Smithda1b4342019-09-27 01:26:47 +00008547 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
8548 << ArrayBound << (*ArraySize)->getSourceRange();
8549 return false;
8550 }
8551
8552 // -- the new-initializer is a braced-init-list and the number of
8553 // array elements for which initializers are provided [...]
8554 // exceeds the number of elements to initialize
8555 if (Init) {
8556 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
8557 assert(CAT && "unexpected type for array initializer");
8558
8559 unsigned Bits =
8560 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
8561 llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
8562 llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
8563 if (InitBound.ugt(AllocBound)) {
Richard Smith62a95562019-09-27 01:26:49 +00008564 if (IsNothrow)
8565 return ZeroInitialization(E);
8566
Richard Smithda1b4342019-09-27 01:26:47 +00008567 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
8568 << AllocBound.toString(10, /*Signed=*/false)
8569 << InitBound.toString(10, /*Signed=*/false)
8570 << (*ArraySize)->getSourceRange();
8571 return false;
8572 }
8573
8574 // If the sizes differ, we must have an initializer list, and we need
8575 // special handling for this case when we initialize.
8576 if (InitBound != AllocBound)
8577 ResizedArrayILE = cast<InitListExpr>(Init);
8578 }
8579
Richard Smith772e2662019-10-04 01:25:59 +00008580 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
Richard Smithda1b4342019-09-27 01:26:47 +00008581 ArrayType::Normal, 0);
8582 } else {
8583 assert(!AllocType->isArrayType() &&
8584 "array allocation with non-array new");
8585 }
8586
Richard Smithb5426022019-10-03 00:39:35 +00008587 APValue *Val;
8588 if (IsPlacement) {
8589 AccessKinds AK = AK_Construct;
8590 struct FindObjectHandler {
8591 EvalInfo &Info;
8592 const Expr *E;
8593 QualType AllocType;
8594 const AccessKinds AccessKind;
8595 APValue *Value;
8596
8597 typedef bool result_type;
8598 bool failed() { return false; }
8599 bool found(APValue &Subobj, QualType SubobjType) {
8600 // FIXME: Reject the cases where [basic.life]p8 would not permit the
8601 // old name of the object to be used to name the new object.
8602 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
8603 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
8604 SubobjType << AllocType;
8605 return false;
8606 }
8607 Value = &Subobj;
8608 return true;
8609 }
8610 bool found(APSInt &Value, QualType SubobjType) {
8611 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8612 return false;
8613 }
8614 bool found(APFloat &Value, QualType SubobjType) {
8615 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8616 return false;
8617 }
8618 } Handler = {Info, E, AllocType, AK, nullptr};
8619
8620 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
8621 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
8622 return false;
8623
8624 Val = Handler.Value;
8625
8626 // [basic.life]p1:
8627 // The lifetime of an object o of type T ends when [...] the storage
8628 // which the object occupies is [...] reused by an object that is not
8629 // nested within o (6.6.2).
8630 *Val = APValue();
8631 } else {
8632 // Perform the allocation and obtain a pointer to the resulting object.
8633 Val = Info.createHeapAlloc(E, AllocType, Result);
8634 if (!Val)
8635 return false;
8636 }
Richard Smithda1b4342019-09-27 01:26:47 +00008637
8638 if (ResizedArrayILE) {
8639 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
8640 AllocType))
8641 return false;
8642 } else if (Init) {
8643 if (!EvaluateInPlace(*Val, Info, Result, Init))
8644 return false;
8645 } else {
8646 *Val = getDefaultInitValue(AllocType);
8647 }
8648
8649 // Array new returns a pointer to the first element, not a pointer to the
8650 // array.
8651 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
8652 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
8653
8654 return true;
8655}
Chris Lattner05706e882008-07-11 18:11:29 +00008656//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00008657// Member Pointer Evaluation
8658//===----------------------------------------------------------------------===//
8659
8660namespace {
8661class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008662 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00008663 MemberPtr &Result;
8664
8665 bool Success(const ValueDecl *D) {
8666 Result = MemberPtr(D);
8667 return true;
8668 }
8669public:
8670
8671 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
8672 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8673
Richard Smith2e312c82012-03-03 22:46:17 +00008674 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008675 Result.setFrom(V);
8676 return true;
8677 }
Richard Smithfddd3842011-12-30 21:15:51 +00008678 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00008679 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00008680 }
8681
8682 bool VisitCastExpr(const CastExpr *E);
8683 bool VisitUnaryAddrOf(const UnaryOperator *E);
8684};
8685} // end anonymous namespace
8686
8687static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
8688 EvalInfo &Info) {
8689 assert(E->isRValue() && E->getType()->isMemberPointerType());
8690 return MemberPointerExprEvaluator(Info, Result).Visit(E);
8691}
8692
8693bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8694 switch (E->getCastKind()) {
8695 default:
8696 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8697
8698 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00008699 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00008700 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00008701
8702 case CK_BaseToDerivedMemberPointer: {
8703 if (!Visit(E->getSubExpr()))
8704 return false;
8705 if (E->path_empty())
8706 return true;
8707 // Base-to-derived member pointer casts store the path in derived-to-base
8708 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
8709 // the wrong end of the derived->base arc, so stagger the path by one class.
8710 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
8711 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
8712 PathI != PathE; ++PathI) {
8713 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8714 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
8715 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008716 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00008717 }
8718 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
8719 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008720 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00008721 return true;
8722 }
8723
8724 case CK_DerivedToBaseMemberPointer:
8725 if (!Visit(E->getSubExpr()))
8726 return false;
8727 for (CastExpr::path_const_iterator PathI = E->path_begin(),
8728 PathE = E->path_end(); PathI != PathE; ++PathI) {
8729 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8730 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8731 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008732 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00008733 }
8734 return true;
8735 }
8736}
8737
8738bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8739 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
8740 // member can be formed.
8741 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
8742}
8743
8744//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00008745// Record Evaluation
8746//===----------------------------------------------------------------------===//
8747
8748namespace {
8749 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008750 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00008751 const LValue &This;
8752 APValue &Result;
8753 public:
8754
8755 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
8756 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
8757
Richard Smith2e312c82012-03-03 22:46:17 +00008758 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00008759 Result = V;
8760 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00008761 }
Richard Smithb8348f52016-05-12 22:16:28 +00008762 bool ZeroInitialization(const Expr *E) {
8763 return ZeroInitialization(E, E->getType());
8764 }
8765 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00008766
Richard Smith52a980a2015-08-28 02:43:42 +00008767 bool VisitCallExpr(const CallExpr *E) {
8768 return handleCallExpr(E, Result, &This);
8769 }
Richard Smithe97cbd72011-11-11 04:05:33 +00008770 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00008771 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00008772 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8773 return VisitCXXConstructExpr(E, E->getType());
8774 }
Faisal Valic72a08c2017-01-09 03:02:53 +00008775 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00008776 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00008777 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00008778 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008779 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00008780 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008781}
Richard Smithd62306a2011-11-10 06:34:14 +00008782
Richard Smithfddd3842011-12-30 21:15:51 +00008783/// Perform zero-initialization on an object of non-union class type.
8784/// C++11 [dcl.init]p5:
8785/// To zero-initialize an object or reference of type T means:
8786/// [...]
8787/// -- if T is a (possibly cv-qualified) non-union class type,
8788/// each non-static data member and each base-class subobject is
8789/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00008790static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
8791 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00008792 const LValue &This, APValue &Result) {
8793 assert(!RD->isUnion() && "Expected non-union class type");
8794 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
8795 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00008796 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00008797
John McCalld7bca762012-05-01 00:38:49 +00008798 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00008799 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8800
8801 if (CD) {
8802 unsigned Index = 0;
8803 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00008804 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00008805 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
8806 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00008807 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
8808 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00008809 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00008810 Result.getStructBase(Index)))
8811 return false;
8812 }
8813 }
8814
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008815 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00008816 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00008817 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00008818 continue;
8819
8820 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008821 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00008822 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00008823
David Blaikie2d7c57e2012-04-30 02:36:29 +00008824 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00008825 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00008826 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00008827 return false;
8828 }
8829
8830 return true;
8831}
8832
Richard Smithb8348f52016-05-12 22:16:28 +00008833bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
8834 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00008835 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00008836 if (RD->isUnion()) {
8837 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
8838 // object's first non-static named data member is zero-initialized
8839 RecordDecl::field_iterator I = RD->field_begin();
8840 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00008841 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00008842 return true;
8843 }
8844
8845 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00008846 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00008847 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00008848 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00008849 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00008850 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00008851 }
8852
Richard Smith5d108602012-02-17 00:44:16 +00008853 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008854 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00008855 return false;
8856 }
8857
Richard Smitha8105bc2012-01-06 16:39:00 +00008858 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00008859}
8860
Richard Smithe97cbd72011-11-11 04:05:33 +00008861bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
8862 switch (E->getCastKind()) {
8863 default:
8864 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8865
8866 case CK_ConstructorConversion:
8867 return Visit(E->getSubExpr());
8868
8869 case CK_DerivedToBase:
8870 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00008871 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008872 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00008873 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008874 if (!DerivedObject.isStruct())
8875 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00008876
8877 // Derived-to-base rvalue conversion: just slice off the derived part.
8878 APValue *Value = &DerivedObject;
8879 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
8880 for (CastExpr::path_const_iterator PathI = E->path_begin(),
8881 PathE = E->path_end(); PathI != PathE; ++PathI) {
8882 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
8883 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8884 Value = &Value->getStructBase(getBaseIndex(RD, Base));
8885 RD = Base;
8886 }
8887 Result = *Value;
8888 return true;
8889 }
8890 }
8891}
8892
Richard Smithd62306a2011-11-10 06:34:14 +00008893bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00008894 if (E->isTransparent())
8895 return Visit(E->getInit(0));
8896
Richard Smithd62306a2011-11-10 06:34:14 +00008897 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00008898 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008899 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
Richard Smithd3d6f4f2019-05-12 08:57:59 +00008900 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
8901
8902 EvalInfo::EvaluatingConstructorRAII EvalObj(
8903 Info,
8904 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
8905 CXXRD && CXXRD->getNumBases());
Richard Smithd62306a2011-11-10 06:34:14 +00008906
8907 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00008908 const FieldDecl *Field = E->getInitializedFieldInUnion();
8909 Result = APValue(Field);
8910 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00008911 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00008912
8913 // If the initializer list for a union does not contain any elements, the
8914 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00008915 // FIXME: The element should be initialized from an initializer list.
8916 // Is this difference ever observable for initializer lists which
8917 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00008918 ImplicitValueInitExpr VIE(Field->getType());
8919 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
8920
Richard Smithd62306a2011-11-10 06:34:14 +00008921 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00008922 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
8923 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00008924
8925 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
8926 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
8927 isa<CXXDefaultInitExpr>(InitExpr));
8928
Richard Smithb228a862012-02-15 02:18:13 +00008929 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00008930 }
8931
Richard Smithe637cbe2019-05-21 23:15:18 +00008932 if (!Result.hasValue())
Richard Smithc0d04a22016-05-25 22:06:25 +00008933 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
8934 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00008935 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00008936 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00008937
8938 // Initialize base classes.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00008939 if (CXXRD && CXXRD->getNumBases()) {
Richard Smith872307e2016-03-08 22:17:41 +00008940 for (const auto &Base : CXXRD->bases()) {
8941 assert(ElementNo < E->getNumInits() && "missing init for base class");
8942 const Expr *Init = E->getInit(ElementNo);
8943
8944 LValue Subobject = This;
8945 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
8946 return false;
8947
8948 APValue &FieldVal = Result.getStructBase(ElementNo);
8949 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00008950 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00008951 return false;
8952 Success = false;
8953 }
8954 ++ElementNo;
8955 }
Richard Smithd3d6f4f2019-05-12 08:57:59 +00008956
8957 EvalObj.finishedConstructingBases();
Richard Smith872307e2016-03-08 22:17:41 +00008958 }
8959
8960 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008961 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008962 // Anonymous bit-fields are not considered members of the class for
8963 // purposes of aggregate initialization.
8964 if (Field->isUnnamedBitfield())
8965 continue;
8966
8967 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00008968
Richard Smith253c2a32012-01-27 01:14:48 +00008969 bool HaveInit = ElementNo < E->getNumInits();
8970
8971 // FIXME: Diagnostics here should point to the end of the initializer
8972 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00008973 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008974 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00008975 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00008976
8977 // Perform an implicit value-initialization for members beyond the end of
8978 // the initializer list.
8979 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00008980 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00008981
Richard Smith852c9db2013-04-20 22:23:05 +00008982 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
8983 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
8984 isa<CXXDefaultInitExpr>(Init));
8985
Richard Smith49ca8aa2013-08-06 07:09:20 +00008986 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8987 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
8988 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008989 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00008990 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00008991 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00008992 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00008993 }
8994 }
8995
Richard Smith253c2a32012-01-27 01:14:48 +00008996 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00008997}
8998
Richard Smithb8348f52016-05-12 22:16:28 +00008999bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9000 QualType T) {
9001 // Note that E's type is not necessarily the type of our class here; we might
9002 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00009003 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00009004 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9005
Richard Smithfddd3842011-12-30 21:15:51 +00009006 bool ZeroInit = E->requiresZeroInitialization();
9007 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00009008 // If we've already performed zero-initialization, we're already done.
Richard Smithe637cbe2019-05-21 23:15:18 +00009009 if (Result.hasValue())
Richard Smith9eae7232012-01-12 18:54:33 +00009010 return true;
9011
Richard Smithc667cdc2019-09-18 17:37:44 +00009012 if (ZeroInit)
9013 return ZeroInitialization(E, T);
9014
9015 Result = getDefaultInitValue(T);
9016 return true;
Richard Smithcc36f692011-12-22 02:22:31 +00009017 }
9018
Craig Topper36250ad2014-05-12 05:36:57 +00009019 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00009020 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00009021
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00009022 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00009023 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00009024
Richard Smith1bc5c2c2012-01-10 04:32:03 +00009025 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00009026 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00009027 if (const MaterializeTemporaryExpr *ME
9028 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
Tykerb0561b32019-11-17 11:41:55 +01009029 return Visit(ME->getSubExpr());
Richard Smithd62306a2011-11-10 06:34:14 +00009030
Richard Smithb8348f52016-05-12 22:16:28 +00009031 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00009032 return false;
9033
Craig Topper5fc8fc22014-08-27 06:28:36 +00009034 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00009035 return HandleConstructorCall(E, This, Args,
9036 cast<CXXConstructorDecl>(Definition), Info,
9037 Result);
9038}
9039
9040bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9041 const CXXInheritedCtorInitExpr *E) {
9042 if (!Info.CurrentCall) {
9043 assert(Info.checkingPotentialConstantExpression());
9044 return false;
9045 }
9046
9047 const CXXConstructorDecl *FD = E->getConstructor();
9048 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9049 return false;
9050
9051 const FunctionDecl *Definition = nullptr;
9052 auto Body = FD->getBody(Definition);
9053
9054 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9055 return false;
9056
9057 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009058 cast<CXXConstructorDecl>(Definition), Info,
9059 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00009060}
9061
Richard Smithcc1b96d2013-06-12 22:31:48 +00009062bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9063 const CXXStdInitializerListExpr *E) {
9064 const ConstantArrayType *ArrayType =
9065 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9066
9067 LValue Array;
9068 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9069 return false;
9070
9071 // Get a pointer to the first element of the array.
9072 Array.addArray(Info, E, ArrayType);
9073
9074 // FIXME: Perform the checks on the field types in SemaInit.
9075 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9076 RecordDecl::field_iterator Field = Record->field_begin();
9077 if (Field == Record->field_end())
9078 return Error(E);
9079
9080 // Start pointer.
9081 if (!Field->getType()->isPointerType() ||
9082 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9083 ArrayType->getElementType()))
9084 return Error(E);
9085
9086 // FIXME: What if the initializer_list type has base classes, etc?
9087 Result = APValue(APValue::UninitStruct(), 0, 2);
9088 Array.moveInto(Result.getStructField(0));
9089
9090 if (++Field == Record->field_end())
9091 return Error(E);
9092
9093 if (Field->getType()->isPointerType() &&
9094 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9095 ArrayType->getElementType())) {
9096 // End pointer.
9097 if (!HandleLValueArrayAdjustment(Info, E, Array,
9098 ArrayType->getElementType(),
9099 ArrayType->getSize().getZExtValue()))
9100 return false;
9101 Array.moveInto(Result.getStructField(1));
9102 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9103 // Length.
9104 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9105 else
9106 return Error(E);
9107
9108 if (++Field != Record->field_end())
9109 return Error(E);
9110
9111 return true;
9112}
9113
Faisal Valic72a08c2017-01-09 03:02:53 +00009114bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9115 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
Richard Smithda1b4342019-09-27 01:26:47 +00009116 if (ClosureClass->isInvalidDecl())
9117 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009118
Faisal Vali051e3a22017-02-16 04:12:21 +00009119 const size_t NumFields =
9120 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00009121
9122 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9123 E->capture_init_end()) &&
9124 "The number of lambda capture initializers should equal the number of "
9125 "fields within the closure type");
9126
Faisal Vali051e3a22017-02-16 04:12:21 +00009127 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9128 // Iterate through all the lambda's closure object's fields and initialize
9129 // them.
9130 auto *CaptureInitIt = E->capture_init_begin();
9131 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9132 bool Success = true;
9133 for (const auto *Field : ClosureClass->fields()) {
9134 assert(CaptureInitIt != E->capture_init_end());
9135 // Get the initializer for this field
9136 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00009137
Faisal Vali051e3a22017-02-16 04:12:21 +00009138 // If there is no initializer, either this is a VLA or an error has
9139 // occurred.
9140 if (!CurFieldInit)
9141 return Error(E);
9142
9143 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9144 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9145 if (!Info.keepEvaluatingAfterFailure())
9146 return false;
9147 Success = false;
9148 }
9149 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00009150 }
Faisal Vali051e3a22017-02-16 04:12:21 +00009151 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00009152}
9153
Richard Smithd62306a2011-11-10 06:34:14 +00009154static bool EvaluateRecord(const Expr *E, const LValue &This,
9155 APValue &Result, EvalInfo &Info) {
9156 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00009157 "can't evaluate expression as a record rvalue");
9158 return RecordExprEvaluator(Info, This, Result).Visit(E);
9159}
9160
9161//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00009162// Temporary Evaluation
9163//
9164// Temporaries are represented in the AST as rvalues, but generally behave like
9165// lvalues. The full-object of which the temporary is a subobject is implicitly
9166// materialized so that a reference can bind to it.
9167//===----------------------------------------------------------------------===//
9168namespace {
9169class TemporaryExprEvaluator
9170 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9171public:
9172 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00009173 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00009174
9175 /// Visit an expression which constructs the value of this temporary.
9176 bool VisitConstructExpr(const Expr *E) {
Richard Smith457226e2019-09-23 03:48:44 +00009177 APValue &Value =
9178 Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00009179 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00009180 }
9181
9182 bool VisitCastExpr(const CastExpr *E) {
9183 switch (E->getCastKind()) {
9184 default:
9185 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9186
9187 case CK_ConstructorConversion:
9188 return VisitConstructExpr(E->getSubExpr());
9189 }
9190 }
9191 bool VisitInitListExpr(const InitListExpr *E) {
9192 return VisitConstructExpr(E);
9193 }
9194 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9195 return VisitConstructExpr(E);
9196 }
9197 bool VisitCallExpr(const CallExpr *E) {
9198 return VisitConstructExpr(E);
9199 }
Richard Smith513955c2014-12-17 19:24:30 +00009200 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9201 return VisitConstructExpr(E);
9202 }
Faisal Valic72a08c2017-01-09 03:02:53 +00009203 bool VisitLambdaExpr(const LambdaExpr *E) {
9204 return VisitConstructExpr(E);
9205 }
Richard Smith027bf112011-11-17 22:56:20 +00009206};
9207} // end anonymous namespace
9208
9209/// Evaluate an expression of record type as a temporary.
9210static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00009211 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00009212 return TemporaryExprEvaluator(Info, Result).Visit(E);
9213}
9214
9215//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009216// Vector Evaluation
9217//===----------------------------------------------------------------------===//
9218
9219namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009220 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009221 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00009222 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009223 public:
Mike Stump11289f42009-09-09 15:08:12 +00009224
Richard Smith2d406342011-10-22 21:10:00 +00009225 VectorExprEvaluator(EvalInfo &info, APValue &Result)
9226 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00009227
Craig Topper9798b932015-09-29 04:30:05 +00009228 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00009229 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
9230 // FIXME: remove this APValue copy.
9231 Result = APValue(V.data(), V.size());
9232 return true;
9233 }
Richard Smith2e312c82012-03-03 22:46:17 +00009234 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00009235 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00009236 Result = V;
9237 return true;
9238 }
Richard Smithfddd3842011-12-30 21:15:51 +00009239 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00009240
Richard Smith2d406342011-10-22 21:10:00 +00009241 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00009242 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00009243 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00009244 bool VisitInitListExpr(const InitListExpr *E);
9245 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00009246 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00009247 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00009248 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009249 };
9250} // end anonymous namespace
9251
9252static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009253 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00009254 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009255}
9256
George Burgess IV533ff002015-12-11 00:23:35 +00009257bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00009258 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00009259 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00009260
Richard Smith161f09a2011-12-06 22:44:34 +00009261 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00009262 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009263
Eli Friedmanc757de22011-03-25 00:43:55 +00009264 switch (E->getCastKind()) {
9265 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00009266 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00009267 if (SETy->isIntegerType()) {
9268 APSInt IntResult;
9269 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00009270 return false;
9271 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00009272 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00009273 APFloat FloatResult(0.0);
9274 if (!EvaluateFloat(SE, FloatResult, Info))
9275 return false;
9276 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00009277 } else {
Richard Smith2d406342011-10-22 21:10:00 +00009278 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009279 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00009280
9281 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00009282 SmallVector<APValue, 4> Elts(NElts, Val);
9283 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00009284 }
Eli Friedman803acb32011-12-22 03:51:45 +00009285 case CK_BitCast: {
9286 // Evaluate the operand into an APInt we can extract from.
9287 llvm::APInt SValInt;
9288 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
9289 return false;
9290 // Extract the elements
9291 QualType EltTy = VTy->getElementType();
9292 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
9293 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
9294 SmallVector<APValue, 4> Elts;
9295 if (EltTy->isRealFloatingType()) {
9296 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00009297 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00009298 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00009299 FloatEltSize = 80;
9300 for (unsigned i = 0; i < NElts; i++) {
9301 llvm::APInt Elt;
9302 if (BigEndian)
9303 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
9304 else
9305 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00009306 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00009307 }
9308 } else if (EltTy->isIntegerType()) {
9309 for (unsigned i = 0; i < NElts; i++) {
9310 llvm::APInt Elt;
9311 if (BigEndian)
9312 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
9313 else
9314 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
9315 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
9316 }
9317 } else {
9318 return Error(E);
9319 }
9320 return Success(Elts, E);
9321 }
Eli Friedmanc757de22011-03-25 00:43:55 +00009322 default:
Richard Smith11562c52011-10-28 17:51:58 +00009323 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009324 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009325}
9326
Richard Smith2d406342011-10-22 21:10:00 +00009327bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009328VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00009329 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009330 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00009331 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00009332
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009333 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009334 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009335
Eli Friedmanb9c71292012-01-03 23:24:20 +00009336 // The number of initializers can be less than the number of
9337 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00009338 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00009339 // should be initialized with zeroes.
9340 unsigned CountInits = 0, CountElts = 0;
9341 while (CountElts < NumElements) {
9342 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00009343 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00009344 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00009345 APValue v;
9346 if (!EvaluateVector(E->getInit(CountInits), v, Info))
9347 return Error(E);
9348 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00009349 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00009350 Elements.push_back(v.getVectorElt(j));
9351 CountElts += vlen;
9352 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009353 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00009354 if (CountInits < NumInits) {
9355 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00009356 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00009357 } else // trailing integer zero.
9358 sInt = Info.Ctx.MakeIntValue(0, EltTy);
9359 Elements.push_back(APValue(sInt));
9360 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009361 } else {
9362 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00009363 if (CountInits < NumInits) {
9364 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00009365 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00009366 } else // trailing float zero.
9367 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9368 Elements.push_back(APValue(f));
9369 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00009370 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00009371 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009372 }
Richard Smith2d406342011-10-22 21:10:00 +00009373 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009374}
9375
Richard Smith2d406342011-10-22 21:10:00 +00009376bool
Richard Smithfddd3842011-12-30 21:15:51 +00009377VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Simon Pilgrimc15b38e2019-10-03 15:08:30 +00009378 const auto *VT = E->getType()->castAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00009379 QualType EltTy = VT->getElementType();
9380 APValue ZeroElement;
9381 if (EltTy->isIntegerType())
9382 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9383 else
9384 ZeroElement =
9385 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9386
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009387 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00009388 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00009389}
9390
Richard Smith2d406342011-10-22 21:10:00 +00009391bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00009392 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00009393 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00009394}
9395
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009396//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00009397// Array Evaluation
9398//===----------------------------------------------------------------------===//
9399
9400namespace {
9401 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009402 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00009403 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00009404 APValue &Result;
9405 public:
9406
Richard Smithd62306a2011-11-10 06:34:14 +00009407 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9408 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00009409
9410 bool Success(const APValue &V, const Expr *E) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00009411 assert(V.isArray() && "expected array");
Richard Smithf3e9e432011-11-07 09:22:26 +00009412 Result = V;
9413 return true;
9414 }
Richard Smithf3e9e432011-11-07 09:22:26 +00009415
Richard Smithfddd3842011-12-30 21:15:51 +00009416 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00009417 const ConstantArrayType *CAT =
9418 Info.Ctx.getAsConstantArrayType(E->getType());
9419 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009420 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00009421
9422 Result = APValue(APValue::UninitArray(), 0,
9423 CAT->getSize().getZExtValue());
9424 if (!Result.hasArrayFiller()) return true;
9425
Richard Smithfddd3842011-12-30 21:15:51 +00009426 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00009427 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00009428 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00009429 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00009430 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00009431 }
9432
Richard Smith52a980a2015-08-28 02:43:42 +00009433 bool VisitCallExpr(const CallExpr *E) {
9434 return handleCallExpr(E, Result, &This);
9435 }
Richard Smithda1b4342019-09-27 01:26:47 +00009436 bool VisitInitListExpr(const InitListExpr *E,
9437 QualType AllocType = QualType());
Richard Smith410306b2016-12-12 02:53:20 +00009438 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00009439 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00009440 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
9441 const LValue &Subobject,
9442 APValue *Value, QualType Type);
Richard Smithda1b4342019-09-27 01:26:47 +00009443 bool VisitStringLiteral(const StringLiteral *E,
9444 QualType AllocType = QualType()) {
9445 expandStringLiteral(Info, E, Result, AllocType);
Eli Friedman3bf72d72019-02-08 21:18:46 +00009446 return true;
9447 }
Richard Smithf3e9e432011-11-07 09:22:26 +00009448 };
9449} // end anonymous namespace
9450
Richard Smithd62306a2011-11-10 06:34:14 +00009451static bool EvaluateArray(const Expr *E, const LValue &This,
9452 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00009453 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00009454 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00009455}
9456
Richard Smithda1b4342019-09-27 01:26:47 +00009457static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9458 APValue &Result, const InitListExpr *ILE,
9459 QualType AllocType) {
9460 assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
9461 "not an array rvalue");
9462 return ArrayExprEvaluator(Info, This, Result)
9463 .VisitInitListExpr(ILE, AllocType);
9464}
9465
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00009466// Return true iff the given array filler may depend on the element index.
9467static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
9468 // For now, just whitelist non-class value-initialization and initialization
9469 // lists comprised of them.
9470 if (isa<ImplicitValueInitExpr>(FillerExpr))
9471 return false;
9472 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
9473 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
9474 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
9475 return true;
9476 }
9477 return false;
9478 }
9479 return true;
9480}
9481
Richard Smithda1b4342019-09-27 01:26:47 +00009482bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
9483 QualType AllocType) {
9484 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
9485 AllocType.isNull() ? E->getType() : AllocType);
Richard Smithf3e9e432011-11-07 09:22:26 +00009486 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009487 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00009488
Richard Smithca2cfbf2011-12-22 01:07:19 +00009489 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
9490 // an appropriately-typed string literal enclosed in braces.
Richard Smithda1b4342019-09-27 01:26:47 +00009491 if (E->isStringLiteralInit()) {
9492 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
9493 // FIXME: Support ObjCEncodeExpr here once we support it in
9494 // ArrayExprEvaluator generally.
9495 if (!SL)
9496 return Error(E);
9497 return VisitStringLiteral(SL, AllocType);
9498 }
Richard Smithca2cfbf2011-12-22 01:07:19 +00009499
Richard Smith253c2a32012-01-27 01:14:48 +00009500 bool Success = true;
9501
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009502 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
9503 "zero-initialized array shouldn't have any initialized elts");
9504 APValue Filler;
9505 if (Result.isArray() && Result.hasArrayFiller())
9506 Filler = Result.getArrayFiller();
9507
Richard Smith9543c5e2013-04-22 14:44:29 +00009508 unsigned NumEltsToInit = E->getNumInits();
9509 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00009510 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00009511
9512 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00009513 // array element.
9514 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00009515 NumEltsToInit = NumElts;
9516
Nicola Zaghen3538b392018-05-15 13:30:56 +00009517 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
9518 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00009519
Richard Smith9543c5e2013-04-22 14:44:29 +00009520 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009521
9522 // If the array was previously zero-initialized, preserve the
9523 // zero-initialized values.
Richard Smithe637cbe2019-05-21 23:15:18 +00009524 if (Filler.hasValue()) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009525 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
9526 Result.getArrayInitializedElt(I) = Filler;
9527 if (Result.hasArrayFiller())
9528 Result.getArrayFiller() = Filler;
9529 }
9530
Richard Smithd62306a2011-11-10 06:34:14 +00009531 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00009532 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00009533 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
9534 const Expr *Init =
9535 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00009536 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00009537 Info, Subobject, Init) ||
9538 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00009539 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00009540 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00009541 return false;
9542 Success = false;
9543 }
Richard Smithd62306a2011-11-10 06:34:14 +00009544 }
Richard Smithf3e9e432011-11-07 09:22:26 +00009545
Richard Smith9543c5e2013-04-22 14:44:29 +00009546 if (!Result.hasArrayFiller())
9547 return Success;
9548
9549 // If we get here, we have a trivial filler, which we can just evaluate
9550 // once and splat over the rest of the array elements.
9551 assert(FillerExpr && "no array filler for incomplete init list");
9552 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
9553 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00009554}
9555
Richard Smith410306b2016-12-12 02:53:20 +00009556bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
Richard Smith457226e2019-09-23 03:48:44 +00009557 LValue CommonLV;
Richard Smith410306b2016-12-12 02:53:20 +00009558 if (E->getCommonExpr() &&
Richard Smith457226e2019-09-23 03:48:44 +00009559 !Evaluate(Info.CurrentCall->createTemporary(
9560 E->getCommonExpr(),
9561 getStorageType(Info.Ctx, E->getCommonExpr()), false,
9562 CommonLV),
Richard Smith410306b2016-12-12 02:53:20 +00009563 Info, E->getCommonExpr()->getSourceExpr()))
9564 return false;
9565
9566 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
9567
9568 uint64_t Elements = CAT->getSize().getZExtValue();
9569 Result = APValue(APValue::UninitArray(), Elements, Elements);
9570
9571 LValue Subobject = This;
9572 Subobject.addArray(Info, E, CAT);
9573
9574 bool Success = true;
9575 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
9576 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9577 Info, Subobject, E->getSubExpr()) ||
9578 !HandleLValueArrayAdjustment(Info, E, Subobject,
9579 CAT->getElementType(), 1)) {
9580 if (!Info.noteFailure())
9581 return false;
9582 Success = false;
9583 }
9584 }
9585
9586 return Success;
9587}
9588
Richard Smith027bf112011-11-17 22:56:20 +00009589bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00009590 return VisitCXXConstructExpr(E, This, &Result, E->getType());
9591}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009592
Richard Smith9543c5e2013-04-22 14:44:29 +00009593bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9594 const LValue &Subobject,
9595 APValue *Value,
9596 QualType Type) {
Richard Smithe637cbe2019-05-21 23:15:18 +00009597 bool HadZeroInit = Value->hasValue();
Richard Smith9543c5e2013-04-22 14:44:29 +00009598
9599 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
9600 unsigned N = CAT->getSize().getZExtValue();
9601
9602 // Preserve the array filler if we had prior zero-initialization.
9603 APValue Filler =
9604 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
9605 : APValue();
9606
9607 *Value = APValue(APValue::UninitArray(), N, N);
9608
9609 if (HadZeroInit)
9610 for (unsigned I = 0; I != N; ++I)
9611 Value->getArrayInitializedElt(I) = Filler;
9612
9613 // Initialize the elements.
9614 LValue ArrayElt = Subobject;
9615 ArrayElt.addArray(Info, E, CAT);
9616 for (unsigned I = 0; I != N; ++I)
9617 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
9618 CAT->getElementType()) ||
9619 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
9620 CAT->getElementType(), 1))
9621 return false;
9622
9623 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00009624 }
Richard Smith027bf112011-11-17 22:56:20 +00009625
Richard Smith9543c5e2013-04-22 14:44:29 +00009626 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00009627 return Error(E);
9628
Richard Smithb8348f52016-05-12 22:16:28 +00009629 return RecordExprEvaluator(Info, Subobject, *Value)
9630 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00009631}
9632
Richard Smithf3e9e432011-11-07 09:22:26 +00009633//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00009634// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00009635//
9636// As a GNU extension, we support casting pointers to sufficiently-wide integer
9637// types and back in constant folding. Integer values are thus represented
9638// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00009639//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00009640
9641namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009642class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009643 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00009644 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00009645public:
Richard Smith2e312c82012-03-03 22:46:17 +00009646 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009647 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00009648
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009649 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009650 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00009651 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009652 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009653 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009654 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009655 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00009656 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009657 return true;
9658 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009659 bool Success(const llvm::APSInt &SI, const Expr *E) {
9660 return Success(SI, E, Result);
9661 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009662
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009663 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00009664 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00009665 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009666 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00009667 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00009668 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00009669 Result.getInt().setIsUnsigned(
9670 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009671 return true;
9672 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009673 bool Success(const llvm::APInt &I, const Expr *E) {
9674 return Success(I, E, Result);
9675 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009676
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009677 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009678 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00009679 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00009680 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009681 return true;
9682 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009683 bool Success(uint64_t Value, const Expr *E) {
9684 return Success(Value, E, Result);
9685 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009686
Ken Dyckdbc01912011-03-11 02:13:43 +00009687 bool Success(CharUnits Size, const Expr *E) {
9688 return Success(Size.getQuantity(), E);
9689 }
9690
Richard Smith2e312c82012-03-03 22:46:17 +00009691 bool Success(const APValue &V, const Expr *E) {
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00009692 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00009693 Result = V;
9694 return true;
9695 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009696 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00009697 }
Mike Stump11289f42009-09-09 15:08:12 +00009698
Richard Smithfddd3842011-12-30 21:15:51 +00009699 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00009700
Peter Collingbournee9200682011-05-13 03:29:01 +00009701 //===--------------------------------------------------------------------===//
9702 // Visitor Methods
9703 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00009704
Fangrui Song407659a2018-11-30 23:41:18 +00009705 bool VisitConstantExpr(const ConstantExpr *E);
9706
Chris Lattner7174bf32008-07-12 00:38:25 +00009707 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009708 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00009709 }
9710 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009711 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00009712 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009713
9714 bool CheckReferencedDecl(const Expr *E, const Decl *D);
9715 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009716 if (CheckReferencedDecl(E, E->getDecl()))
9717 return true;
9718
9719 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009720 }
9721 bool VisitMemberExpr(const MemberExpr *E) {
9722 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00009723 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009724 return true;
9725 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009726
9727 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009728 }
9729
Peter Collingbournee9200682011-05-13 03:29:01 +00009730 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00009731 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00009732 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00009733 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00009734 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00009735
Peter Collingbournee9200682011-05-13 03:29:01 +00009736 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009737 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00009738
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009739 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009740 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009741 }
Mike Stump11289f42009-09-09 15:08:12 +00009742
Ted Kremeneke65b0862012-03-06 20:05:56 +00009743 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
9744 return Success(E->getValue(), E);
9745 }
Richard Smith410306b2016-12-12 02:53:20 +00009746
9747 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
9748 if (Info.ArrayInitIndex == uint64_t(-1)) {
9749 // We were asked to evaluate this subexpression independent of the
9750 // enclosing ArrayInitLoopExpr. We can't do that.
9751 Info.FFDiag(E);
9752 return false;
9753 }
9754 return Success(Info.ArrayInitIndex, E);
9755 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009756
Richard Smith4ce706a2011-10-11 21:43:33 +00009757 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00009758 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00009759 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00009760 }
9761
Douglas Gregor29c42f22012-02-24 07:38:34 +00009762 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
9763 return Success(E->getValue(), E);
9764 }
9765
John Wiegley6242b6a2011-04-28 00:16:57 +00009766 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
9767 return Success(E->getValue(), E);
9768 }
9769
John Wiegleyf9f65842011-04-25 06:54:41 +00009770 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
9771 return Success(E->getValue(), E);
9772 }
9773
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009774 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00009775 bool VisitUnaryImag(const UnaryOperator *E);
9776
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009777 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009778 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Eric Fiselier708afb52019-05-16 21:04:15 +00009779 bool VisitSourceLocExpr(const SourceLocExpr *E);
Saar Raz5d98ba62019-10-15 15:24:26 +00009780 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00009781 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00009782};
Leonard Chandb01c3a2018-06-20 17:19:40 +00009783
9784class FixedPointExprEvaluator
9785 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
9786 APValue &Result;
9787
9788 public:
9789 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
9790 : ExprEvaluatorBaseTy(info), Result(result) {}
9791
Leonard Chandb01c3a2018-06-20 17:19:40 +00009792 bool Success(const llvm::APInt &I, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00009793 return Success(
9794 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009795 }
9796
Leonard Chandb01c3a2018-06-20 17:19:40 +00009797 bool Success(uint64_t Value, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00009798 return Success(
9799 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009800 }
9801
9802 bool Success(const APValue &V, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00009803 return Success(V.getFixedPoint(), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009804 }
9805
Leonard Chand3f3e162019-01-18 21:04:25 +00009806 bool Success(const APFixedPoint &V, const Expr *E) {
9807 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
9808 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9809 "Invalid evaluation result.");
9810 Result = APValue(V);
9811 return true;
9812 }
Leonard Chandb01c3a2018-06-20 17:19:40 +00009813
9814 //===--------------------------------------------------------------------===//
9815 // Visitor Methods
9816 //===--------------------------------------------------------------------===//
9817
9818 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
9819 return Success(E->getValue(), E);
9820 }
9821
Leonard Chand3f3e162019-01-18 21:04:25 +00009822 bool VisitCastExpr(const CastExpr *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009823 bool VisitUnaryOperator(const UnaryOperator *E);
Leonard Chand3f3e162019-01-18 21:04:25 +00009824 bool VisitBinaryOperator(const BinaryOperator *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009825};
Chris Lattner05706e882008-07-11 18:11:29 +00009826} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009827
Richard Smith11562c52011-10-28 17:51:58 +00009828/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
9829/// produce either the integer value or a pointer.
9830///
9831/// GCC has a heinous extension which folds casts between pointer types and
9832/// pointer-sized integral types. We support this by allowing the evaluation of
9833/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
9834/// Some simple arithmetic on such values is supported (they are treated much
9835/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00009836static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00009837 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009838 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009839 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00009840}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009841
Richard Smithf57d8cb2011-12-09 22:58:01 +00009842static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00009843 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009844 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00009845 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009846 if (!Val.isInt()) {
9847 // FIXME: It would be better to produce the diagnostic for casting
9848 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00009849 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009850 return false;
9851 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009852 Result = Val.getInt();
9853 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009854}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009855
Eric Fiselier708afb52019-05-16 21:04:15 +00009856bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
9857 APValue Evaluated = E->EvaluateInContext(
9858 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9859 return Success(Evaluated, E);
9860}
9861
Leonard Chand3f3e162019-01-18 21:04:25 +00009862static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
9863 EvalInfo &Info) {
9864 if (E->getType()->isFixedPointType()) {
9865 APValue Val;
9866 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
9867 return false;
9868 if (!Val.isFixedPoint())
9869 return false;
9870
9871 Result = Val.getFixedPoint();
9872 return true;
9873 }
9874 return false;
9875}
9876
9877static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
9878 EvalInfo &Info) {
9879 if (E->getType()->isIntegerType()) {
9880 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
9881 APSInt Val;
9882 if (!EvaluateInteger(E, Val, Info))
9883 return false;
9884 Result = APFixedPoint(Val, FXSema);
9885 return true;
9886 } else if (E->getType()->isFixedPointType()) {
9887 return EvaluateFixedPoint(E, Result, Info);
9888 }
9889 return false;
9890}
9891
Richard Smithf57d8cb2011-12-09 22:58:01 +00009892/// Check whether the given declaration can be directly converted to an integral
9893/// rvalue. If not, no diagnostic is produced; there are other things we can
9894/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00009895bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00009896 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00009897 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00009898 // Check for signedness/width mismatches between E type and ECD value.
9899 bool SameSign = (ECD->getInitVal().isSigned()
9900 == E->getType()->isSignedIntegerOrEnumerationType());
9901 bool SameWidth = (ECD->getInitVal().getBitWidth()
9902 == Info.Ctx.getIntWidth(E->getType()));
9903 if (SameSign && SameWidth)
9904 return Success(ECD->getInitVal(), E);
9905 else {
9906 // Get rid of mismatch (otherwise Success assertions will fail)
9907 // by computing a new value matching the type of E.
9908 llvm::APSInt Val = ECD->getInitVal();
9909 if (!SameSign)
9910 Val.setIsSigned(!ECD->getInitVal().isSigned());
9911 if (!SameWidth)
9912 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
9913 return Success(Val, E);
9914 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00009915 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009916 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00009917}
9918
Richard Smith08b682b2018-05-23 21:18:00 +00009919/// Values returned by __builtin_classify_type, chosen to match the values
9920/// produced by GCC's builtin.
9921enum class GCCTypeClass {
9922 None = -1,
9923 Void = 0,
9924 Integer = 1,
9925 // GCC reserves 2 for character types, but instead classifies them as
9926 // integers.
9927 Enum = 3,
9928 Bool = 4,
9929 Pointer = 5,
9930 // GCC reserves 6 for references, but appears to never use it (because
9931 // expressions never have reference type, presumably).
9932 PointerToDataMember = 7,
9933 RealFloat = 8,
9934 Complex = 9,
9935 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
9936 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
9937 // GCC claims to reserve 11 for pointers to member functions, but *actually*
9938 // uses 12 for that purpose, same as for a class or struct. Maybe it
9939 // internally implements a pointer to member as a struct? Who knows.
9940 PointerToMemberFunction = 12, // Not a bug, see above.
9941 ClassOrStruct = 12,
9942 Union = 13,
9943 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
9944 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
9945 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
9946 // literals.
9947};
9948
Chris Lattner86ee2862008-10-06 06:40:35 +00009949/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9950/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00009951static GCCTypeClass
9952EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
9953 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00009954
Richard Smith08b682b2018-05-23 21:18:00 +00009955 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009956 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
9957
9958 switch (CanTy->getTypeClass()) {
9959#define TYPE(ID, BASE)
9960#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
9961#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
9962#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
John McCall36b12a82019-10-02 06:35:23 +00009963#include "clang/AST/TypeNodes.inc"
Richard Smith08b682b2018-05-23 21:18:00 +00009964 case Type::Auto:
9965 case Type::DeducedTemplateSpecialization:
9966 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009967
9968 case Type::Builtin:
9969 switch (BT->getKind()) {
9970#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00009971#define SIGNED_TYPE(ID, SINGLETON_ID) \
9972 case BuiltinType::ID: return GCCTypeClass::Integer;
9973#define FLOATING_TYPE(ID, SINGLETON_ID) \
9974 case BuiltinType::ID: return GCCTypeClass::RealFloat;
9975#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
9976 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009977#include "clang/AST/BuiltinTypes.def"
9978 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00009979 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009980
9981 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00009982 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009983
Richard Smith08b682b2018-05-23 21:18:00 +00009984 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009985 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00009986 case BuiltinType::WChar_U:
9987 case BuiltinType::Char8:
9988 case BuiltinType::Char16:
9989 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009990 case BuiltinType::UShort:
9991 case BuiltinType::UInt:
9992 case BuiltinType::ULong:
9993 case BuiltinType::ULongLong:
9994 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00009995 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009996
Leonard Chanf921d852018-06-04 16:07:52 +00009997 case BuiltinType::UShortAccum:
9998 case BuiltinType::UAccum:
9999 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +000010000 case BuiltinType::UShortFract:
10001 case BuiltinType::UFract:
10002 case BuiltinType::ULongFract:
10003 case BuiltinType::SatUShortAccum:
10004 case BuiltinType::SatUAccum:
10005 case BuiltinType::SatULongAccum:
10006 case BuiltinType::SatUShortFract:
10007 case BuiltinType::SatUFract:
10008 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +000010009 return GCCTypeClass::None;
10010
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010011 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010012
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010013 case BuiltinType::ObjCId:
10014 case BuiltinType::ObjCClass:
10015 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +000010016#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10017 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +000010018#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +000010019#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10020 case BuiltinType::Id:
10021#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010022 case BuiltinType::OCLSampler:
10023 case BuiltinType::OCLEvent:
10024 case BuiltinType::OCLClkEvent:
10025 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010026 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +000010027#define SVE_TYPE(Name, Id, SingletonId) \
10028 case BuiltinType::Id:
10029#include "clang/Basic/AArch64SVEACLETypes.def"
Richard Smith08b682b2018-05-23 21:18:00 +000010030 return GCCTypeClass::None;
10031
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010032 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +000010033 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010034 };
Richard Smith08b682b2018-05-23 21:18:00 +000010035 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010036
10037 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +000010038 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010039
10040 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010041 case Type::ConstantArray:
10042 case Type::VariableArray:
10043 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +000010044 case Type::FunctionNoProto:
10045 case Type::FunctionProto:
10046 return GCCTypeClass::Pointer;
10047
10048 case Type::MemberPointer:
10049 return CanTy->isMemberDataPointerType()
10050 ? GCCTypeClass::PointerToDataMember
10051 : GCCTypeClass::PointerToMemberFunction;
10052
10053 case Type::Complex:
10054 return GCCTypeClass::Complex;
10055
10056 case Type::Record:
10057 return CanTy->isUnionType() ? GCCTypeClass::Union
10058 : GCCTypeClass::ClassOrStruct;
10059
10060 case Type::Atomic:
10061 // GCC classifies _Atomic T the same as T.
10062 return EvaluateBuiltinClassifyType(
10063 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010064
10065 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010066 case Type::Vector:
10067 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010068 case Type::ObjCObject:
10069 case Type::ObjCInterface:
10070 case Type::ObjCObjectPointer:
10071 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +000010072 // GCC classifies vectors as None. We follow its lead and classify all
10073 // other types that don't fit into the regular classification the same way.
10074 return GCCTypeClass::None;
10075
10076 case Type::LValueReference:
10077 case Type::RValueReference:
10078 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +000010079 }
10080
Richard Smith08b682b2018-05-23 21:18:00 +000010081 llvm_unreachable("unexpected type class");
10082}
10083
10084/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10085/// as GCC.
10086static GCCTypeClass
10087EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10088 // If no argument was supplied, default to None. This isn't
10089 // ideal, however it is what gcc does.
10090 if (E->getNumArgs() == 0)
10091 return GCCTypeClass::None;
10092
10093 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10094 // being an ICE, but still folds it to a constant using the type of the first
10095 // argument.
10096 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +000010097}
10098
Richard Smith5fab0c92011-12-28 19:48:30 +000010099/// EvaluateBuiltinConstantPForLValue - Determine the result of
Richard Smith31cfb312019-04-27 02:58:17 +000010100/// __builtin_constant_p when applied to the given pointer.
Richard Smith5fab0c92011-12-28 19:48:30 +000010101///
Richard Smith31cfb312019-04-27 02:58:17 +000010102/// A pointer is only "constant" if it is null (or a pointer cast to integer)
10103/// or it points to the first character of a string literal.
10104static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10105 APValue::LValueBase Base = LV.getLValueBase();
10106 if (Base.isNull()) {
10107 // A null base is acceptable.
10108 return true;
10109 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10110 if (!isa<StringLiteral>(E))
10111 return false;
10112 return LV.getLValueOffset().isZero();
Richard Smithee0ce3022019-05-17 07:06:46 +000010113 } else if (Base.is<TypeInfoLValue>()) {
10114 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10115 // evaluate to true.
10116 return true;
Richard Smith31cfb312019-04-27 02:58:17 +000010117 } else {
10118 // Any other base is not constant enough for GCC.
10119 return false;
10120 }
Richard Smith5fab0c92011-12-28 19:48:30 +000010121}
10122
10123/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10124/// GCC as we can manage.
Richard Smith31cfb312019-04-27 02:58:17 +000010125static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
Richard Smith37be3362019-05-04 04:00:45 +000010126 // This evaluation is not permitted to have side-effects, so evaluate it in
10127 // a speculative evaluation context.
10128 SpeculativeEvaluationRAII SpeculativeEval(Info);
10129
Richard Smith31cfb312019-04-27 02:58:17 +000010130 // Constant-folding is always enabled for the operand of __builtin_constant_p
10131 // (even when the enclosing evaluation context otherwise requires a strict
10132 // language-specific constant expression).
10133 FoldConstant Fold(Info, true);
10134
Richard Smith5fab0c92011-12-28 19:48:30 +000010135 QualType ArgType = Arg->getType();
10136
10137 // __builtin_constant_p always has one operand. The rules which gcc follows
10138 // are not precisely documented, but are as follows:
10139 //
10140 // - If the operand is of integral, floating, complex or enumeration type,
10141 // and can be folded to a known value of that type, it returns 1.
Richard Smith31cfb312019-04-27 02:58:17 +000010142 // - If the operand can be folded to a pointer to the first character
10143 // of a string literal (or such a pointer cast to an integral type)
10144 // or to a null pointer or an integer cast to a pointer, it returns 1.
Richard Smith5fab0c92011-12-28 19:48:30 +000010145 //
10146 // Otherwise, it returns 0.
10147 //
10148 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
Richard Smith31cfb312019-04-27 02:58:17 +000010149 // its support for this did not work prior to GCC 9 and is not yet well
10150 // understood.
10151 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10152 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10153 ArgType->isNullPtrType()) {
10154 APValue V;
10155 if (!::EvaluateAsRValue(Info, Arg, V)) {
10156 Fold.keepDiagnostics();
Richard Smith5fab0c92011-12-28 19:48:30 +000010157 return false;
Richard Smith31cfb312019-04-27 02:58:17 +000010158 }
Richard Smith5fab0c92011-12-28 19:48:30 +000010159
Richard Smith31cfb312019-04-27 02:58:17 +000010160 // For a pointer (possibly cast to integer), there are special rules.
Richard Smith0c6124b2015-12-03 01:36:22 +000010161 if (V.getKind() == APValue::LValue)
10162 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith31cfb312019-04-27 02:58:17 +000010163
10164 // Otherwise, any constant value is good enough.
Richard Smithe637cbe2019-05-21 23:15:18 +000010165 return V.hasValue();
Richard Smith5fab0c92011-12-28 19:48:30 +000010166 }
10167
10168 // Anything else isn't considered to be sufficiently constant.
10169 return false;
10170}
10171
John McCall95007602010-05-10 23:27:23 +000010172/// Retrieves the "underlying object type" of the given expression,
10173/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +000010174static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000010175 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
10176 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +000010177 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000010178 } else if (const Expr *E = B.get<const Expr*>()) {
10179 if (isa<CompoundLiteralExpr>(E))
10180 return E->getType();
Richard Smithee0ce3022019-05-17 07:06:46 +000010181 } else if (B.is<TypeInfoLValue>()) {
10182 return B.getTypeInfoType();
Richard Smithda1b4342019-09-27 01:26:47 +000010183 } else if (B.is<DynamicAllocLValue>()) {
10184 return B.getDynamicAllocType();
John McCall95007602010-05-10 23:27:23 +000010185 }
10186
10187 return QualType();
10188}
10189
George Burgess IV3a03fab2015-09-04 21:28:13 +000010190/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +000010191/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +000010192/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +000010193/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
10194///
10195/// Always returns an RValue with a pointer representation.
10196static const Expr *ignorePointerCastsAndParens(const Expr *E) {
10197 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
10198
10199 auto *NoParens = E->IgnoreParens();
10200 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +000010201 if (Cast == nullptr)
10202 return NoParens;
10203
10204 // We only conservatively allow a few kinds of casts, because this code is
10205 // inherently a simple solution that seeks to support the common case.
10206 auto CastKind = Cast->getCastKind();
10207 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
10208 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +000010209 return NoParens;
10210
10211 auto *SubExpr = Cast->getSubExpr();
10212 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
10213 return NoParens;
10214 return ignorePointerCastsAndParens(SubExpr);
10215}
10216
George Burgess IVa51c4072015-10-16 01:49:01 +000010217/// Checks to see if the given LValue's Designator is at the end of the LValue's
10218/// record layout. e.g.
10219/// struct { struct { int a, b; } fst, snd; } obj;
10220/// obj.fst // no
10221/// obj.snd // yes
10222/// obj.fst.a // no
10223/// obj.fst.b // no
10224/// obj.snd.a // no
10225/// obj.snd.b // yes
10226///
10227/// Please note: this function is specialized for how __builtin_object_size
10228/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +000010229///
Richard Smith6f4f0f12017-10-20 22:56:25 +000010230/// If this encounters an invalid RecordDecl or otherwise cannot determine the
10231/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +000010232static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
10233 assert(!LVal.Designator.Invalid);
10234
George Burgess IV4168d752016-06-27 19:40:41 +000010235 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
10236 const RecordDecl *Parent = FD->getParent();
10237 Invalid = Parent->isInvalidDecl();
10238 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +000010239 return true;
George Burgess IV4168d752016-06-27 19:40:41 +000010240 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +000010241 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
10242 };
10243
10244 auto &Base = LVal.getLValueBase();
10245 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
10246 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +000010247 bool Invalid;
10248 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10249 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +000010250 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +000010251 for (auto *FD : IFD->chain()) {
10252 bool Invalid;
10253 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
10254 return Invalid;
10255 }
George Burgess IVa51c4072015-10-16 01:49:01 +000010256 }
10257 }
10258
George Burgess IVe3763372016-12-22 02:50:20 +000010259 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +000010260 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +000010261 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000010262 // If we don't know the array bound, conservatively assume we're looking at
10263 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +000010264 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +000010265 if (BaseType->isIncompleteArrayType())
10266 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
10267 else
10268 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +000010269 }
10270
10271 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
10272 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +000010273 if (BaseType->isArrayType()) {
10274 // Because __builtin_object_size treats arrays as objects, we can ignore
10275 // the index iff this is the last array in the Designator.
10276 if (I + 1 == E)
10277 return true;
George Burgess IVe3763372016-12-22 02:50:20 +000010278 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
Richard Smith5b5e27a2019-05-10 20:05:31 +000010279 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +000010280 if (Index + 1 != CAT->getSize())
10281 return false;
10282 BaseType = CAT->getElementType();
10283 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +000010284 const auto *CT = BaseType->castAs<ComplexType>();
Richard Smith5b5e27a2019-05-10 20:05:31 +000010285 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +000010286 if (Index != 1)
10287 return false;
10288 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +000010289 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +000010290 bool Invalid;
10291 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10292 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +000010293 BaseType = FD->getType();
10294 } else {
George Burgess IVe3763372016-12-22 02:50:20 +000010295 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +000010296 return false;
10297 }
10298 }
10299 return true;
10300}
10301
George Burgess IVe3763372016-12-22 02:50:20 +000010302/// Tests to see if the LValue has a user-specified designator (that isn't
10303/// necessarily valid). Note that this always returns 'true' if the LValue has
10304/// an unsized array as its first designator entry, because there's currently no
10305/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +000010306static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +000010307 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +000010308 return false;
10309
George Burgess IVe3763372016-12-22 02:50:20 +000010310 if (!LVal.Designator.Entries.empty())
10311 return LVal.Designator.isMostDerivedAnUnsizedArray();
10312
George Burgess IVa51c4072015-10-16 01:49:01 +000010313 if (!LVal.InvalidBase)
10314 return true;
10315
George Burgess IVe3763372016-12-22 02:50:20 +000010316 // If `E` is a MemberExpr, then the first part of the designator is hiding in
10317 // the LValueBase.
10318 const auto *E = LVal.Base.dyn_cast<const Expr *>();
10319 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +000010320}
10321
George Burgess IVe3763372016-12-22 02:50:20 +000010322/// Attempts to detect a user writing into a piece of memory that's impossible
10323/// to figure out the size of by just using types.
10324static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10325 const SubobjectDesignator &Designator = LVal.Designator;
10326 // Notes:
10327 // - Users can only write off of the end when we have an invalid base. Invalid
10328 // bases imply we don't know where the memory came from.
10329 // - We used to be a bit more aggressive here; we'd only be conservative if
10330 // the array at the end was flexible, or if it had 0 or 1 elements. This
10331 // broke some common standard library extensions (PR30346), but was
10332 // otherwise seemingly fine. It may be useful to reintroduce this behavior
10333 // with some sort of whitelist. OTOH, it seems that GCC is always
10334 // conservative with the last element in structs (if it's an array), so our
10335 // current behavior is more compatible than a whitelisting approach would
10336 // be.
10337 return LVal.InvalidBase &&
10338 Designator.Entries.size() == Designator.MostDerivedPathLength &&
10339 Designator.MostDerivedIsArrayElement &&
10340 isDesignatorAtObjectEnd(Ctx, LVal);
10341}
10342
10343/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10344/// Fails if the conversion would cause loss of precision.
10345static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10346 CharUnits &Result) {
10347 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10348 if (Int.ugt(CharUnitsMax))
10349 return false;
10350 Result = CharUnits::fromQuantity(Int.getZExtValue());
10351 return true;
10352}
10353
10354/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
10355/// determine how many bytes exist from the beginning of the object to either
10356/// the end of the current subobject, or the end of the object itself, depending
10357/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +000010358///
George Burgess IVe3763372016-12-22 02:50:20 +000010359/// If this returns false, the value of Result is undefined.
10360static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10361 unsigned Type, const LValue &LVal,
10362 CharUnits &EndOffset) {
10363 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010364
George Burgess IV7fb7e362017-01-03 23:35:19 +000010365 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10366 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10367 return false;
10368 return HandleSizeof(Info, ExprLoc, Ty, Result);
10369 };
10370
George Burgess IVe3763372016-12-22 02:50:20 +000010371 // We want to evaluate the size of the entire object. This is a valid fallback
10372 // for when Type=1 and the designator is invalid, because we're asked for an
10373 // upper-bound.
10374 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10375 // Type=3 wants a lower bound, so we can't fall back to this.
10376 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +000010377 return false;
George Burgess IVe3763372016-12-22 02:50:20 +000010378
10379 llvm::APInt APEndOffset;
10380 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10381 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10382 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10383
10384 if (LVal.InvalidBase)
10385 return false;
10386
10387 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +000010388 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +000010389 }
10390
George Burgess IVe3763372016-12-22 02:50:20 +000010391 // We want to evaluate the size of a subobject.
10392 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010393
10394 // The following is a moderately common idiom in C:
10395 //
10396 // struct Foo { int a; char c[1]; };
10397 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10398 // strcpy(&F->c[0], Bar);
10399 //
George Burgess IVe3763372016-12-22 02:50:20 +000010400 // In order to not break too much legacy code, we need to support it.
10401 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10402 // If we can resolve this to an alloc_size call, we can hand that back,
10403 // because we know for certain how many bytes there are to write to.
10404 llvm::APInt APEndOffset;
10405 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10406 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10407 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10408
10409 // If we cannot determine the size of the initial allocation, then we can't
10410 // given an accurate upper-bound. However, we are still able to give
10411 // conservative lower-bounds for Type=3.
10412 if (Type == 1)
10413 return false;
10414 }
10415
10416 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +000010417 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010418 return false;
10419
George Burgess IVe3763372016-12-22 02:50:20 +000010420 // According to the GCC documentation, we want the size of the subobject
10421 // denoted by the pointer. But that's not quite right -- what we actually
10422 // want is the size of the immediately-enclosing array, if there is one.
10423 int64_t ElemsRemaining;
10424 if (Designator.MostDerivedIsArrayElement &&
10425 Designator.Entries.size() == Designator.MostDerivedPathLength) {
10426 uint64_t ArraySize = Designator.getMostDerivedArraySize();
Richard Smith5b5e27a2019-05-10 20:05:31 +000010427 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
George Burgess IVe3763372016-12-22 02:50:20 +000010428 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
10429 } else {
10430 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
10431 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010432
George Burgess IVe3763372016-12-22 02:50:20 +000010433 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
10434 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +000010435}
10436
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010437/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +000010438/// returns true and stores the result in @p Size.
10439///
10440/// If @p WasError is non-null, this will report whether the failure to evaluate
10441/// is to be treated as an Error in IntExprEvaluator.
10442static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
10443 EvalInfo &Info, uint64_t &Size) {
10444 // Determine the denoted object.
10445 LValue LVal;
10446 {
10447 // The operand of __builtin_object_size is never evaluated for side-effects.
10448 // If there are any, but we can determine the pointed-to object anyway, then
10449 // ignore the side-effects.
10450 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +000010451 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +000010452
10453 if (E->isGLValue()) {
10454 // It's possible for us to be given GLValues if we're called via
10455 // Expr::tryEvaluateObjectSize.
10456 APValue RVal;
10457 if (!EvaluateAsRValue(Info, E, RVal))
10458 return false;
10459 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +000010460 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
10461 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +000010462 return false;
10463 }
10464
10465 // If we point to before the start of the object, there are no accessible
10466 // bytes.
10467 if (LVal.getLValueOffset().isNegative()) {
10468 Size = 0;
10469 return true;
10470 }
10471
10472 CharUnits EndOffset;
10473 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
10474 return false;
10475
10476 // If we've fallen outside of the end offset, just pretend there's nothing to
10477 // write to/read from.
10478 if (EndOffset <= LVal.getLValueOffset())
10479 Size = 0;
10480 else
10481 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
10482 return true;
John McCall95007602010-05-10 23:27:23 +000010483}
10484
Fangrui Song407659a2018-11-30 23:41:18 +000010485bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
10486 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
Gauthier Harnischdea9d572019-06-21 08:26:21 +000010487 if (E->getResultAPValueKind() != APValue::None)
10488 return Success(E->getAPValueResult(), E);
Fangrui Song407659a2018-11-30 23:41:18 +000010489 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
10490}
10491
Peter Collingbournee9200682011-05-13 03:29:01 +000010492bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +000010493 if (unsigned BuiltinOp = E->getBuiltinCallee())
10494 return VisitBuiltinCallExpr(E, BuiltinOp);
10495
10496 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10497}
10498
10499bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10500 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +000010501 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010502 default:
Peter Collingbournee9200682011-05-13 03:29:01 +000010503 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +000010504
Erik Pilkington9c3b5882019-01-30 20:34:53 +000010505 case Builtin::BI__builtin_dynamic_object_size:
Mike Stump722cedf2009-10-26 18:35:08 +000010506 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +000010507 // The type was checked when we built the expression.
10508 unsigned Type =
10509 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10510 assert(Type <= 3 && "unexpected type");
10511
George Burgess IVe3763372016-12-22 02:50:20 +000010512 uint64_t Size;
10513 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
10514 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +000010515
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010516 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +000010517 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +000010518
Richard Smith01ade172012-05-23 04:13:20 +000010519 // Expression had no side effects, but we couldn't statically determine the
10520 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010521 switch (Info.EvalMode) {
10522 case EvalInfo::EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010523 case EvalInfo::EM_ConstantFold:
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010524 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +000010525 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010526 return Error(E);
10527 case EvalInfo::EM_ConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +000010528 // Reduce it to a constant now.
10529 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010530 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +000010531
10532 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +000010533 }
10534
Tim Northover314fbfa2018-11-02 13:14:11 +000010535 case Builtin::BI__builtin_os_log_format_buffer_size: {
10536 analyze_os_log::OSLogBufferLayout Layout;
10537 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
10538 return Success(Layout.size().getQuantity(), E);
10539 }
10540
Benjamin Kramera801f4a2012-10-06 14:42:22 +000010541 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +000010542 case Builtin::BI__builtin_bswap32:
10543 case Builtin::BI__builtin_bswap64: {
10544 APSInt Val;
10545 if (!EvaluateInteger(E->getArg(0), Val, Info))
10546 return false;
10547
10548 return Success(Val.byteSwap(), E);
10549 }
10550
Richard Smith8889a3d2013-06-13 06:26:32 +000010551 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +000010552 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +000010553
Craig Topperf95a6d92018-08-08 22:31:12 +000010554 case Builtin::BI__builtin_clrsb:
10555 case Builtin::BI__builtin_clrsbl:
10556 case Builtin::BI__builtin_clrsbll: {
10557 APSInt Val;
10558 if (!EvaluateInteger(E->getArg(0), Val, Info))
10559 return false;
10560
10561 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
10562 }
Richard Smith8889a3d2013-06-13 06:26:32 +000010563
Richard Smith80b3c8e2013-06-13 05:04:16 +000010564 case Builtin::BI__builtin_clz:
10565 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +000010566 case Builtin::BI__builtin_clzll:
10567 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +000010568 APSInt Val;
10569 if (!EvaluateInteger(E->getArg(0), Val, Info))
10570 return false;
10571 if (!Val)
10572 return Error(E);
10573
10574 return Success(Val.countLeadingZeros(), E);
10575 }
10576
Fangrui Song407659a2018-11-30 23:41:18 +000010577 case Builtin::BI__builtin_constant_p: {
Richard Smith31cfb312019-04-27 02:58:17 +000010578 const Expr *Arg = E->getArg(0);
David Blaikie639b3d12019-05-03 18:11:31 +000010579 if (EvaluateBuiltinConstantP(Info, Arg))
Fangrui Song407659a2018-11-30 23:41:18 +000010580 return Success(true, E);
David Blaikie639b3d12019-05-03 18:11:31 +000010581 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
Richard Smithf7d30482019-05-02 23:21:28 +000010582 // Outside a constant context, eagerly evaluate to false in the presence
10583 // of side-effects in order to avoid -Wunsequenced false-positives in
10584 // a branch on __builtin_constant_p(expr).
Richard Smith31cfb312019-04-27 02:58:17 +000010585 return Success(false, E);
Fangrui Song407659a2018-11-30 23:41:18 +000010586 }
David Blaikie639b3d12019-05-03 18:11:31 +000010587 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10588 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000010589 }
Richard Smith8889a3d2013-06-13 06:26:32 +000010590
Dávid Bolvanskýb06305e2019-10-29 19:06:48 +010010591 case Builtin::BI__builtin_is_constant_evaluated: {
10592 const auto *Callee = Info.CurrentCall->getCallee();
10593 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
10594 (Info.CallStackDepth == 1 ||
10595 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
10596 Callee->getIdentifier() &&
10597 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
10598 // FIXME: Find a better way to avoid duplicated diagnostics.
10599 if (Info.EvalStatus.Diag)
10600 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
10601 : Info.CurrentCall->CallLoc,
10602 diag::warn_is_constant_evaluated_always_true_constexpr)
10603 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
10604 : "std::is_constant_evaluated");
10605 }
10606
Eric Fiselieradd16a82019-04-24 02:23:30 +000010607 return Success(Info.InConstantContext, E);
Dávid Bolvanskýb06305e2019-10-29 19:06:48 +010010608 }
Eric Fiselieradd16a82019-04-24 02:23:30 +000010609
Richard Smith80b3c8e2013-06-13 05:04:16 +000010610 case Builtin::BI__builtin_ctz:
10611 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +000010612 case Builtin::BI__builtin_ctzll:
10613 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +000010614 APSInt Val;
10615 if (!EvaluateInteger(E->getArg(0), Val, Info))
10616 return false;
10617 if (!Val)
10618 return Error(E);
10619
10620 return Success(Val.countTrailingZeros(), E);
10621 }
10622
Richard Smith8889a3d2013-06-13 06:26:32 +000010623 case Builtin::BI__builtin_eh_return_data_regno: {
10624 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10625 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
10626 return Success(Operand, E);
10627 }
10628
10629 case Builtin::BI__builtin_expect:
10630 return Visit(E->getArg(0));
10631
10632 case Builtin::BI__builtin_ffs:
10633 case Builtin::BI__builtin_ffsl:
10634 case Builtin::BI__builtin_ffsll: {
10635 APSInt Val;
10636 if (!EvaluateInteger(E->getArg(0), Val, Info))
10637 return false;
10638
10639 unsigned N = Val.countTrailingZeros();
10640 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
10641 }
10642
10643 case Builtin::BI__builtin_fpclassify: {
10644 APFloat Val(0.0);
10645 if (!EvaluateFloat(E->getArg(5), Val, Info))
10646 return false;
10647 unsigned Arg;
10648 switch (Val.getCategory()) {
10649 case APFloat::fcNaN: Arg = 0; break;
10650 case APFloat::fcInfinity: Arg = 1; break;
10651 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
10652 case APFloat::fcZero: Arg = 4; break;
10653 }
10654 return Visit(E->getArg(Arg));
10655 }
10656
10657 case Builtin::BI__builtin_isinf_sign: {
10658 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +000010659 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +000010660 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
10661 }
10662
Richard Smithea3019d2013-10-15 19:07:14 +000010663 case Builtin::BI__builtin_isinf: {
10664 APFloat Val(0.0);
10665 return EvaluateFloat(E->getArg(0), Val, Info) &&
10666 Success(Val.isInfinity() ? 1 : 0, E);
10667 }
10668
10669 case Builtin::BI__builtin_isfinite: {
10670 APFloat Val(0.0);
10671 return EvaluateFloat(E->getArg(0), Val, Info) &&
10672 Success(Val.isFinite() ? 1 : 0, E);
10673 }
10674
10675 case Builtin::BI__builtin_isnan: {
10676 APFloat Val(0.0);
10677 return EvaluateFloat(E->getArg(0), Val, Info) &&
10678 Success(Val.isNaN() ? 1 : 0, E);
10679 }
10680
10681 case Builtin::BI__builtin_isnormal: {
10682 APFloat Val(0.0);
10683 return EvaluateFloat(E->getArg(0), Val, Info) &&
10684 Success(Val.isNormal() ? 1 : 0, E);
10685 }
10686
Richard Smith8889a3d2013-06-13 06:26:32 +000010687 case Builtin::BI__builtin_parity:
10688 case Builtin::BI__builtin_parityl:
10689 case Builtin::BI__builtin_parityll: {
10690 APSInt Val;
10691 if (!EvaluateInteger(E->getArg(0), Val, Info))
10692 return false;
10693
10694 return Success(Val.countPopulation() % 2, E);
10695 }
10696
Richard Smith80b3c8e2013-06-13 05:04:16 +000010697 case Builtin::BI__builtin_popcount:
10698 case Builtin::BI__builtin_popcountl:
10699 case Builtin::BI__builtin_popcountll: {
10700 APSInt Val;
10701 if (!EvaluateInteger(E->getArg(0), Val, Info))
10702 return false;
10703
10704 return Success(Val.countPopulation(), E);
10705 }
10706
Douglas Gregor6a6dac22010-09-10 06:27:15 +000010707 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +000010708 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +000010709 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010710 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010711 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +000010712 << /*isConstexpr*/0 << /*isConstructor*/0
10713 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +000010714 else
Richard Smithce1ec5e2012-03-15 04:53:45 +000010715 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +000010716 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +000010717 case Builtin::BI__builtin_strlen:
10718 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +000010719 // As an extension, we support __builtin_strlen() as a constant expression,
10720 // and support folding strlen() to a constant.
10721 LValue String;
10722 if (!EvaluatePointer(E->getArg(0), String, Info))
10723 return false;
10724
Richard Smith8110c9d2016-11-29 19:45:17 +000010725 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
10726
Richard Smithe6c19f22013-11-15 02:10:04 +000010727 // Fast path: if it's a string literal, search the string value.
10728 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
10729 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +000010730 // The string literal may have embedded null characters. Find the first
10731 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +000010732 StringRef Str = S->getBytes();
10733 int64_t Off = String.Offset.getQuantity();
10734 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +000010735 S->getCharByteWidth() == 1 &&
10736 // FIXME: Add fast-path for wchar_t too.
10737 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +000010738 Str = Str.substr(Off);
10739
10740 StringRef::size_type Pos = Str.find(0);
10741 if (Pos != StringRef::npos)
10742 Str = Str.substr(0, Pos);
10743
10744 return Success(Str.size(), E);
10745 }
10746
10747 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +000010748 }
Richard Smithe6c19f22013-11-15 02:10:04 +000010749
10750 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +000010751 for (uint64_t Strlen = 0; /**/; ++Strlen) {
10752 APValue Char;
10753 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
10754 !Char.isInt())
10755 return false;
10756 if (!Char.getInt())
10757 return Success(Strlen, E);
10758 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
10759 return false;
10760 }
10761 }
Eli Friedmana4c26022011-10-17 21:44:23 +000010762
Richard Smithe151bab2016-11-11 23:43:35 +000010763 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010764 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010765 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010766 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010767 case Builtin::BImemcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +000010768 case Builtin::BIbcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010769 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010770 // A call to strlen is not a constant expression.
10771 if (Info.getLangOpts().CPlusPlus11)
10772 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10773 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +000010774 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +000010775 else
10776 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +000010777 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +000010778 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010779 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +000010780 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010781 case Builtin::BI__builtin_wcsncmp:
10782 case Builtin::BI__builtin_memcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +000010783 case Builtin::BI__builtin_bcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +000010784 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +000010785 LValue String1, String2;
10786 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
10787 !EvaluatePointer(E->getArg(1), String2, Info))
10788 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +000010789
Richard Smithe151bab2016-11-11 23:43:35 +000010790 uint64_t MaxLength = uint64_t(-1);
10791 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +000010792 BuiltinOp != Builtin::BIwcscmp &&
10793 BuiltinOp != Builtin::BI__builtin_strcmp &&
10794 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +000010795 APSInt N;
10796 if (!EvaluateInteger(E->getArg(2), N, Info))
10797 return false;
10798 MaxLength = N.getExtValue();
10799 }
Hubert Tong147b7432018-12-12 16:53:43 +000010800
10801 // Empty substrings compare equal by definition.
10802 if (MaxLength == 0u)
10803 return Success(0, E);
10804
10805 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10806 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
10807 String1.Designator.Invalid || String2.Designator.Invalid)
10808 return false;
10809
10810 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
10811 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
10812
10813 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
Clement Courbet8c3343d2019-02-14 12:00:34 +000010814 BuiltinOp == Builtin::BIbcmp ||
10815 BuiltinOp == Builtin::BI__builtin_memcmp ||
10816 BuiltinOp == Builtin::BI__builtin_bcmp;
Hubert Tong147b7432018-12-12 16:53:43 +000010817
10818 assert(IsRawByte ||
10819 (Info.Ctx.hasSameUnqualifiedType(
10820 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
10821 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
10822
10823 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
10824 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
10825 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
10826 Char1.isInt() && Char2.isInt();
10827 };
10828 const auto &AdvanceElems = [&] {
10829 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
10830 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
10831 };
10832
10833 if (IsRawByte) {
10834 uint64_t BytesRemaining = MaxLength;
10835 // Pointers to const void may point to objects of incomplete type.
10836 if (CharTy1->isIncompleteType()) {
10837 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
10838 return false;
10839 }
10840 if (CharTy2->isIncompleteType()) {
10841 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
10842 return false;
10843 }
10844 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
10845 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
10846 // Give up on comparing between elements with disparate widths.
10847 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
10848 return false;
10849 uint64_t BytesPerElement = CharTy1Size.getQuantity();
10850 assert(BytesRemaining && "BytesRemaining should not be zero: the "
10851 "following loop considers at least one element");
10852 while (true) {
10853 APValue Char1, Char2;
10854 if (!ReadCurElems(Char1, Char2))
10855 return false;
10856 // We have compatible in-memory widths, but a possible type and
10857 // (for `bool`) internal representation mismatch.
10858 // Assuming two's complement representation, including 0 for `false` and
10859 // 1 for `true`, we can check an appropriate number of elements for
10860 // equality even if they are not byte-sized.
10861 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
10862 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
10863 if (Char1InMem.ne(Char2InMem)) {
10864 // If the elements are byte-sized, then we can produce a three-way
10865 // comparison result in a straightforward manner.
10866 if (BytesPerElement == 1u) {
10867 // memcmp always compares unsigned chars.
10868 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
10869 }
10870 // The result is byte-order sensitive, and we have multibyte elements.
10871 // FIXME: We can compare the remaining bytes in the correct order.
10872 return false;
10873 }
10874 if (!AdvanceElems())
10875 return false;
10876 if (BytesRemaining <= BytesPerElement)
10877 break;
10878 BytesRemaining -= BytesPerElement;
10879 }
10880 // Enough elements are equal to account for the memcmp limit.
10881 return Success(0, E);
10882 }
10883
Clement Courbet8c3343d2019-02-14 12:00:34 +000010884 bool StopAtNull =
10885 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
10886 BuiltinOp != Builtin::BIwmemcmp &&
10887 BuiltinOp != Builtin::BI__builtin_memcmp &&
10888 BuiltinOp != Builtin::BI__builtin_bcmp &&
10889 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +000010890 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
10891 BuiltinOp == Builtin::BIwcsncmp ||
10892 BuiltinOp == Builtin::BIwmemcmp ||
10893 BuiltinOp == Builtin::BI__builtin_wcscmp ||
10894 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
10895 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +000010896
Richard Smithe151bab2016-11-11 23:43:35 +000010897 for (; MaxLength; --MaxLength) {
10898 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +000010899 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +000010900 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +000010901 if (Char1.getInt() != Char2.getInt()) {
10902 if (IsWide) // wmemcmp compares with wchar_t signedness.
10903 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
10904 // memcmp always compares unsigned chars.
10905 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
10906 }
Richard Smithe151bab2016-11-11 23:43:35 +000010907 if (StopAtNull && !Char1.getInt())
10908 return Success(0, E);
10909 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +000010910 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +000010911 return false;
10912 }
10913 // We hit the strncmp / memcmp limit.
10914 return Success(0, E);
10915 }
10916
Richard Smith01ba47d2012-04-13 00:45:38 +000010917 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +000010918 case Builtin::BI__atomic_is_lock_free:
10919 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +000010920 APSInt SizeVal;
10921 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
10922 return false;
10923
10924 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
10925 // of two less than the maximum inline atomic width, we know it is
10926 // lock-free. If the size isn't a power of two, or greater than the
10927 // maximum alignment where we promote atomics, we know it is not lock-free
10928 // (at least not in the sense of atomic_is_lock_free). Otherwise,
10929 // the answer can only be determined at runtime; for example, 16-byte
10930 // atomics have lock-free implementations on some, but not all,
10931 // x86-64 processors.
10932
10933 // Check power-of-two.
10934 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +000010935 if (Size.isPowerOfTwo()) {
10936 // Check against inlining width.
10937 unsigned InlineWidthBits =
10938 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
10939 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
10940 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
10941 Size == CharUnits::One() ||
10942 E->getArg(1)->isNullPointerConstant(Info.Ctx,
10943 Expr::NPC_NeverValueDependent))
10944 // OK, we will inline appropriately-aligned operations of this size,
10945 // and _Atomic(T) is appropriately-aligned.
10946 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +000010947
Richard Smith01ba47d2012-04-13 00:45:38 +000010948 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
10949 castAs<PointerType>()->getPointeeType();
10950 if (!PointeeType->isIncompleteType() &&
10951 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
10952 // OK, we will inline operations on this object.
10953 return Success(1, E);
10954 }
10955 }
10956 }
Eli Friedmana4c26022011-10-17 21:44:23 +000010957
Richard Smith01ba47d2012-04-13 00:45:38 +000010958 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
10959 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +000010960 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +000010961 case Builtin::BIomp_is_initial_device:
10962 // We can decide statically which value the runtime would return if called.
10963 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +000010964 case Builtin::BI__builtin_add_overflow:
10965 case Builtin::BI__builtin_sub_overflow:
10966 case Builtin::BI__builtin_mul_overflow:
10967 case Builtin::BI__builtin_sadd_overflow:
10968 case Builtin::BI__builtin_uadd_overflow:
10969 case Builtin::BI__builtin_uaddl_overflow:
10970 case Builtin::BI__builtin_uaddll_overflow:
10971 case Builtin::BI__builtin_usub_overflow:
10972 case Builtin::BI__builtin_usubl_overflow:
10973 case Builtin::BI__builtin_usubll_overflow:
10974 case Builtin::BI__builtin_umul_overflow:
10975 case Builtin::BI__builtin_umull_overflow:
10976 case Builtin::BI__builtin_umulll_overflow:
10977 case Builtin::BI__builtin_saddl_overflow:
10978 case Builtin::BI__builtin_saddll_overflow:
10979 case Builtin::BI__builtin_ssub_overflow:
10980 case Builtin::BI__builtin_ssubl_overflow:
10981 case Builtin::BI__builtin_ssubll_overflow:
10982 case Builtin::BI__builtin_smul_overflow:
10983 case Builtin::BI__builtin_smull_overflow:
10984 case Builtin::BI__builtin_smulll_overflow: {
10985 LValue ResultLValue;
10986 APSInt LHS, RHS;
10987
10988 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
10989 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
10990 !EvaluateInteger(E->getArg(1), RHS, Info) ||
10991 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
10992 return false;
10993
10994 APSInt Result;
10995 bool DidOverflow = false;
10996
10997 // If the types don't have to match, enlarge all 3 to the largest of them.
10998 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10999 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11000 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11001 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
11002 ResultType->isSignedIntegerOrEnumerationType();
11003 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
11004 ResultType->isSignedIntegerOrEnumerationType();
11005 uint64_t LHSSize = LHS.getBitWidth();
11006 uint64_t RHSSize = RHS.getBitWidth();
11007 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
11008 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
11009
11010 // Add an additional bit if the signedness isn't uniformly agreed to. We
11011 // could do this ONLY if there is a signed and an unsigned that both have
11012 // MaxBits, but the code to check that is pretty nasty. The issue will be
11013 // caught in the shrink-to-result later anyway.
11014 if (IsSigned && !AllSigned)
11015 ++MaxBits;
11016
Erich Keanefc3dfd32019-05-30 21:35:32 +000011017 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11018 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
Erich Keane00958272018-06-13 20:43:27 +000011019 Result = APSInt(MaxBits, !IsSigned);
11020 }
11021
11022 // Find largest int.
11023 switch (BuiltinOp) {
11024 default:
11025 llvm_unreachable("Invalid value for BuiltinOp");
11026 case Builtin::BI__builtin_add_overflow:
11027 case Builtin::BI__builtin_sadd_overflow:
11028 case Builtin::BI__builtin_saddl_overflow:
11029 case Builtin::BI__builtin_saddll_overflow:
11030 case Builtin::BI__builtin_uadd_overflow:
11031 case Builtin::BI__builtin_uaddl_overflow:
11032 case Builtin::BI__builtin_uaddll_overflow:
11033 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11034 : LHS.uadd_ov(RHS, DidOverflow);
11035 break;
11036 case Builtin::BI__builtin_sub_overflow:
11037 case Builtin::BI__builtin_ssub_overflow:
11038 case Builtin::BI__builtin_ssubl_overflow:
11039 case Builtin::BI__builtin_ssubll_overflow:
11040 case Builtin::BI__builtin_usub_overflow:
11041 case Builtin::BI__builtin_usubl_overflow:
11042 case Builtin::BI__builtin_usubll_overflow:
11043 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11044 : LHS.usub_ov(RHS, DidOverflow);
11045 break;
11046 case Builtin::BI__builtin_mul_overflow:
11047 case Builtin::BI__builtin_smul_overflow:
11048 case Builtin::BI__builtin_smull_overflow:
11049 case Builtin::BI__builtin_smulll_overflow:
11050 case Builtin::BI__builtin_umul_overflow:
11051 case Builtin::BI__builtin_umull_overflow:
11052 case Builtin::BI__builtin_umulll_overflow:
11053 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11054 : LHS.umul_ov(RHS, DidOverflow);
11055 break;
11056 }
11057
11058 // In the case where multiple sizes are allowed, truncate and see if
11059 // the values are the same.
11060 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11061 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11062 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11063 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11064 // since it will give us the behavior of a TruncOrSelf in the case where
11065 // its parameter <= its size. We previously set Result to be at least the
11066 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
11067 // will work exactly like TruncOrSelf.
11068 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
11069 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
11070
11071 if (!APSInt::isSameValue(Temp, Result))
11072 DidOverflow = true;
11073 Result = Temp;
11074 }
11075
11076 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +000011077 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
11078 return false;
Erich Keane00958272018-06-13 20:43:27 +000011079 return Success(DidOverflow, E);
11080 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011081 }
Chris Lattner7174bf32008-07-12 00:38:25 +000011082}
Anders Carlsson4a3585b2008-07-08 15:34:11 +000011083
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011084/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +000011085/// object referred to by the lvalue.
11086static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
11087 const LValue &LV) {
11088 // A null pointer can be viewed as being "past the end" but we don't
11089 // choose to look at it that way here.
11090 if (!LV.getLValueBase())
11091 return false;
11092
11093 // If the designator is valid and refers to a subobject, we're not pointing
11094 // past the end.
11095 if (!LV.getLValueDesignator().Invalid &&
11096 !LV.getLValueDesignator().isOnePastTheEnd())
11097 return false;
11098
David Majnemerc378ca52015-08-29 08:32:55 +000011099 // A pointer to an incomplete type might be past-the-end if the type's size is
11100 // zero. We cannot tell because the type is incomplete.
11101 QualType Ty = getType(LV.getLValueBase());
11102 if (Ty->isIncompleteType())
11103 return true;
11104
Richard Smithd20f1e62014-10-21 23:01:04 +000011105 // We're a past-the-end pointer if we point to the byte after the object,
11106 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +000011107 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +000011108 return LV.getLValueOffset() == Size;
11109}
11110
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011111namespace {
Richard Smith11562c52011-10-28 17:51:58 +000011112
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011113/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011114///
11115/// We use a data recursive algorithm for binary operators so that we are able
11116/// to handle extreme cases of chained binary operators without causing stack
11117/// overflow.
11118class DataRecursiveIntBinOpEvaluator {
11119 struct EvalResult {
11120 APValue Val;
11121 bool Failed;
11122
11123 EvalResult() : Failed(false) { }
11124
11125 void swap(EvalResult &RHS) {
11126 Val.swap(RHS.Val);
11127 Failed = RHS.Failed;
11128 RHS.Failed = false;
11129 }
11130 };
11131
11132 struct Job {
11133 const Expr *E;
11134 EvalResult LHSResult; // meaningful only for binary operator expression.
11135 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +000011136
David Blaikie73726062015-08-12 23:09:24 +000011137 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +000011138 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +000011139
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011140 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +000011141 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011142 }
George Burgess IV8c892b52016-05-25 22:31:54 +000011143
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011144 private:
George Burgess IV8c892b52016-05-25 22:31:54 +000011145 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011146 };
11147
11148 SmallVector<Job, 16> Queue;
11149
11150 IntExprEvaluator &IntEval;
11151 EvalInfo &Info;
11152 APValue &FinalResult;
11153
11154public:
11155 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
11156 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
11157
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011158 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011159 /// data recursively.
11160 /// We handle binary operators that are comma, logical, or that have operands
11161 /// with integral or enumeration type.
11162 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011163 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
11164 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +000011165 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011166 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +000011167 }
11168
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011169 bool Traverse(const BinaryOperator *E) {
11170 enqueue(E);
11171 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +000011172 while (!Queue.empty())
11173 process(PrevResult);
11174
11175 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011176
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011177 FinalResult.swap(PrevResult.Val);
11178 return true;
11179 }
11180
11181private:
11182 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11183 return IntEval.Success(Value, E, Result);
11184 }
11185 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
11186 return IntEval.Success(Value, E, Result);
11187 }
11188 bool Error(const Expr *E) {
11189 return IntEval.Error(E);
11190 }
11191 bool Error(const Expr *E, diag::kind D) {
11192 return IntEval.Error(E, D);
11193 }
11194
11195 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
11196 return Info.CCEDiag(E, D);
11197 }
11198
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011199 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011200 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011201 bool &SuppressRHSDiags);
11202
11203 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11204 const BinaryOperator *E, APValue &Result);
11205
11206 void EvaluateExpr(const Expr *E, EvalResult &Result) {
11207 Result.Failed = !Evaluate(Result.Val, Info, E);
11208 if (Result.Failed)
11209 Result.Val = APValue();
11210 }
11211
Richard Trieuba4d0872012-03-21 23:30:30 +000011212 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011213
11214 void enqueue(const Expr *E) {
11215 E = E->IgnoreParens();
11216 Queue.resize(Queue.size()+1);
11217 Queue.back().E = E;
11218 Queue.back().Kind = Job::AnyExprKind;
11219 }
11220};
11221
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011222}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011223
11224bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011225 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011226 bool &SuppressRHSDiags) {
11227 if (E->getOpcode() == BO_Comma) {
11228 // Ignore LHS but note if we could not evaluate it.
11229 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +000011230 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011231 return true;
11232 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000011233
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011234 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +000011235 bool LHSAsBool;
11236 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011237 // We were able to evaluate the LHS, see if we can get away with not
11238 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +000011239 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
11240 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011241 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011242 }
11243 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +000011244 LHSResult.Failed = true;
11245
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011246 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +000011247 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +000011248 if (!Info.noteSideEffect())
11249 return false;
11250
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011251 // We can't evaluate the LHS; however, sometimes the result
11252 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11253 // Don't ignore RHS and suppress diagnostics from this arm.
11254 SuppressRHSDiags = true;
11255 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000011256
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011257 return true;
11258 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000011259
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011260 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11261 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +000011262
George Burgess IVa145e252016-05-25 22:38:36 +000011263 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011264 return false; // Ignore RHS;
11265
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011266 return true;
11267}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011268
Benjamin Kramerf6021ec2017-03-21 21:35:04 +000011269static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
11270 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +000011271 // Compute the new offset in the appropriate width, wrapping at 64 bits.
11272 // FIXME: When compiling for a 32-bit target, we should use 32-bit
11273 // offsets.
11274 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
11275 CharUnits &Offset = LVal.getLValueOffset();
11276 uint64_t Offset64 = Offset.getQuantity();
11277 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
11278 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
11279 : Offset64 + Index64);
11280}
11281
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011282bool DataRecursiveIntBinOpEvaluator::
11283 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11284 const BinaryOperator *E, APValue &Result) {
11285 if (E->getOpcode() == BO_Comma) {
11286 if (RHSResult.Failed)
11287 return false;
11288 Result = RHSResult.Val;
11289 return true;
11290 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011291
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011292 if (E->isLogicalOp()) {
11293 bool lhsResult, rhsResult;
11294 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
11295 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +000011296
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011297 if (LHSIsOK) {
11298 if (RHSIsOK) {
11299 if (E->getOpcode() == BO_LOr)
11300 return Success(lhsResult || rhsResult, E, Result);
11301 else
11302 return Success(lhsResult && rhsResult, E, Result);
11303 }
11304 } else {
11305 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011306 // We can't evaluate the LHS; however, sometimes the result
11307 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11308 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011309 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011310 }
11311 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011312
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000011313 return false;
11314 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011315
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011316 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11317 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +000011318
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011319 if (LHSResult.Failed || RHSResult.Failed)
11320 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000011321
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011322 const APValue &LHSVal = LHSResult.Val;
11323 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +000011324
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011325 // Handle cases like (unsigned long)&a + 4.
11326 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
11327 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000011328 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011329 return true;
11330 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011331
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011332 // Handle cases like 4 + (unsigned long)&a
11333 if (E->getOpcode() == BO_Add &&
11334 RHSVal.isLValue() && LHSVal.isInt()) {
11335 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000011336 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011337 return true;
11338 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011339
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011340 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
11341 // Handle (intptr_t)&&A - (intptr_t)&&B.
11342 if (!LHSVal.getLValueOffset().isZero() ||
11343 !RHSVal.getLValueOffset().isZero())
11344 return false;
11345 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
11346 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
11347 if (!LHSExpr || !RHSExpr)
11348 return false;
11349 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11350 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11351 if (!LHSAddrExpr || !RHSAddrExpr)
11352 return false;
11353 // Make sure both labels come from the same function.
11354 if (LHSAddrExpr->getLabel()->getDeclContext() !=
11355 RHSAddrExpr->getLabel()->getDeclContext())
11356 return false;
11357 Result = APValue(LHSAddrExpr, RHSAddrExpr);
11358 return true;
11359 }
Richard Smith43e77732013-05-07 04:50:00 +000011360
11361 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011362 if (!LHSVal.isInt() || !RHSVal.isInt())
11363 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +000011364
11365 // Set up the width and signedness manually, in case it can't be deduced
11366 // from the operation we're performing.
11367 // FIXME: Don't do this in the cases where we can deduce it.
11368 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
11369 E->getType()->isUnsignedIntegerOrEnumerationType());
11370 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
11371 RHSVal.getInt(), Value))
11372 return false;
11373 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011374}
11375
Richard Trieuba4d0872012-03-21 23:30:30 +000011376void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011377 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +000011378
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011379 switch (job.Kind) {
11380 case Job::AnyExprKind: {
11381 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
11382 if (shouldEnqueue(Bop)) {
11383 job.Kind = Job::BinOpKind;
11384 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000011385 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011386 }
11387 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011388
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011389 EvaluateExpr(job.E, Result);
11390 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000011391 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011392 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011393
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011394 case Job::BinOpKind: {
11395 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011396 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011397 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011398 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000011399 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011400 }
11401 if (SuppressRHSDiags)
11402 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000011403 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011404 job.Kind = Job::BinOpVisitedLHSKind;
11405 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000011406 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011407 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011408
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011409 case Job::BinOpVisitedLHSKind: {
11410 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11411 EvalResult RHS;
11412 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +000011413 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011414 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000011415 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011416 }
11417 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011418
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011419 llvm_unreachable("Invalid Job::Kind!");
11420}
11421
George Burgess IV8c892b52016-05-25 22:31:54 +000011422namespace {
11423/// Used when we determine that we should fail, but can keep evaluating prior to
11424/// noting that we had a failure.
11425class DelayedNoteFailureRAII {
11426 EvalInfo &Info;
11427 bool NoteFailure;
11428
11429public:
11430 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
11431 : Info(Info), NoteFailure(NoteFailure) {}
11432 ~DelayedNoteFailureRAII() {
11433 if (NoteFailure) {
11434 bool ContinueAfterFailure = Info.noteFailure();
11435 (void)ContinueAfterFailure;
11436 assert(ContinueAfterFailure &&
11437 "Shouldn't have kept evaluating on failure.");
11438 }
11439 }
11440};
11441}
11442
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011443template <class SuccessCB, class AfterCB>
11444static bool
11445EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
11446 SuccessCB &&Success, AfterCB &&DoAfter) {
11447 assert(E->isComparisonOp() && "expected comparison operator");
11448 assert((E->getOpcode() == BO_Cmp ||
11449 E->getType()->isIntegralOrEnumerationType()) &&
11450 "unsupported binary expression evaluation");
11451 auto Error = [&](const Expr *E) {
11452 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11453 return false;
11454 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011455
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011456 using CCR = ComparisonCategoryResult;
11457 bool IsRelational = E->isRelationalOp();
11458 bool IsEquality = E->isEqualityOp();
11459 if (E->getOpcode() == BO_Cmp) {
11460 const ComparisonCategoryInfo &CmpInfo =
11461 Info.Ctx.CompCategories.getInfoForType(E->getType());
11462 IsRelational = CmpInfo.isOrdered();
11463 IsEquality = CmpInfo.isEquality();
11464 }
Eli Friedman5a332ea2008-11-13 06:09:17 +000011465
Anders Carlssonacc79812008-11-16 07:17:21 +000011466 QualType LHSTy = E->getLHS()->getType();
11467 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011468
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011469 if (LHSTy->isIntegralOrEnumerationType() &&
11470 RHSTy->isIntegralOrEnumerationType()) {
11471 APSInt LHS, RHS;
11472 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
11473 if (!LHSOK && !Info.noteFailure())
11474 return false;
11475 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
11476 return false;
11477 if (LHS < RHS)
11478 return Success(CCR::Less, E);
11479 if (LHS > RHS)
11480 return Success(CCR::Greater, E);
11481 return Success(CCR::Equal, E);
11482 }
11483
Leonard Chance1d4f12019-02-21 20:50:09 +000011484 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
11485 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
11486 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
11487
11488 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
11489 if (!LHSOK && !Info.noteFailure())
11490 return false;
11491 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
11492 return false;
11493 if (LHSFX < RHSFX)
11494 return Success(CCR::Less, E);
11495 if (LHSFX > RHSFX)
11496 return Success(CCR::Greater, E);
11497 return Success(CCR::Equal, E);
11498 }
11499
Chandler Carruthb29a7432014-10-11 11:03:30 +000011500 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011501 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +000011502 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +000011503 if (E->isAssignmentOp()) {
11504 LValue LV;
11505 EvaluateLValue(E->getLHS(), LV, Info);
11506 LHSOK = false;
11507 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +000011508 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
11509 if (LHSOK) {
11510 LHS.makeComplexFloat();
11511 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
11512 }
11513 } else {
11514 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
11515 }
George Burgess IVa145e252016-05-25 22:38:36 +000011516 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011517 return false;
11518
Chandler Carruthb29a7432014-10-11 11:03:30 +000011519 if (E->getRHS()->getType()->isRealFloatingType()) {
11520 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
11521 return false;
11522 RHS.makeComplexFloat();
11523 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
11524 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011525 return false;
11526
11527 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +000011528 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011529 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +000011530 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011531 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011532 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
11533 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011534 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011535 assert(IsEquality && "invalid complex comparison");
11536 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
11537 LHS.getComplexIntImag() == RHS.getComplexIntImag();
11538 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000011539 }
11540 }
Mike Stump11289f42009-09-09 15:08:12 +000011541
Anders Carlssonacc79812008-11-16 07:17:21 +000011542 if (LHSTy->isRealFloatingType() &&
11543 RHSTy->isRealFloatingType()) {
11544 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +000011545
Richard Smith253c2a32012-01-27 01:14:48 +000011546 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000011547 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +000011548 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011549
Richard Smith253c2a32012-01-27 01:14:48 +000011550 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +000011551 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011552
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011553 assert(E->isComparisonOp() && "Invalid binary operator!");
11554 auto GetCmpRes = [&]() {
11555 switch (LHS.compare(RHS)) {
11556 case APFloat::cmpEqual:
11557 return CCR::Equal;
11558 case APFloat::cmpLessThan:
11559 return CCR::Less;
11560 case APFloat::cmpGreaterThan:
11561 return CCR::Greater;
11562 case APFloat::cmpUnordered:
11563 return CCR::Unordered;
11564 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +000011565 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011566 };
11567 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +000011568 }
Mike Stump11289f42009-09-09 15:08:12 +000011569
Eli Friedmana38da572009-04-28 19:17:36 +000011570 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011571 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +000011572
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011573 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11574 if (!LHSOK && !Info.noteFailure())
11575 return false;
Eli Friedman64004332009-03-23 04:38:34 +000011576
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011577 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11578 return false;
Eli Friedman64004332009-03-23 04:38:34 +000011579
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011580 // Reject differing bases from the normal codepath; we special-case
11581 // comparisons to null.
11582 if (!HasSameBase(LHSValue, RHSValue)) {
11583 // Inequalities and subtractions between unrelated pointers have
11584 // unspecified or undefined behavior.
11585 if (!IsEquality)
11586 return Error(E);
11587 // A constant address may compare equal to the address of a symbol.
11588 // The one exception is that address of an object cannot compare equal
11589 // to a null pointer constant.
11590 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
11591 (!RHSValue.Base && !RHSValue.Offset.isZero()))
11592 return Error(E);
11593 // It's implementation-defined whether distinct literals will have
11594 // distinct addresses. In clang, the result of such a comparison is
11595 // unspecified, so it is not a constant expression. However, we do know
11596 // that the address of a literal will be non-null.
11597 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
11598 LHSValue.Base && RHSValue.Base)
11599 return Error(E);
11600 // We can't tell whether weak symbols will end up pointing to the same
11601 // object.
11602 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
11603 return Error(E);
11604 // We can't compare the address of the start of one object with the
11605 // past-the-end address of another object, per C++ DR1652.
11606 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
11607 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
11608 (RHSValue.Base && RHSValue.Offset.isZero() &&
11609 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
11610 return Error(E);
11611 // We can't tell whether an object is at the same address as another
11612 // zero sized object.
11613 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
11614 (LHSValue.Base && isZeroSized(RHSValue)))
11615 return Error(E);
11616 return Success(CCR::Nonequal, E);
11617 }
Eli Friedman64004332009-03-23 04:38:34 +000011618
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011619 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11620 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +000011621
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011622 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11623 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +000011624
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011625 // C++11 [expr.rel]p3:
11626 // Pointers to void (after pointer conversions) can be compared, with a
11627 // result defined as follows: If both pointers represent the same
11628 // address or are both the null pointer value, the result is true if the
11629 // operator is <= or >= and false otherwise; otherwise the result is
11630 // unspecified.
11631 // We interpret this as applying to pointers to *cv* void.
11632 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
11633 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +000011634
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011635 // C++11 [expr.rel]p2:
11636 // - If two pointers point to non-static data members of the same object,
11637 // or to subobjects or array elements fo such members, recursively, the
11638 // pointer to the later declared member compares greater provided the
11639 // two members have the same access control and provided their class is
11640 // not a union.
11641 // [...]
11642 // - Otherwise pointer comparisons are unspecified.
11643 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
11644 bool WasArrayIndex;
11645 unsigned Mismatch = FindDesignatorMismatch(
11646 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
11647 // At the point where the designators diverge, the comparison has a
11648 // specified value if:
11649 // - we are comparing array indices
11650 // - we are comparing fields of a union, or fields with the same access
11651 // Otherwise, the result is unspecified and thus the comparison is not a
11652 // constant expression.
11653 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
11654 Mismatch < RHSDesignator.Entries.size()) {
11655 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
11656 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
11657 if (!LF && !RF)
11658 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
11659 else if (!LF)
11660 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000011661 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
11662 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011663 else if (!RF)
11664 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000011665 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
11666 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011667 else if (!LF->getParent()->isUnion() &&
11668 LF->getAccess() != RF->getAccess())
11669 Info.CCEDiag(E,
11670 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +000011671 << LF << LF->getAccess() << RF << RF->getAccess()
11672 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +000011673 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +000011674 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011675
11676 // The comparison here must be unsigned, and performed with the same
11677 // width as the pointer.
11678 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
11679 uint64_t CompareLHS = LHSOffset.getQuantity();
11680 uint64_t CompareRHS = RHSOffset.getQuantity();
11681 assert(PtrSize <= 64 && "Unexpected pointer width");
11682 uint64_t Mask = ~0ULL >> (64 - PtrSize);
11683 CompareLHS &= Mask;
11684 CompareRHS &= Mask;
11685
11686 // If there is a base and this is a relational operator, we can only
11687 // compare pointers within the object in question; otherwise, the result
11688 // depends on where the object is located in memory.
11689 if (!LHSValue.Base.isNull() && IsRelational) {
11690 QualType BaseTy = getType(LHSValue.Base);
11691 if (BaseTy->isIncompleteType())
11692 return Error(E);
11693 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
11694 uint64_t OffsetLimit = Size.getQuantity();
11695 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
11696 return Error(E);
11697 }
11698
11699 if (CompareLHS < CompareRHS)
11700 return Success(CCR::Less, E);
11701 if (CompareLHS > CompareRHS)
11702 return Success(CCR::Greater, E);
11703 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +000011704 }
Richard Smith7bb00672012-02-01 01:42:44 +000011705
11706 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011707 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +000011708 assert(RHSTy->isMemberPointerType() && "invalid comparison");
11709
11710 MemberPtr LHSValue, RHSValue;
11711
11712 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000011713 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +000011714 return false;
11715
11716 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11717 return false;
11718
11719 // C++11 [expr.eq]p2:
11720 // If both operands are null, they compare equal. Otherwise if only one is
11721 // null, they compare unequal.
11722 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
11723 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011724 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000011725 }
11726
11727 // Otherwise if either is a pointer to a virtual member function, the
11728 // result is unspecified.
11729 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
11730 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011731 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000011732 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
11733 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011734 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000011735
11736 // Otherwise they compare equal if and only if they would refer to the
11737 // same member of the same most derived object or the same subobject if
11738 // they were dereferenced with a hypothetical object of the associated
11739 // class type.
11740 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011741 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000011742 }
11743
Richard Smithab44d9b2012-02-14 22:35:28 +000011744 if (LHSTy->isNullPtrType()) {
11745 assert(E->isComparisonOp() && "unexpected nullptr operation");
11746 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
11747 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
11748 // are compared, the result is true of the operator is <=, >= or ==, and
11749 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011750 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +000011751 }
11752
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011753 return DoAfter();
11754}
11755
11756bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
11757 if (!CheckLiteralType(Info, E))
11758 return false;
11759
11760 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
11761 const BinaryOperator *E) {
11762 // Evaluation succeeded. Lookup the information for the comparison category
11763 // type and fetch the VarDecl for the result.
11764 const ComparisonCategoryInfo &CmpInfo =
11765 Info.Ctx.CompCategories.getInfoForType(E->getType());
11766 const VarDecl *VD =
11767 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
11768 // Check and evaluate the result as a constant expression.
11769 LValue LV;
11770 LV.set(VD);
11771 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
11772 return false;
11773 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
11774 };
11775 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
11776 return ExprEvaluatorBaseTy::VisitBinCmp(E);
11777 });
11778}
11779
11780bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11781 // We don't call noteFailure immediately because the assignment happens after
11782 // we evaluate LHS and RHS.
11783 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
11784 return Error(E);
11785
11786 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
11787 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
11788 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
11789
11790 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
11791 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011792 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011793
11794 if (E->isComparisonOp()) {
11795 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
11796 // comparisons and then translating the result.
11797 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
11798 const BinaryOperator *E) {
11799 using CCR = ComparisonCategoryResult;
11800 bool IsEqual = ResKind == CCR::Equal,
11801 IsLess = ResKind == CCR::Less,
11802 IsGreater = ResKind == CCR::Greater;
11803 auto Op = E->getOpcode();
11804 switch (Op) {
11805 default:
11806 llvm_unreachable("unsupported binary operator");
11807 case BO_EQ:
11808 case BO_NE:
11809 return Success(IsEqual == (Op == BO_EQ), E);
11810 case BO_LT: return Success(IsLess, E);
11811 case BO_GT: return Success(IsGreater, E);
11812 case BO_LE: return Success(IsEqual || IsLess, E);
11813 case BO_GE: return Success(IsEqual || IsGreater, E);
11814 }
11815 };
11816 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
11817 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11818 });
11819 }
11820
11821 QualType LHSTy = E->getLHS()->getType();
11822 QualType RHSTy = E->getRHS()->getType();
11823
11824 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
11825 E->getOpcode() == BO_Sub) {
11826 LValue LHSValue, RHSValue;
11827
11828 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11829 if (!LHSOK && !Info.noteFailure())
11830 return false;
11831
11832 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11833 return false;
11834
11835 // Reject differing bases from the normal codepath; we special-case
11836 // comparisons to null.
11837 if (!HasSameBase(LHSValue, RHSValue)) {
11838 // Handle &&A - &&B.
11839 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
11840 return Error(E);
11841 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
11842 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
11843 if (!LHSExpr || !RHSExpr)
11844 return Error(E);
11845 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11846 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11847 if (!LHSAddrExpr || !RHSAddrExpr)
11848 return Error(E);
11849 // Make sure both labels come from the same function.
11850 if (LHSAddrExpr->getLabel()->getDeclContext() !=
11851 RHSAddrExpr->getLabel()->getDeclContext())
11852 return Error(E);
11853 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
11854 }
11855 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11856 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
11857
11858 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11859 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
11860
11861 // C++11 [expr.add]p6:
11862 // Unless both pointers point to elements of the same array object, or
11863 // one past the last element of the array object, the behavior is
11864 // undefined.
11865 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
11866 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
11867 RHSDesignator))
11868 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
11869
11870 QualType Type = E->getLHS()->getType();
Simon Pilgrimc15b38e2019-10-03 15:08:30 +000011871 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011872
11873 CharUnits ElementSize;
11874 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
11875 return false;
11876
11877 // As an extension, a type may have zero size (empty struct or union in
11878 // C, array of zero length). Pointer subtraction in such cases has
11879 // undefined behavior, so is not constant.
11880 if (ElementSize.isZero()) {
11881 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
11882 << ElementType;
11883 return false;
11884 }
11885
11886 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
11887 // and produce incorrect results when it overflows. Such behavior
11888 // appears to be non-conforming, but is common, so perhaps we should
11889 // assume the standard intended for such cases to be undefined behavior
11890 // and check for them.
11891
11892 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
11893 // overflow in the final conversion to ptrdiff_t.
11894 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
11895 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
11896 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
11897 false);
11898 APSInt TrueResult = (LHS - RHS) / ElemSize;
11899 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
11900
11901 if (Result.extend(65) != TrueResult &&
11902 !HandleOverflow(Info, E, TrueResult, E->getType()))
11903 return false;
11904 return Success(Result, E);
11905 }
11906
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000011907 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +000011908}
11909
Peter Collingbournee190dee2011-03-11 19:24:49 +000011910/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
11911/// a result as the expression's type.
11912bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
11913 const UnaryExprOrTypeTraitExpr *E) {
11914 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +000011915 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +000011916 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +000011917 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +000011918 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
11919 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000011920 else
Richard Smith6822bd72018-10-26 19:26:45 +000011921 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
11922 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000011923 }
Eli Friedman64004332009-03-23 04:38:34 +000011924
Peter Collingbournee190dee2011-03-11 19:24:49 +000011925 case UETT_VecStep: {
11926 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +000011927
Peter Collingbournee190dee2011-03-11 19:24:49 +000011928 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +000011929 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +000011930
Peter Collingbournee190dee2011-03-11 19:24:49 +000011931 // The vec_step built-in functions that take a 3-component
11932 // vector return 4. (OpenCL 1.1 spec 6.11.12)
11933 if (n == 3)
11934 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +000011935
Peter Collingbournee190dee2011-03-11 19:24:49 +000011936 return Success(n, E);
11937 } else
11938 return Success(1, E);
11939 }
11940
11941 case UETT_SizeOf: {
11942 QualType SrcTy = E->getTypeOfArgument();
11943 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
11944 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +000011945 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
11946 SrcTy = Ref->getPointeeType();
11947
Richard Smithd62306a2011-11-10 06:34:14 +000011948 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +000011949 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +000011950 return false;
Richard Smithd62306a2011-11-10 06:34:14 +000011951 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000011952 }
Alexey Bataev00396512015-07-02 03:40:19 +000011953 case UETT_OpenMPRequiredSimdAlign:
11954 assert(E->isArgumentType());
11955 return Success(
11956 Info.Ctx.toCharUnitsFromBits(
11957 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
11958 .getQuantity(),
11959 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000011960 }
11961
11962 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +000011963}
11964
Peter Collingbournee9200682011-05-13 03:29:01 +000011965bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +000011966 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +000011967 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +000011968 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011969 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +000011970 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +000011971 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +000011972 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +000011973 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +000011974 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +000011975 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +000011976 APSInt IdxResult;
11977 if (!EvaluateInteger(Idx, IdxResult, Info))
11978 return false;
11979 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
11980 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011981 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000011982 CurrentType = AT->getElementType();
11983 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
11984 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +000011985 break;
Douglas Gregor882211c2010-04-28 22:16:22 +000011986 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011987
James Y Knight7281c352015-12-29 22:31:18 +000011988 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +000011989 FieldDecl *MemberDecl = ON.getField();
11990 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000011991 if (!RT)
11992 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000011993 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000011994 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +000011995 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +000011996 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +000011997 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +000011998 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +000011999 CurrentType = MemberDecl->getType().getNonReferenceType();
12000 break;
12001 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000012002
James Y Knight7281c352015-12-29 22:31:18 +000012003 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +000012004 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +000012005
James Y Knight7281c352015-12-29 22:31:18 +000012006 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +000012007 CXXBaseSpecifier *BaseSpec = ON.getBase();
12008 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +000012009 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000012010
12011 // Find the layout of the class whose base we are looking into.
12012 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000012013 if (!RT)
12014 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000012015 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000012016 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +000012017 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12018
12019 // Find the base class itself.
12020 CurrentType = BaseSpec->getType();
12021 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
12022 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000012023 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +000012024
Douglas Gregord1702062010-04-29 00:18:15 +000012025 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +000012026 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +000012027 break;
12028 }
Douglas Gregor882211c2010-04-28 22:16:22 +000012029 }
12030 }
Peter Collingbournee9200682011-05-13 03:29:01 +000012031 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000012032}
12033
Chris Lattnere13042c2008-07-11 19:10:17 +000012034bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012035 switch (E->getOpcode()) {
12036 default:
12037 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12038 // See C99 6.6p3.
12039 return Error(E);
12040 case UO_Extension:
12041 // FIXME: Should extension allow i-c-e extension expressions in its scope?
12042 // If so, we could clear the diagnostic ID.
12043 return Visit(E->getSubExpr());
12044 case UO_Plus:
12045 // The result is just the value.
12046 return Visit(E->getSubExpr());
12047 case UO_Minus: {
12048 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +000012049 return false;
12050 if (!Result.isInt()) return Error(E);
12051 const APSInt &Value = Result.getInt();
12052 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
12053 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
12054 E->getType()))
12055 return false;
Richard Smithfe800032012-01-31 04:08:20 +000012056 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +000012057 }
12058 case UO_Not: {
12059 if (!Visit(E->getSubExpr()))
12060 return false;
12061 if (!Result.isInt()) return Error(E);
12062 return Success(~Result.getInt(), E);
12063 }
12064 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +000012065 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +000012066 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +000012067 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +000012068 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +000012069 }
Anders Carlsson9c181652008-07-08 14:35:21 +000012070 }
Anders Carlsson9c181652008-07-08 14:35:21 +000012071}
Mike Stump11289f42009-09-09 15:08:12 +000012072
Chris Lattner477c4be2008-07-12 01:15:53 +000012073/// HandleCast - This is used to evaluate implicit or explicit casts where the
12074/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +000012075bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
12076 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000012077 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +000012078 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000012079
Eli Friedmanc757de22011-03-25 00:43:55 +000012080 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +000012081 case CK_BaseToDerived:
12082 case CK_DerivedToBase:
12083 case CK_UncheckedDerivedToBase:
12084 case CK_Dynamic:
12085 case CK_ToUnion:
12086 case CK_ArrayToPointerDecay:
12087 case CK_FunctionToPointerDecay:
12088 case CK_NullToPointer:
12089 case CK_NullToMemberPointer:
12090 case CK_BaseToDerivedMemberPointer:
12091 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +000012092 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +000012093 case CK_ConstructorConversion:
12094 case CK_IntegralToPointer:
12095 case CK_ToVoid:
12096 case CK_VectorSplat:
12097 case CK_IntegralToFloating:
12098 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000012099 case CK_CPointerToObjCPointerCast:
12100 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000012101 case CK_AnyPointerToBlockPointerCast:
12102 case CK_ObjCObjectLValueCast:
12103 case CK_FloatingRealToComplex:
12104 case CK_FloatingComplexToReal:
12105 case CK_FloatingComplexCast:
12106 case CK_FloatingComplexToIntegralComplex:
12107 case CK_IntegralRealToComplex:
12108 case CK_IntegralComplexCast:
12109 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +000012110 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000012111 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000012112 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000012113 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000012114 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000012115 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +000012116 case CK_IntegralToFixedPoint:
Eli Friedmanc757de22011-03-25 00:43:55 +000012117 llvm_unreachable("invalid cast kind for integral value");
12118
Eli Friedman9faf2f92011-03-25 19:07:11 +000012119 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000012120 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000012121 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +000012122 case CK_ARCProduceObject:
12123 case CK_ARCConsumeObject:
12124 case CK_ARCReclaimReturnedObject:
12125 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000012126 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012127 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000012128
Richard Smith4ef685b2012-01-17 21:17:26 +000012129 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +000012130 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000012131 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +000012132 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000012133 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000012134 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000012135
12136 case CK_MemberPointerToBoolean:
12137 case CK_PointerToBoolean:
12138 case CK_IntegralToBoolean:
12139 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +000012140 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +000012141 case CK_FloatingComplexToBoolean:
12142 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +000012143 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +000012144 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +000012145 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +000012146 uint64_t IntResult = BoolResult;
12147 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
12148 IntResult = (uint64_t)-1;
12149 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +000012150 }
12151
Leonard Chan8f7caae2019-03-06 00:28:43 +000012152 case CK_FixedPointToIntegral: {
12153 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
12154 if (!EvaluateFixedPoint(SubExpr, Src, Info))
12155 return false;
12156 bool Overflowed;
12157 llvm::APSInt Result = Src.convertToInt(
12158 Info.Ctx.getIntWidth(DestType),
12159 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
12160 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12161 return false;
12162 return Success(Result, E);
12163 }
12164
Leonard Chanb4ba4672018-10-23 17:55:35 +000012165 case CK_FixedPointToBoolean: {
12166 // Unsigned padding does not affect this.
12167 APValue Val;
12168 if (!Evaluate(Val, Info, SubExpr))
12169 return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000012170 return Success(Val.getFixedPoint().getBoolValue(), E);
Leonard Chanb4ba4672018-10-23 17:55:35 +000012171 }
12172
Eli Friedmanc757de22011-03-25 00:43:55 +000012173 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +000012174 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +000012175 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +000012176
Eli Friedman742421e2009-02-20 01:15:07 +000012177 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +000012178 // Allow casts of address-of-label differences if they are no-ops
12179 // or narrowing. (The narrowing case isn't actually guaranteed to
12180 // be constant-evaluatable except in some narrow cases which are hard
12181 // to detect here. We let it through on the assumption the user knows
12182 // what they are doing.)
12183 if (Result.isAddrLabelDiff())
12184 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +000012185 // Only allow casts of lvalues if they are lossless.
12186 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
12187 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +000012188
Richard Smith911e1422012-01-30 22:27:01 +000012189 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
12190 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +000012191 }
Mike Stump11289f42009-09-09 15:08:12 +000012192
Eli Friedmanc757de22011-03-25 00:43:55 +000012193 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +000012194 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
12195
John McCall45d55e42010-05-07 21:00:08 +000012196 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +000012197 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +000012198 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +000012199
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000012200 if (LV.getLValueBase()) {
12201 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +000012202 // FIXME: Allow a larger integer size than the pointer size, and allow
12203 // narrowing back down to pointer width in subsequent integral casts.
12204 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000012205 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +000012206 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +000012207
Richard Smithcf74da72011-11-16 07:18:12 +000012208 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +000012209 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000012210 return true;
12211 }
12212
Hans Wennborgdd1ea8a2019-03-06 10:26:19 +000012213 APSInt AsInt;
12214 APValue V;
12215 LV.moveInto(V);
12216 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
12217 llvm_unreachable("Can't cast this!");
Yaxun Liu402804b2016-12-15 08:09:08 +000012218
Richard Smith911e1422012-01-30 22:27:01 +000012219 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +000012220 }
Eli Friedman9a156e52008-11-12 09:44:48 +000012221
Eli Friedmanc757de22011-03-25 00:43:55 +000012222 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +000012223 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000012224 if (!EvaluateComplex(SubExpr, C, Info))
12225 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +000012226 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000012227 }
Eli Friedmanc2b50172009-02-22 11:46:18 +000012228
Eli Friedmanc757de22011-03-25 00:43:55 +000012229 case CK_FloatingToIntegral: {
12230 APFloat F(0.0);
12231 if (!EvaluateFloat(SubExpr, F, Info))
12232 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +000012233
Richard Smith357362d2011-12-13 06:39:58 +000012234 APSInt Value;
12235 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
12236 return false;
12237 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +000012238 }
12239 }
Mike Stump11289f42009-09-09 15:08:12 +000012240
Eli Friedmanc757de22011-03-25 00:43:55 +000012241 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +000012242}
Anders Carlssonb5ad0212008-07-08 14:30:00 +000012243
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000012244bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12245 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000012246 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012247 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12248 return false;
12249 if (!LV.isComplexInt())
12250 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000012251 return Success(LV.getComplexIntReal(), E);
12252 }
12253
12254 return Visit(E->getSubExpr());
12255}
12256
Eli Friedman4e7a2412009-02-27 04:45:43 +000012257bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000012258 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +000012259 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012260 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12261 return false;
12262 if (!LV.isComplexInt())
12263 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000012264 return Success(LV.getComplexIntImag(), E);
12265 }
12266
Richard Smith4a678122011-10-24 18:44:57 +000012267 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +000012268 return Success(0, E);
12269}
12270
Douglas Gregor820ba7b2011-01-04 17:33:58 +000012271bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
12272 return Success(E->getPackLength(), E);
12273}
12274
Sebastian Redl5f0180d2010-09-10 20:55:47 +000012275bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
12276 return Success(E->getValue(), E);
12277}
12278
Saar Raz5d98ba62019-10-15 15:24:26 +000012279bool IntExprEvaluator::VisitConceptSpecializationExpr(
12280 const ConceptSpecializationExpr *E) {
12281 return Success(E->isSatisfied(), E);
12282}
12283
12284
Leonard Chandb01c3a2018-06-20 17:19:40 +000012285bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12286 switch (E->getOpcode()) {
12287 default:
12288 // Invalid unary operators
12289 return Error(E);
12290 case UO_Plus:
12291 // The result is just the value.
12292 return Visit(E->getSubExpr());
12293 case UO_Minus: {
12294 if (!Visit(E->getSubExpr())) return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000012295 if (!Result.isFixedPoint())
12296 return Error(E);
12297 bool Overflowed;
12298 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
12299 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
12300 return false;
12301 return Success(Negated, E);
Leonard Chandb01c3a2018-06-20 17:19:40 +000012302 }
12303 case UO_LNot: {
12304 bool bres;
12305 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12306 return false;
12307 return Success(!bres, E);
12308 }
12309 }
12310}
12311
Leonard Chand3f3e162019-01-18 21:04:25 +000012312bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
12313 const Expr *SubExpr = E->getSubExpr();
12314 QualType DestType = E->getType();
12315 assert(DestType->isFixedPointType() &&
12316 "Expected destination type to be a fixed point type");
12317 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
12318
12319 switch (E->getCastKind()) {
12320 case CK_FixedPointCast: {
12321 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
12322 if (!EvaluateFixedPoint(SubExpr, Src, Info))
12323 return false;
12324 bool Overflowed;
12325 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
12326 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12327 return false;
12328 return Success(Result, E);
12329 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000012330 case CK_IntegralToFixedPoint: {
12331 APSInt Src;
12332 if (!EvaluateInteger(SubExpr, Src, Info))
12333 return false;
12334
12335 bool Overflowed;
12336 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
12337 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
12338
12339 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
12340 return false;
12341
12342 return Success(IntResult, E);
12343 }
Leonard Chand3f3e162019-01-18 21:04:25 +000012344 case CK_NoOp:
12345 case CK_LValueToRValue:
12346 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12347 default:
12348 return Error(E);
12349 }
12350}
12351
12352bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12353 const Expr *LHS = E->getLHS();
12354 const Expr *RHS = E->getRHS();
12355 FixedPointSemantics ResultFXSema =
12356 Info.Ctx.getFixedPointSemantics(E->getType());
12357
12358 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
12359 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
12360 return false;
12361 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
12362 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
12363 return false;
12364
12365 switch (E->getOpcode()) {
12366 case BO_Add: {
12367 bool AddOverflow, ConversionOverflow;
12368 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
12369 .convert(ResultFXSema, &ConversionOverflow);
12370 if ((AddOverflow || ConversionOverflow) &&
12371 !HandleOverflow(Info, E, Result, E->getType()))
12372 return false;
12373 return Success(Result, E);
12374 }
12375 default:
12376 return false;
12377 }
12378 llvm_unreachable("Should've exited before this");
12379}
12380
Chris Lattner05706e882008-07-11 18:11:29 +000012381//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +000012382// Float Evaluation
12383//===----------------------------------------------------------------------===//
12384
12385namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000012386class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000012387 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +000012388 APFloat &Result;
12389public:
12390 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +000012391 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +000012392
Richard Smith2e312c82012-03-03 22:46:17 +000012393 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000012394 Result = V.getFloat();
12395 return true;
12396 }
Eli Friedman24c01542008-08-22 00:06:13 +000012397
Richard Smithfddd3842011-12-30 21:15:51 +000012398 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +000012399 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
12400 return true;
12401 }
12402
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012403 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +000012404
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012405 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +000012406 bool VisitBinaryOperator(const BinaryOperator *E);
12407 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000012408 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +000012409
John McCallb1fb0d32010-05-07 22:08:54 +000012410 bool VisitUnaryReal(const UnaryOperator *E);
12411 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +000012412
Richard Smithfddd3842011-12-30 21:15:51 +000012413 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +000012414};
12415} // end anonymous namespace
12416
12417static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000012418 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +000012419 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +000012420}
12421
Jay Foad39c79802011-01-12 09:06:06 +000012422static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +000012423 QualType ResultTy,
12424 const Expr *Arg,
12425 bool SNaN,
12426 llvm::APFloat &Result) {
12427 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
12428 if (!S) return false;
12429
12430 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
12431
12432 llvm::APInt fill;
12433
12434 // Treat empty strings as if they were zero.
12435 if (S->getString().empty())
12436 fill = llvm::APInt(32, 0);
12437 else if (S->getString().getAsInteger(0, fill))
12438 return false;
12439
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +000012440 if (Context.getTargetInfo().isNan2008()) {
12441 if (SNaN)
12442 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12443 else
12444 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12445 } else {
12446 // Prior to IEEE 754-2008, architectures were allowed to choose whether
12447 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
12448 // a different encoding to what became a standard in 2008, and for pre-
12449 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
12450 // sNaN. This is now known as "legacy NaN" encoding.
12451 if (SNaN)
12452 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12453 else
12454 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12455 }
12456
John McCall16291492010-02-28 13:00:19 +000012457 return true;
12458}
12459
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012460bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000012461 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000012462 default:
12463 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12464
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012465 case Builtin::BI__builtin_huge_val:
12466 case Builtin::BI__builtin_huge_valf:
12467 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012468 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012469 case Builtin::BI__builtin_inf:
12470 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012471 case Builtin::BI__builtin_infl:
12472 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000012473 const llvm::fltSemantics &Sem =
12474 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000012475 Result = llvm::APFloat::getInf(Sem);
12476 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000012477 }
Mike Stump11289f42009-09-09 15:08:12 +000012478
John McCall16291492010-02-28 13:00:19 +000012479 case Builtin::BI__builtin_nans:
12480 case Builtin::BI__builtin_nansf:
12481 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012482 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012483 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12484 true, Result))
12485 return Error(E);
12486 return true;
John McCall16291492010-02-28 13:00:19 +000012487
Chris Lattner0b7282e2008-10-06 06:31:58 +000012488 case Builtin::BI__builtin_nan:
12489 case Builtin::BI__builtin_nanf:
12490 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012491 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000012492 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000012493 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000012494 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12495 false, Result))
12496 return Error(E);
12497 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012498
12499 case Builtin::BI__builtin_fabs:
12500 case Builtin::BI__builtin_fabsf:
12501 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012502 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012503 if (!EvaluateFloat(E->getArg(0), Result, Info))
12504 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012505
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012506 if (Result.isNegative())
12507 Result.changeSign();
12508 return true;
12509
Richard Smith8889a3d2013-06-13 06:26:32 +000012510 // FIXME: Builtin::BI__builtin_powi
12511 // FIXME: Builtin::BI__builtin_powif
12512 // FIXME: Builtin::BI__builtin_powil
12513
Mike Stump11289f42009-09-09 15:08:12 +000012514 case Builtin::BI__builtin_copysign:
12515 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000012516 case Builtin::BI__builtin_copysignl:
12517 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012518 APFloat RHS(0.);
12519 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
12520 !EvaluateFloat(E->getArg(1), RHS, Info))
12521 return false;
12522 Result.copySign(RHS);
12523 return true;
12524 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012525 }
12526}
12527
John McCallb1fb0d32010-05-07 22:08:54 +000012528bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000012529 if (E->getSubExpr()->getType()->isAnyComplexType()) {
12530 ComplexValue CV;
12531 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12532 return false;
12533 Result = CV.FloatReal;
12534 return true;
12535 }
12536
12537 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000012538}
12539
12540bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000012541 if (E->getSubExpr()->getType()->isAnyComplexType()) {
12542 ComplexValue CV;
12543 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12544 return false;
12545 Result = CV.FloatImag;
12546 return true;
12547 }
12548
Richard Smith4a678122011-10-24 18:44:57 +000012549 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000012550 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
12551 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000012552 return true;
12553}
12554
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012555bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012556 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012557 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000012558 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000012559 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000012560 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000012561 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
12562 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012563 Result.changeSign();
12564 return true;
12565 }
12566}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000012567
Eli Friedman24c01542008-08-22 00:06:13 +000012568bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000012569 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12570 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000012571
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000012572 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000012573 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000012574 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000012575 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000012576 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
12577 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000012578}
12579
12580bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
12581 Result = E->getValue();
12582 return true;
12583}
12584
Peter Collingbournee9200682011-05-13 03:29:01 +000012585bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
12586 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000012587
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012588 switch (E->getCastKind()) {
12589 default:
Richard Smith11562c52011-10-28 17:51:58 +000012590 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012591
12592 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000012593 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000012594 return EvaluateInteger(SubExpr, IntResult, Info) &&
12595 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
12596 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000012597 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012598
12599 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000012600 if (!Visit(SubExpr))
12601 return false;
Richard Smith357362d2011-12-13 06:39:58 +000012602 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
12603 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000012604 }
John McCalld7646252010-11-14 08:17:51 +000012605
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012606 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000012607 ComplexValue V;
12608 if (!EvaluateComplex(SubExpr, V, Info))
12609 return false;
12610 Result = V.getComplexFloatReal();
12611 return true;
12612 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000012613 }
Eli Friedman9a156e52008-11-12 09:44:48 +000012614}
12615
Eli Friedman24c01542008-08-22 00:06:13 +000012616//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012617// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000012618//===----------------------------------------------------------------------===//
12619
12620namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000012621class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000012622 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000012623 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000012624
Anders Carlsson537969c2008-11-16 20:27:53 +000012625public:
John McCall93d91dc2010-05-07 17:22:02 +000012626 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000012627 : ExprEvaluatorBaseTy(info), Result(Result) {}
12628
Richard Smith2e312c82012-03-03 22:46:17 +000012629 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000012630 Result.setFrom(V);
12631 return true;
12632 }
Mike Stump11289f42009-09-09 15:08:12 +000012633
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012634 bool ZeroInitialization(const Expr *E);
12635
Anders Carlsson537969c2008-11-16 20:27:53 +000012636 //===--------------------------------------------------------------------===//
12637 // Visitor Methods
12638 //===--------------------------------------------------------------------===//
12639
Peter Collingbournee9200682011-05-13 03:29:01 +000012640 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000012641 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000012642 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012643 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012644 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000012645};
12646} // end anonymous namespace
12647
John McCall93d91dc2010-05-07 17:22:02 +000012648static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
12649 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000012650 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000012651 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000012652}
12653
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012654bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000012655 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012656 if (ElemTy->isRealFloatingType()) {
12657 Result.makeComplexFloat();
12658 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
12659 Result.FloatReal = Zero;
12660 Result.FloatImag = Zero;
12661 } else {
12662 Result.makeComplexInt();
12663 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
12664 Result.IntReal = Zero;
12665 Result.IntImag = Zero;
12666 }
12667 return true;
12668}
12669
Peter Collingbournee9200682011-05-13 03:29:01 +000012670bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
12671 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012672
12673 if (SubExpr->getType()->isRealFloatingType()) {
12674 Result.makeComplexFloat();
12675 APFloat &Imag = Result.FloatImag;
12676 if (!EvaluateFloat(SubExpr, Imag, Info))
12677 return false;
12678
12679 Result.FloatReal = APFloat(Imag.getSemantics());
12680 return true;
12681 } else {
12682 assert(SubExpr->getType()->isIntegerType() &&
12683 "Unexpected imaginary literal.");
12684
12685 Result.makeComplexInt();
12686 APSInt &Imag = Result.IntImag;
12687 if (!EvaluateInteger(SubExpr, Imag, Info))
12688 return false;
12689
12690 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
12691 return true;
12692 }
12693}
12694
Peter Collingbournee9200682011-05-13 03:29:01 +000012695bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012696
John McCallfcef3cf2010-12-14 17:51:41 +000012697 switch (E->getCastKind()) {
12698 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000012699 case CK_BaseToDerived:
12700 case CK_DerivedToBase:
12701 case CK_UncheckedDerivedToBase:
12702 case CK_Dynamic:
12703 case CK_ToUnion:
12704 case CK_ArrayToPointerDecay:
12705 case CK_FunctionToPointerDecay:
12706 case CK_NullToPointer:
12707 case CK_NullToMemberPointer:
12708 case CK_BaseToDerivedMemberPointer:
12709 case CK_DerivedToBaseMemberPointer:
12710 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000012711 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000012712 case CK_ConstructorConversion:
12713 case CK_IntegralToPointer:
12714 case CK_PointerToIntegral:
12715 case CK_PointerToBoolean:
12716 case CK_ToVoid:
12717 case CK_VectorSplat:
12718 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000012719 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000012720 case CK_IntegralToBoolean:
12721 case CK_IntegralToFloating:
12722 case CK_FloatingToIntegral:
12723 case CK_FloatingToBoolean:
12724 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000012725 case CK_CPointerToObjCPointerCast:
12726 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000012727 case CK_AnyPointerToBlockPointerCast:
12728 case CK_ObjCObjectLValueCast:
12729 case CK_FloatingComplexToReal:
12730 case CK_FloatingComplexToBoolean:
12731 case CK_IntegralComplexToReal:
12732 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000012733 case CK_ARCProduceObject:
12734 case CK_ARCConsumeObject:
12735 case CK_ARCReclaimReturnedObject:
12736 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000012737 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000012738 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000012739 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000012740 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000012741 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000012742 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000012743 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000012744 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +000012745 case CK_FixedPointToIntegral:
12746 case CK_IntegralToFixedPoint:
John McCallfcef3cf2010-12-14 17:51:41 +000012747 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000012748
John McCallfcef3cf2010-12-14 17:51:41 +000012749 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000012750 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000012751 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000012752 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000012753 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000012754
12755 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000012756 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000012757 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012758 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000012759
12760 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012761 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000012762 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012763 return false;
12764
John McCallfcef3cf2010-12-14 17:51:41 +000012765 Result.makeComplexFloat();
12766 Result.FloatImag = APFloat(Real.getSemantics());
12767 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012768 }
12769
John McCallfcef3cf2010-12-14 17:51:41 +000012770 case CK_FloatingComplexCast: {
12771 if (!Visit(E->getSubExpr()))
12772 return false;
12773
Simon Pilgrimc15b38e2019-10-03 15:08:30 +000012774 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012775 QualType From
Simon Pilgrimc15b38e2019-10-03 15:08:30 +000012776 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012777
Richard Smith357362d2011-12-13 06:39:58 +000012778 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
12779 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012780 }
12781
12782 case CK_FloatingComplexToIntegralComplex: {
12783 if (!Visit(E->getSubExpr()))
12784 return false;
12785
Simon Pilgrimc15b38e2019-10-03 15:08:30 +000012786 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012787 QualType From
Simon Pilgrimc15b38e2019-10-03 15:08:30 +000012788 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012789 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000012790 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
12791 To, Result.IntReal) &&
12792 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
12793 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012794 }
12795
12796 case CK_IntegralRealToComplex: {
12797 APSInt &Real = Result.IntReal;
12798 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
12799 return false;
12800
12801 Result.makeComplexInt();
12802 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
12803 return true;
12804 }
12805
12806 case CK_IntegralComplexCast: {
12807 if (!Visit(E->getSubExpr()))
12808 return false;
12809
Simon Pilgrimc15b38e2019-10-03 15:08:30 +000012810 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012811 QualType From
Simon Pilgrimc15b38e2019-10-03 15:08:30 +000012812 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012813
Richard Smith911e1422012-01-30 22:27:01 +000012814 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
12815 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012816 return true;
12817 }
12818
12819 case CK_IntegralComplexToFloatingComplex: {
12820 if (!Visit(E->getSubExpr()))
12821 return false;
12822
Ted Kremenek28831752012-08-23 20:46:57 +000012823 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012824 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000012825 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000012826 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000012827 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
12828 To, Result.FloatReal) &&
12829 HandleIntToFloatCast(Info, E, From, Result.IntImag,
12830 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000012831 }
12832 }
12833
12834 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000012835}
12836
John McCall93d91dc2010-05-07 17:22:02 +000012837bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000012838 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000012839 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12840
Chandler Carrutha216cad2014-10-11 00:57:18 +000012841 // Track whether the LHS or RHS is real at the type system level. When this is
12842 // the case we can simplify our evaluation strategy.
12843 bool LHSReal = false, RHSReal = false;
12844
12845 bool LHSOK;
12846 if (E->getLHS()->getType()->isRealFloatingType()) {
12847 LHSReal = true;
12848 APFloat &Real = Result.FloatReal;
12849 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
12850 if (LHSOK) {
12851 Result.makeComplexFloat();
12852 Result.FloatImag = APFloat(Real.getSemantics());
12853 }
12854 } else {
12855 LHSOK = Visit(E->getLHS());
12856 }
George Burgess IVa145e252016-05-25 22:38:36 +000012857 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000012858 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012859
John McCall93d91dc2010-05-07 17:22:02 +000012860 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000012861 if (E->getRHS()->getType()->isRealFloatingType()) {
12862 RHSReal = true;
12863 APFloat &Real = RHS.FloatReal;
12864 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
12865 return false;
12866 RHS.makeComplexFloat();
12867 RHS.FloatImag = APFloat(Real.getSemantics());
12868 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000012869 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012870
Chandler Carrutha216cad2014-10-11 00:57:18 +000012871 assert(!(LHSReal && RHSReal) &&
12872 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000012873 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012874 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000012875 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012876 if (Result.isComplexFloat()) {
12877 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
12878 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012879 if (LHSReal)
12880 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
12881 else if (!RHSReal)
12882 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
12883 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012884 } else {
12885 Result.getComplexIntReal() += RHS.getComplexIntReal();
12886 Result.getComplexIntImag() += RHS.getComplexIntImag();
12887 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012888 break;
John McCalle3027922010-08-25 11:45:40 +000012889 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012890 if (Result.isComplexFloat()) {
12891 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
12892 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000012893 if (LHSReal) {
12894 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
12895 Result.getComplexFloatImag().changeSign();
12896 } else if (!RHSReal) {
12897 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
12898 APFloat::rmNearestTiesToEven);
12899 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000012900 } else {
12901 Result.getComplexIntReal() -= RHS.getComplexIntReal();
12902 Result.getComplexIntImag() -= RHS.getComplexIntImag();
12903 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012904 break;
John McCalle3027922010-08-25 11:45:40 +000012905 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012906 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000012907 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000012908 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000012909 // following naming scheme:
12910 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000012911 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000012912 APFloat &A = LHS.getComplexFloatReal();
12913 APFloat &B = LHS.getComplexFloatImag();
12914 APFloat &C = RHS.getComplexFloatReal();
12915 APFloat &D = RHS.getComplexFloatImag();
12916 APFloat &ResR = Result.getComplexFloatReal();
12917 APFloat &ResI = Result.getComplexFloatImag();
12918 if (LHSReal) {
12919 assert(!RHSReal && "Cannot have two real operands for a complex op!");
12920 ResR = A * C;
12921 ResI = A * D;
12922 } else if (RHSReal) {
12923 ResR = C * A;
12924 ResI = C * B;
12925 } else {
12926 // In the fully general case, we need to handle NaNs and infinities
12927 // robustly.
12928 APFloat AC = A * C;
12929 APFloat BD = B * D;
12930 APFloat AD = A * D;
12931 APFloat BC = B * C;
12932 ResR = AC - BD;
12933 ResI = AD + BC;
12934 if (ResR.isNaN() && ResI.isNaN()) {
12935 bool Recalc = false;
12936 if (A.isInfinity() || B.isInfinity()) {
12937 A = APFloat::copySign(
12938 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
12939 B = APFloat::copySign(
12940 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
12941 if (C.isNaN())
12942 C = APFloat::copySign(APFloat(C.getSemantics()), C);
12943 if (D.isNaN())
12944 D = APFloat::copySign(APFloat(D.getSemantics()), D);
12945 Recalc = true;
12946 }
12947 if (C.isInfinity() || D.isInfinity()) {
12948 C = APFloat::copySign(
12949 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
12950 D = APFloat::copySign(
12951 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
12952 if (A.isNaN())
12953 A = APFloat::copySign(APFloat(A.getSemantics()), A);
12954 if (B.isNaN())
12955 B = APFloat::copySign(APFloat(B.getSemantics()), B);
12956 Recalc = true;
12957 }
12958 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
12959 AD.isInfinity() || BC.isInfinity())) {
12960 if (A.isNaN())
12961 A = APFloat::copySign(APFloat(A.getSemantics()), A);
12962 if (B.isNaN())
12963 B = APFloat::copySign(APFloat(B.getSemantics()), B);
12964 if (C.isNaN())
12965 C = APFloat::copySign(APFloat(C.getSemantics()), C);
12966 if (D.isNaN())
12967 D = APFloat::copySign(APFloat(D.getSemantics()), D);
12968 Recalc = true;
12969 }
12970 if (Recalc) {
12971 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
12972 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
12973 }
12974 }
12975 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012976 } else {
John McCall93d91dc2010-05-07 17:22:02 +000012977 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000012978 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012979 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
12980 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000012981 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000012982 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
12983 LHS.getComplexIntImag() * RHS.getComplexIntReal());
12984 }
12985 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012986 case BO_Div:
12987 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000012988 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000012989 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000012990 // following naming scheme:
12991 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012992 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000012993 APFloat &A = LHS.getComplexFloatReal();
12994 APFloat &B = LHS.getComplexFloatImag();
12995 APFloat &C = RHS.getComplexFloatReal();
12996 APFloat &D = RHS.getComplexFloatImag();
12997 APFloat &ResR = Result.getComplexFloatReal();
12998 APFloat &ResI = Result.getComplexFloatImag();
12999 if (RHSReal) {
13000 ResR = A / C;
13001 ResI = B / C;
13002 } else {
13003 if (LHSReal) {
13004 // No real optimizations we can do here, stub out with zero.
13005 B = APFloat::getZero(A.getSemantics());
13006 }
13007 int DenomLogB = 0;
13008 APFloat MaxCD = maxnum(abs(C), abs(D));
13009 if (MaxCD.isFinite()) {
13010 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000013011 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
13012 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000013013 }
13014 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000013015 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
13016 APFloat::rmNearestTiesToEven);
13017 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
13018 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000013019 if (ResR.isNaN() && ResI.isNaN()) {
13020 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
13021 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
13022 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
13023 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
13024 D.isFinite()) {
13025 A = APFloat::copySign(
13026 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13027 B = APFloat::copySign(
13028 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13029 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
13030 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
13031 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
13032 C = APFloat::copySign(
13033 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13034 D = APFloat::copySign(
13035 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13036 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
13037 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
13038 }
13039 }
13040 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000013041 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000013042 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
13043 return Error(E, diag::note_expr_divide_by_zero);
13044
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000013045 ComplexValue LHS = Result;
13046 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
13047 RHS.getComplexIntImag() * RHS.getComplexIntImag();
13048 Result.getComplexIntReal() =
13049 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
13050 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
13051 Result.getComplexIntImag() =
13052 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
13053 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
13054 }
13055 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000013056 }
13057
John McCall93d91dc2010-05-07 17:22:02 +000013058 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000013059}
13060
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000013061bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13062 // Get the operand value into 'Result'.
13063 if (!Visit(E->getSubExpr()))
13064 return false;
13065
13066 switch (E->getOpcode()) {
13067 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000013068 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000013069 case UO_Extension:
13070 return true;
13071 case UO_Plus:
13072 // The result is always just the subexpr.
13073 return true;
13074 case UO_Minus:
13075 if (Result.isComplexFloat()) {
13076 Result.getComplexFloatReal().changeSign();
13077 Result.getComplexFloatImag().changeSign();
13078 }
13079 else {
13080 Result.getComplexIntReal() = -Result.getComplexIntReal();
13081 Result.getComplexIntImag() = -Result.getComplexIntImag();
13082 }
13083 return true;
13084 case UO_Not:
13085 if (Result.isComplexFloat())
13086 Result.getComplexFloatImag().changeSign();
13087 else
13088 Result.getComplexIntImag() = -Result.getComplexIntImag();
13089 return true;
13090 }
13091}
13092
Eli Friedmanc4b251d2012-01-10 04:58:17 +000013093bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
13094 if (E->getNumInits() == 2) {
13095 if (E->getType()->isComplexType()) {
13096 Result.makeComplexFloat();
13097 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
13098 return false;
13099 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
13100 return false;
13101 } else {
13102 Result.makeComplexInt();
13103 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
13104 return false;
13105 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
13106 return false;
13107 }
13108 return true;
13109 }
13110 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
13111}
13112
Anders Carlsson537969c2008-11-16 20:27:53 +000013113//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000013114// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
13115// implicit conversion.
13116//===----------------------------------------------------------------------===//
13117
13118namespace {
13119class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000013120 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000013121 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000013122 APValue &Result;
13123public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000013124 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
13125 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000013126
13127 bool Success(const APValue &V, const Expr *E) {
13128 Result = V;
13129 return true;
13130 }
13131
13132 bool ZeroInitialization(const Expr *E) {
13133 ImplicitValueInitExpr VIE(
13134 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000013135 // For atomic-qualified class (and array) types in C++, initialize the
13136 // _Atomic-wrapped subobject directly, in-place.
13137 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
13138 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000013139 }
13140
13141 bool VisitCastExpr(const CastExpr *E) {
13142 switch (E->getCastKind()) {
13143 default:
13144 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13145 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000013146 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
13147 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000013148 }
13149 }
13150};
13151} // end anonymous namespace
13152
Richard Smith64cb9ca2017-02-22 22:09:50 +000013153static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
13154 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000013155 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000013156 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000013157}
13158
13159//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000013160// Void expression evaluation, primarily for a cast to void on the LHS of a
13161// comma operator
13162//===----------------------------------------------------------------------===//
13163
13164namespace {
13165class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000013166 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000013167public:
13168 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
13169
Richard Smith2e312c82012-03-03 22:46:17 +000013170 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000013171
Richard Smith7cd577b2017-08-17 19:35:50 +000013172 bool ZeroInitialization(const Expr *E) { return true; }
13173
Richard Smith42d3af92011-12-07 00:43:50 +000013174 bool VisitCastExpr(const CastExpr *E) {
13175 switch (E->getCastKind()) {
13176 default:
13177 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13178 case CK_ToVoid:
13179 VisitIgnoredValue(E->getSubExpr());
13180 return true;
13181 }
13182 }
Hal Finkela8443c32014-07-17 14:49:58 +000013183
13184 bool VisitCallExpr(const CallExpr *E) {
13185 switch (E->getBuiltinCallee()) {
Hal Finkela8443c32014-07-17 14:49:58 +000013186 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000013187 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000013188 // The argument is not evaluated!
13189 return true;
Richard Smith19ad5232019-10-03 00:39:33 +000013190
13191 case Builtin::BI__builtin_operator_delete:
13192 return HandleOperatorDeleteCall(Info, E);
13193
13194 default:
13195 break;
Hal Finkela8443c32014-07-17 14:49:58 +000013196 }
Richard Smith19ad5232019-10-03 00:39:33 +000013197
13198 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Hal Finkela8443c32014-07-17 14:49:58 +000013199 }
Richard Smithda1b4342019-09-27 01:26:47 +000013200
13201 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
Richard Smith42d3af92011-12-07 00:43:50 +000013202};
13203} // end anonymous namespace
13204
Richard Smithda1b4342019-09-27 01:26:47 +000013205bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
13206 // We cannot speculatively evaluate a delete expression.
13207 if (Info.SpeculativeEvaluationDepth)
13208 return false;
13209
13210 FunctionDecl *OperatorDelete = E->getOperatorDelete();
13211 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
13212 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13213 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
13214 return false;
13215 }
13216
13217 const Expr *Arg = E->getArgument();
13218
13219 LValue Pointer;
13220 if (!EvaluatePointer(Arg, Pointer, Info))
13221 return false;
13222 if (Pointer.Designator.Invalid)
13223 return false;
13224
13225 // Deleting a null pointer has no effect.
13226 if (Pointer.isNullPointer()) {
13227 // This is the only case where we need to produce an extension warning:
13228 // the only other way we can succeed is if we find a dynamic allocation,
13229 // and we will have warned when we allocated it in that case.
13230 if (!Info.getLangOpts().CPlusPlus2a)
13231 Info.CCEDiag(E, diag::note_constexpr_new);
13232 return true;
13233 }
13234
Richard Smith19ad5232019-10-03 00:39:33 +000013235 Optional<DynAlloc *> Alloc = CheckDeleteKind(
13236 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
13237 if (!Alloc)
Richard Smithda1b4342019-09-27 01:26:47 +000013238 return false;
Richard Smithda1b4342019-09-27 01:26:47 +000013239 QualType AllocType = Pointer.Base.getDynamicAllocType();
13240
Richard Smithda1b4342019-09-27 01:26:47 +000013241 // For the non-array case, the designator must be empty if the static type
13242 // does not have a virtual destructor.
13243 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
13244 !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
13245 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
13246 << Arg->getType()->getPointeeType() << AllocType;
13247 return false;
13248 }
13249
Richard Smithdf3761f2019-10-07 03:14:28 +000013250 // For a class type with a virtual destructor, the selected operator delete
13251 // is the one looked up when building the destructor.
13252 if (!E->isArrayForm() && !E->isGlobalDelete()) {
13253 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
13254 if (VirtualDelete &&
13255 !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
13256 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13257 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
13258 return false;
13259 }
13260 }
13261
Richard Smith61422f92019-09-27 20:24:36 +000013262 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
13263 (*Alloc)->Value, AllocType))
Richard Smithda1b4342019-09-27 01:26:47 +000013264 return false;
13265
Richard Smith19ad5232019-10-03 00:39:33 +000013266 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
Richard Smithda1b4342019-09-27 01:26:47 +000013267 // The element was already erased. This means the destructor call also
13268 // deleted the object.
13269 // FIXME: This probably results in undefined behavior before we get this
13270 // far, and should be diagnosed elsewhere first.
13271 Info.FFDiag(E, diag::note_constexpr_double_delete);
13272 return false;
13273 }
13274
13275 return true;
13276}
13277
Richard Smith42d3af92011-12-07 00:43:50 +000013278static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
13279 assert(E->isRValue() && E->getType()->isVoidType());
13280 return VoidExprEvaluator(Info).Visit(E);
13281}
13282
13283//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000013284// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000013285//===----------------------------------------------------------------------===//
13286
Richard Smith2e312c82012-03-03 22:46:17 +000013287static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000013288 // In C, function designators are not lvalues, but we evaluate them as if they
13289 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000013290 QualType T = E->getType();
13291 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000013292 LValue LV;
13293 if (!EvaluateLValue(E, LV, Info))
13294 return false;
13295 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000013296 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000013297 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000013298 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000013299 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000013300 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013301 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000013302 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000013303 LValue LV;
13304 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013305 return false;
Richard Smith725810a2011-10-16 21:26:27 +000013306 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000013307 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000013308 llvm::APFloat F(0.0);
13309 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013310 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000013311 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000013312 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000013313 ComplexValue C;
13314 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013315 return false;
Richard Smith725810a2011-10-16 21:26:27 +000013316 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000013317 } else if (T->isFixedPointType()) {
13318 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000013319 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000013320 MemberPtr P;
13321 if (!EvaluateMemberPointer(E, P, Info))
13322 return false;
13323 P.moveInto(Result);
13324 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000013325 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000013326 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000013327 APValue &Value =
13328 Info.CurrentCall->createTemporary(E, T, false, LV);
Richard Smith08d6a2c2013-07-24 07:11:57 +000013329 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000013330 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000013331 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000013332 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000013333 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000013334 APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
Richard Smith08d6a2c2013-07-24 07:11:57 +000013335 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000013336 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000013337 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000013338 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013339 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000013340 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000013341 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000013342 if (!EvaluateVoid(E, Info))
13343 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000013344 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000013345 QualType Unqual = T.getAtomicUnqualifiedType();
13346 if (Unqual->isArrayType() || Unqual->isRecordType()) {
13347 LValue LV;
Richard Smith457226e2019-09-23 03:48:44 +000013348 APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
Richard Smith64cb9ca2017-02-22 22:09:50 +000013349 if (!EvaluateAtomic(E, &LV, Value, Info))
13350 return false;
13351 } else {
13352 if (!EvaluateAtomic(E, nullptr, Result, Info))
13353 return false;
13354 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013355 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000013356 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000013357 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000013358 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000013359 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000013360 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000013361 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000013362
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000013363 return true;
13364}
13365
Richard Smithb228a862012-02-15 02:18:13 +000013366/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
13367/// cases, the in-place evaluation is essential, since later initializers for
13368/// an object can indirectly refer to subobjects which were initialized earlier.
13369static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000013370 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000013371 assert(!E->isValueDependent());
13372
Richard Smith7525ff62013-05-09 07:14:00 +000013373 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000013374 return false;
13375
13376 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000013377 // Evaluate arrays and record types in-place, so that later initializers can
13378 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000013379 QualType T = E->getType();
13380 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000013381 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000013382 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000013383 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000013384 else if (T->isAtomicType()) {
13385 QualType Unqual = T.getAtomicUnqualifiedType();
13386 if (Unqual->isArrayType() || Unqual->isRecordType())
13387 return EvaluateAtomic(E, &This, Result, Info);
13388 }
Richard Smithed5165f2011-11-04 05:33:44 +000013389 }
13390
13391 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000013392 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000013393}
13394
Richard Smithf57d8cb2011-12-09 22:58:01 +000013395/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
13396/// lvalue-to-rvalue cast if it is an lvalue.
13397static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Nandor Lickerf584f042019-11-11 11:13:34 +000013398 if (Info.EnableNewConstInterp) {
13399 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
Nandor Licker950b70d2019-09-13 09:46:16 +000013400 return false;
Nandor Lickerf584f042019-11-11 11:13:34 +000013401 } else {
13402 if (E->getType().isNull())
13403 return false;
13404
13405 if (!CheckLiteralType(Info, E))
13406 return false;
13407
13408 if (!::Evaluate(Result, Info, E))
13409 return false;
13410
13411 if (E->isGLValue()) {
13412 LValue LV;
13413 LV.setFrom(Info.Ctx, Result);
13414 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13415 return false;
Nandor Licker950b70d2019-09-13 09:46:16 +000013416 }
13417 }
13418
Richard Smith2e312c82012-03-03 22:46:17 +000013419 // Check this core constant expression is a constant expression.
Richard Smithda1b4342019-09-27 01:26:47 +000013420 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
13421 CheckMemoryLeaks(Info);
Richard Smithf57d8cb2011-12-09 22:58:01 +000013422}
Richard Smith11562c52011-10-28 17:51:58 +000013423
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013424static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000013425 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013426 // Fast-path evaluations of integer literals, since we sometimes see files
13427 // containing vast quantities of these.
13428 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
13429 Result.Val = APValue(APSInt(L->getValue(),
13430 L->getType()->isUnsignedIntegerType()));
13431 IsConst = true;
13432 return true;
13433 }
James Dennett0492ef02014-03-14 17:44:10 +000013434
13435 // This case should be rare, but we need to check it before we check on
13436 // the type below.
13437 if (Exp->getType().isNull()) {
13438 IsConst = false;
13439 return true;
13440 }
Fangrui Song6907ce22018-07-30 19:24:48 +000013441
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013442 // FIXME: Evaluating values of large array and record types can cause
13443 // performance problems. Only do so in C++11 for now.
13444 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
13445 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000013446 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013447 IsConst = false;
13448 return true;
13449 }
13450 return false;
13451}
13452
Fangrui Song407659a2018-11-30 23:41:18 +000013453static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
13454 Expr::SideEffectsKind SEK) {
13455 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
13456 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
13457}
13458
13459static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
13460 const ASTContext &Ctx, EvalInfo &Info) {
13461 bool IsConst;
13462 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
13463 return IsConst;
13464
13465 return EvaluateAsRValue(Info, E, Result.Val);
13466}
13467
13468static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
13469 const ASTContext &Ctx,
13470 Expr::SideEffectsKind AllowSideEffects,
13471 EvalInfo &Info) {
13472 if (!E->getType()->isIntegralOrEnumerationType())
13473 return false;
13474
13475 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
13476 !ExprResult.Val.isInt() ||
13477 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13478 return false;
13479
13480 return true;
13481}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013482
Leonard Chand3f3e162019-01-18 21:04:25 +000013483static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
13484 const ASTContext &Ctx,
13485 Expr::SideEffectsKind AllowSideEffects,
13486 EvalInfo &Info) {
13487 if (!E->getType()->isFixedPointType())
13488 return false;
13489
13490 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
13491 return false;
13492
13493 if (!ExprResult.Val.isFixedPoint() ||
13494 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13495 return false;
13496
13497 return true;
13498}
13499
Richard Smith7b553f12011-10-29 00:50:52 +000013500/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000013501/// any crazy technique (that has nothing to do with language standards) that
13502/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000013503/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
13504/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000013505bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
13506 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013507 assert(!isValueDependent() &&
13508 "Expression evaluator can't be called on a dependent expression.");
Richard Smith6d4c6582013-11-05 22:18:15 +000013509 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000013510 Info.InConstantContext = InConstantContext;
13511 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000013512}
13513
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013514bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
13515 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013516 assert(!isValueDependent() &&
13517 "Expression evaluator can't be called on a dependent expression.");
Richard Smith11562c52011-10-28 17:51:58 +000013518 EvalResult Scratch;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013519 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
Richard Smith2e312c82012-03-03 22:46:17 +000013520 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000013521}
13522
Fangrui Song407659a2018-11-30 23:41:18 +000013523bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013524 SideEffectsKind AllowSideEffects,
13525 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013526 assert(!isValueDependent() &&
13527 "Expression evaluator can't be called on a dependent expression.");
Fangrui Song407659a2018-11-30 23:41:18 +000013528 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013529 Info.InConstantContext = InConstantContext;
Fangrui Song407659a2018-11-30 23:41:18 +000013530 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000013531}
13532
Leonard Chand3f3e162019-01-18 21:04:25 +000013533bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013534 SideEffectsKind AllowSideEffects,
13535 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013536 assert(!isValueDependent() &&
13537 "Expression evaluator can't be called on a dependent expression.");
Leonard Chand3f3e162019-01-18 21:04:25 +000013538 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013539 Info.InConstantContext = InConstantContext;
Leonard Chand3f3e162019-01-18 21:04:25 +000013540 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
13541}
13542
Richard Trieube234c32016-04-21 21:04:55 +000013543bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013544 SideEffectsKind AllowSideEffects,
13545 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013546 assert(!isValueDependent() &&
13547 "Expression evaluator can't be called on a dependent expression.");
13548
Richard Trieube234c32016-04-21 21:04:55 +000013549 if (!getType()->isRealFloatingType())
13550 return false;
13551
13552 EvalResult ExprResult;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013553 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
13554 !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000013555 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000013556 return false;
13557
13558 Result = ExprResult.Val.getFloat();
13559 return true;
13560}
13561
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013562bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
13563 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013564 assert(!isValueDependent() &&
13565 "Expression evaluator can't be called on a dependent expression.");
13566
Richard Smith6d4c6582013-11-05 22:18:15 +000013567 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013568 Info.InConstantContext = InConstantContext;
John McCall45d55e42010-05-07 21:00:08 +000013569 LValue LV;
Richard Smith4566f872019-09-29 05:58:31 +000013570 CheckedTemporaries CheckedTemps;
Richard Smith457226e2019-09-23 03:48:44 +000013571 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
13572 Result.HasSideEffects ||
Richard Smithb228a862012-02-15 02:18:13 +000013573 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000013574 Ctx.getLValueReferenceType(getType()), LV,
Richard Smith4566f872019-09-29 05:58:31 +000013575 Expr::EvaluateForCodeGen, CheckedTemps))
Richard Smithb228a862012-02-15 02:18:13 +000013576 return false;
13577
Richard Smith2e312c82012-03-03 22:46:17 +000013578 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000013579 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000013580}
13581
Reid Kleckner1a840d22018-05-10 18:57:35 +000013582bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
13583 const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013584 assert(!isValueDependent() &&
13585 "Expression evaluator can't be called on a dependent expression.");
13586
Reid Kleckner1a840d22018-05-10 18:57:35 +000013587 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
13588 EvalInfo Info(Ctx, Result, EM);
Eric Fiselier680e8652019-03-08 22:06:48 +000013589 Info.InConstantContext = true;
Eric Fiselieradd16a82019-04-24 02:23:30 +000013590
Richard Smithda1b4342019-09-27 01:26:47 +000013591 if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
Reid Kleckner1a840d22018-05-10 18:57:35 +000013592 return false;
13593
Richard Smith457226e2019-09-23 03:48:44 +000013594 if (!Info.discardCleanups())
13595 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13596
Richard Smith57694402019-10-08 23:37:49 +000013597 return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
13598 Result.Val, Usage) &&
Richard Smithda1b4342019-09-27 01:26:47 +000013599 CheckMemoryLeaks(Info);
Reid Kleckner1a840d22018-05-10 18:57:35 +000013600}
13601
Richard Smithd0b4dd62011-12-19 06:19:21 +000013602bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
13603 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013604 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013605 assert(!isValueDependent() &&
13606 "Expression evaluator can't be called on a dependent expression.");
13607
Richard Smithdafff942012-01-14 04:30:29 +000013608 // FIXME: Evaluating initializers for large array and record types can cause
13609 // performance problems. Only do so in C++11 for now.
13610 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013611 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000013612 return false;
13613
Richard Smithd0b4dd62011-12-19 06:19:21 +000013614 Expr::EvalStatus EStatus;
13615 EStatus.Diag = &Notes;
13616
Nandor Licker950b70d2019-09-13 09:46:16 +000013617 EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
Richard Smith0c6124b2015-12-03 01:36:22 +000013618 ? EvalInfo::EM_ConstantExpression
13619 : EvalInfo::EM_ConstantFold);
Nandor Licker950b70d2019-09-13 09:46:16 +000013620 Info.setEvaluatingDecl(VD, Value);
13621 Info.InConstantContext = true;
13622
13623 SourceLocation DeclLoc = VD->getLocation();
13624 QualType DeclTy = VD->getType();
13625
13626 if (Info.EnableNewConstInterp) {
13627 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
Nandor Lickerf584f042019-11-11 11:13:34 +000013628 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
Nandor Licker950b70d2019-09-13 09:46:16 +000013629 return false;
Nandor Lickerf584f042019-11-11 11:13:34 +000013630 } else {
13631 LValue LVal;
13632 LVal.set(VD);
13633
13634 // C++11 [basic.start.init]p2:
13635 // Variables with static storage duration or thread storage duration shall
13636 // be zero-initialized before any other initialization takes place.
13637 // This behavior is not present in C.
13638 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
13639 !DeclTy->isReferenceType()) {
13640 ImplicitValueInitExpr VIE(DeclTy);
13641 if (!EvaluateInPlace(Value, Info, LVal, &VIE,
13642 /*AllowNonLiteralTypes=*/true))
13643 return false;
Nandor Licker950b70d2019-09-13 09:46:16 +000013644 }
Richard Smithd0b4dd62011-12-19 06:19:21 +000013645
Nandor Lickerf584f042019-11-11 11:13:34 +000013646 if (!EvaluateInPlace(Value, Info, LVal, this,
13647 /*AllowNonLiteralTypes=*/true) ||
13648 EStatus.HasSideEffects)
Richard Smithfddd3842011-12-30 21:15:51 +000013649 return false;
Nandor Lickerf584f042019-11-11 11:13:34 +000013650
13651 // At this point, any lifetime-extended temporaries are completely
13652 // initialized.
13653 Info.performLifetimeExtension();
13654
13655 if (!Info.discardCleanups())
13656 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
Richard Smithfddd3842011-12-30 21:15:51 +000013657 }
Richard Smithda1b4342019-09-27 01:26:47 +000013658 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
13659 CheckMemoryLeaks(Info);
Richard Smithd0b4dd62011-12-19 06:19:21 +000013660}
13661
Richard Smith2b4fa532019-09-29 05:08:46 +000013662bool VarDecl::evaluateDestruction(
13663 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13664 assert(getEvaluatedValue() && !getEvaluatedValue()->isAbsent() &&
13665 "cannot evaluate destruction of non-constant-initialized variable");
13666
13667 Expr::EvalStatus EStatus;
13668 EStatus.Diag = &Notes;
13669
13670 // Make a copy of the value for the destructor to mutate.
13671 APValue DestroyedValue = *getEvaluatedValue();
13672
13673 EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
13674 Info.setEvaluatingDecl(this, DestroyedValue,
13675 EvalInfo::EvaluatingDeclKind::Dtor);
13676 Info.InConstantContext = true;
13677
13678 SourceLocation DeclLoc = getLocation();
13679 QualType DeclTy = getType();
13680
13681 LValue LVal;
13682 LVal.set(this);
13683
13684 // FIXME: Consider storing whether this variable has constant destruction in
13685 // the EvaluatedStmt so that CodeGen can query it.
13686 if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
13687 EStatus.HasSideEffects)
13688 return false;
13689
13690 if (!Info.discardCleanups())
13691 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13692
13693 ensureEvaluatedStmt()->HasConstantDestruction = true;
13694 return true;
13695}
13696
Richard Smith7b553f12011-10-29 00:50:52 +000013697/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
13698/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000013699bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013700 assert(!isValueDependent() &&
13701 "Expression evaluator can't be called on a dependent expression.");
13702
Anders Carlsson5b3638b2008-12-01 06:44:05 +000013703 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000013704 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000013705 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000013706}
Anders Carlsson59689ed2008-11-22 21:04:56 +000013707
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000013708APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013709 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013710 assert(!isValueDependent() &&
13711 "Expression evaluator can't be called on a dependent expression.");
13712
Fangrui Song407659a2018-11-30 23:41:18 +000013713 EvalResult EVResult;
13714 EVResult.Diag = Diag;
13715 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
13716 Info.InConstantContext = true;
13717
13718 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000013719 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000013720 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000013721 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000013722
Fangrui Song407659a2018-11-30 23:41:18 +000013723 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000013724}
John McCall864e3962010-05-07 05:32:02 +000013725
David Bolvansky3b6ae572018-10-18 20:49:06 +000013726APSInt Expr::EvaluateKnownConstIntCheckOverflow(
13727 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013728 assert(!isValueDependent() &&
13729 "Expression evaluator can't be called on a dependent expression.");
13730
Fangrui Song407659a2018-11-30 23:41:18 +000013731 EvalResult EVResult;
13732 EVResult.Diag = Diag;
Richard Smith045b2272019-09-10 21:24:09 +000013733 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000013734 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000013735 Info.CheckingForUndefinedBehavior = true;
Fangrui Song407659a2018-11-30 23:41:18 +000013736
13737 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000013738 (void)Result;
13739 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000013740 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000013741
Fangrui Song407659a2018-11-30 23:41:18 +000013742 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000013743}
13744
Richard Smithe9ff7702013-11-05 22:23:30 +000013745void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013746 assert(!isValueDependent() &&
13747 "Expression evaluator can't be called on a dependent expression.");
13748
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013749 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000013750 EvalResult EVResult;
13751 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
Richard Smith045b2272019-09-10 21:24:09 +000013752 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
13753 Info.CheckingForUndefinedBehavior = true;
Fangrui Song407659a2018-11-30 23:41:18 +000013754 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000013755 }
13756}
13757
Richard Smithe6c01442013-06-05 00:46:14 +000013758bool Expr::EvalResult::isGlobalLValue() const {
13759 assert(Val.isLValue());
13760 return IsGlobalLValue(Val.getLValueBase());
13761}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000013762
13763
John McCall864e3962010-05-07 05:32:02 +000013764/// isIntegerConstantExpr - this recursive routine will test if an expression is
13765/// an integer constant expression.
13766
13767/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
13768/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000013769
13770// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000013771// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
13772// and a (possibly null) SourceLocation indicating the location of the problem.
13773//
John McCall864e3962010-05-07 05:32:02 +000013774// Note that to reduce code duplication, this helper does no evaluation
13775// itself; the caller checks whether the expression is evaluatable, and
13776// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000013777// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000013778
Dan Gohman28ade552010-07-26 21:25:24 +000013779namespace {
13780
Richard Smith9e575da2012-12-28 13:25:52 +000013781enum ICEKind {
13782 /// This expression is an ICE.
13783 IK_ICE,
13784 /// This expression is not an ICE, but if it isn't evaluated, it's
13785 /// a legal subexpression for an ICE. This return value is used to handle
13786 /// the comma operator in C99 mode, and non-constant subexpressions.
13787 IK_ICEIfUnevaluated,
13788 /// This expression is not an ICE, and is not a legal subexpression for one.
13789 IK_NotICE
13790};
13791
John McCall864e3962010-05-07 05:32:02 +000013792struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000013793 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000013794 SourceLocation Loc;
13795
Richard Smith9e575da2012-12-28 13:25:52 +000013796 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000013797};
13798
Alexander Kornienkoab9db512015-06-22 23:07:51 +000013799}
Dan Gohman28ade552010-07-26 21:25:24 +000013800
Richard Smith9e575da2012-12-28 13:25:52 +000013801static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
13802
13803static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000013804
Craig Toppera31a8822013-08-22 07:09:37 +000013805static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000013806 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000013807 Expr::EvalStatus Status;
13808 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
13809
13810 Info.InConstantContext = true;
13811 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000013812 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013813 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000013814
John McCall864e3962010-05-07 05:32:02 +000013815 return NoDiag();
13816}
13817
Craig Toppera31a8822013-08-22 07:09:37 +000013818static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000013819 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000013820 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013821 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013822
13823 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000013824#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000013825#define STMT(Node, Base) case Expr::Node##Class:
13826#define EXPR(Node, Base)
13827#include "clang/AST/StmtNodes.inc"
13828 case Expr::PredefinedExprClass:
13829 case Expr::FloatingLiteralClass:
13830 case Expr::ImaginaryLiteralClass:
13831 case Expr::StringLiteralClass:
13832 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000013833 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000013834 case Expr::MemberExprClass:
13835 case Expr::CompoundAssignOperatorClass:
13836 case Expr::CompoundLiteralExprClass:
13837 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000013838 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000013839 case Expr::ArrayInitLoopExprClass:
13840 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000013841 case Expr::NoInitExprClass:
13842 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000013843 case Expr::ImplicitValueInitExprClass:
13844 case Expr::ParenListExprClass:
13845 case Expr::VAArgExprClass:
13846 case Expr::AddrLabelExprClass:
13847 case Expr::StmtExprClass:
13848 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000013849 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000013850 case Expr::CXXDynamicCastExprClass:
13851 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000013852 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000013853 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000013854 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000013855 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000013856 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000013857 case Expr::CXXThisExprClass:
13858 case Expr::CXXThrowExprClass:
13859 case Expr::CXXNewExprClass:
13860 case Expr::CXXDeleteExprClass:
13861 case Expr::CXXPseudoDestructorExprClass:
13862 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000013863 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000013864 case Expr::DependentScopeDeclRefExprClass:
13865 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000013866 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000013867 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000013868 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000013869 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000013870 case Expr::CXXTemporaryObjectExprClass:
13871 case Expr::CXXUnresolvedConstructExprClass:
13872 case Expr::CXXDependentScopeMemberExprClass:
13873 case Expr::UnresolvedMemberExprClass:
13874 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000013875 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000013876 case Expr::ObjCArrayLiteralClass:
13877 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000013878 case Expr::ObjCEncodeExprClass:
13879 case Expr::ObjCMessageExprClass:
13880 case Expr::ObjCSelectorExprClass:
13881 case Expr::ObjCProtocolExprClass:
13882 case Expr::ObjCIvarRefExprClass:
13883 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000013884 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000013885 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000013886 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000013887 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000013888 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000013889 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000013890 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000013891 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000013892 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000013893 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000013894 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000013895 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000013896 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000013897 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000013898 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000013899 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000013900 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000013901 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000013902 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000013903 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000013904 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013905 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000013906
Richard Smithf137f932014-01-25 20:50:08 +000013907 case Expr::InitListExprClass: {
13908 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
13909 // form "T x = { a };" is equivalent to "T x = a;".
13910 // Unless we're initializing a reference, T is a scalar as it is known to be
13911 // of integral or enumeration type.
13912 if (E->isRValue())
13913 if (cast<InitListExpr>(E)->getNumInits() == 1)
13914 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013915 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000013916 }
13917
Douglas Gregor820ba7b2011-01-04 17:33:58 +000013918 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000013919 case Expr::GNUNullExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +000013920 case Expr::SourceLocExprClass:
John McCall864e3962010-05-07 05:32:02 +000013921 return NoDiag();
13922
John McCall7c454bb2011-07-15 05:09:51 +000013923 case Expr::SubstNonTypeTemplateParmExprClass:
13924 return
13925 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
13926
Bill Wendling7c44da22018-10-31 03:48:47 +000013927 case Expr::ConstantExprClass:
13928 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
13929
John McCall864e3962010-05-07 05:32:02 +000013930 case Expr::ParenExprClass:
13931 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000013932 case Expr::GenericSelectionExprClass:
13933 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013934 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000013935 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000013936 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000013937 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000013938 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000013939 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000013940 case Expr::TypeTraitExprClass:
Saar Raz5d98ba62019-10-15 15:24:26 +000013941 case Expr::ConceptSpecializationExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000013942 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000013943 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000013944 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000013945 return NoDiag();
13946 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000013947 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000013948 // C99 6.6/3 allows function calls within unevaluated subexpressions of
13949 // constant expressions, but they can never be ICEs because an ICE cannot
13950 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000013951 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000013952 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000013953 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013954 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000013955 }
Richard Smith778dc0f2019-10-19 00:04:38 +000013956 case Expr::CXXRewrittenBinaryOperatorClass:
13957 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
13958 Ctx);
Richard Smith6365c912012-02-24 22:12:32 +000013959 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000013960 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
13961 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000013962 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000013963 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000013964 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000013965 // Parameter variables are never constants. Without this check,
13966 // getAnyInitializer() can find a default argument, which leads
13967 // to chaos.
13968 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000013969 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000013970
13971 // C++ 7.1.5.1p2
13972 // A variable of non-volatile const-qualified integral or enumeration
13973 // type initialized by an ICE can be used in ICEs.
13974 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000013975 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000013976 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000013977
Richard Smithd0b4dd62011-12-19 06:19:21 +000013978 const VarDecl *VD;
13979 // Look for a declaration of this variable that has an initializer, and
13980 // check whether it is an ICE.
13981 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
13982 return NoDiag();
13983 else
Richard Smith9e575da2012-12-28 13:25:52 +000013984 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000013985 }
13986 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013987 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000013988 }
John McCall864e3962010-05-07 05:32:02 +000013989 case Expr::UnaryOperatorClass: {
13990 const UnaryOperator *Exp = cast<UnaryOperator>(E);
13991 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000013992 case UO_PostInc:
13993 case UO_PostDec:
13994 case UO_PreInc:
13995 case UO_PreDec:
13996 case UO_AddrOf:
13997 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000013998 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000013999 // C99 6.6/3 allows increment and decrement within unevaluated
14000 // subexpressions of constant expressions, but they can never be ICEs
14001 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014002 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000014003 case UO_Extension:
14004 case UO_LNot:
14005 case UO_Plus:
14006 case UO_Minus:
14007 case UO_Not:
14008 case UO_Real:
14009 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000014010 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000014011 }
Reid Klecknere540d972018-11-01 17:51:48 +000014012 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000014013 }
14014 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000014015 // Note that per C99, offsetof must be an ICE. And AFAIK, using
14016 // EvaluateAsRValue matches the proposed gcc behavior for cases like
14017 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
14018 // compliance: we should warn earlier for offsetof expressions with
14019 // array subscripts that aren't ICEs, and if the array subscripts
14020 // are ICEs, the value of the offsetof must be an integer constant.
14021 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000014022 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000014023 case Expr::UnaryExprOrTypeTraitExprClass: {
14024 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
14025 if ((Exp->getKind() == UETT_SizeOf) &&
14026 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014027 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000014028 return NoDiag();
14029 }
14030 case Expr::BinaryOperatorClass: {
14031 const BinaryOperator *Exp = cast<BinaryOperator>(E);
14032 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000014033 case BO_PtrMemD:
14034 case BO_PtrMemI:
14035 case BO_Assign:
14036 case BO_MulAssign:
14037 case BO_DivAssign:
14038 case BO_RemAssign:
14039 case BO_AddAssign:
14040 case BO_SubAssign:
14041 case BO_ShlAssign:
14042 case BO_ShrAssign:
14043 case BO_AndAssign:
14044 case BO_XorAssign:
14045 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000014046 // C99 6.6/3 allows assignments within unevaluated subexpressions of
14047 // constant expressions, but they can never be ICEs because an ICE cannot
14048 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014049 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000014050
John McCalle3027922010-08-25 11:45:40 +000014051 case BO_Mul:
14052 case BO_Div:
14053 case BO_Rem:
14054 case BO_Add:
14055 case BO_Sub:
14056 case BO_Shl:
14057 case BO_Shr:
14058 case BO_LT:
14059 case BO_GT:
14060 case BO_LE:
14061 case BO_GE:
14062 case BO_EQ:
14063 case BO_NE:
14064 case BO_And:
14065 case BO_Xor:
14066 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000014067 case BO_Comma:
14068 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000014069 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14070 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000014071 if (Exp->getOpcode() == BO_Div ||
14072 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000014073 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000014074 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000014075 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000014076 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000014077 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014078 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000014079 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000014080 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000014081 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014082 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000014083 }
14084 }
14085 }
John McCalle3027922010-08-25 11:45:40 +000014086 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000014087 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000014088 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
14089 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000014090 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014091 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000014092 } else {
14093 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014094 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000014095 }
14096 }
Richard Smith9e575da2012-12-28 13:25:52 +000014097 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000014098 }
John McCalle3027922010-08-25 11:45:40 +000014099 case BO_LAnd:
14100 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000014101 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14102 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000014103 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000014104 // Rare case where the RHS has a comma "side-effect"; we need
14105 // to actually check the condition to see whether the side
14106 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000014107 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000014108 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000014109 return RHSResult;
14110 return NoDiag();
14111 }
14112
Richard Smith9e575da2012-12-28 13:25:52 +000014113 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000014114 }
14115 }
Reid Klecknere540d972018-11-01 17:51:48 +000014116 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000014117 }
14118 case Expr::ImplicitCastExprClass:
14119 case Expr::CStyleCastExprClass:
14120 case Expr::CXXFunctionalCastExprClass:
14121 case Expr::CXXStaticCastExprClass:
14122 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000014123 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000014124 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000014125 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000014126 if (isa<ExplicitCastExpr>(E)) {
14127 if (const FloatingLiteral *FL
14128 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
14129 unsigned DestWidth = Ctx.getIntWidth(E->getType());
14130 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
14131 APSInt IgnoredVal(DestWidth, !DestSigned);
14132 bool Ignored;
14133 // If the value does not fit in the destination type, the behavior is
14134 // undefined, so we are not required to treat it as a constant
14135 // expression.
14136 if (FL->getValue().convertToInteger(IgnoredVal,
14137 llvm::APFloat::rmTowardZero,
14138 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014139 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000014140 return NoDiag();
14141 }
14142 }
Eli Friedman76d4e432011-09-29 21:49:34 +000014143 switch (cast<CastExpr>(E)->getCastKind()) {
14144 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000014145 case CK_AtomicToNonAtomic:
14146 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000014147 case CK_NoOp:
14148 case CK_IntegralToBoolean:
14149 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000014150 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000014151 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014152 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000014153 }
John McCall864e3962010-05-07 05:32:02 +000014154 }
John McCallc07a0c72011-02-17 10:25:35 +000014155 case Expr::BinaryConditionalOperatorClass: {
14156 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
14157 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000014158 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000014159 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000014160 if (FalseResult.Kind == IK_NotICE) return FalseResult;
14161 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
14162 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000014163 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000014164 return FalseResult;
14165 }
John McCall864e3962010-05-07 05:32:02 +000014166 case Expr::ConditionalOperatorClass: {
14167 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
14168 // If the condition (ignoring parens) is a __builtin_constant_p call,
14169 // then only the true side is actually considered in an integer constant
14170 // expression, and it is fully evaluated. This is an important GNU
14171 // extension. See GCC PR38377 for discussion.
14172 if (const CallExpr *CallCE
14173 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000014174 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000014175 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000014176 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000014177 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000014178 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000014179
Richard Smithf57d8cb2011-12-09 22:58:01 +000014180 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
14181 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000014182
Richard Smith9e575da2012-12-28 13:25:52 +000014183 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000014184 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000014185 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000014186 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000014187 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000014188 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000014189 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000014190 return NoDiag();
14191 // Rare case where the diagnostics depend on which side is evaluated
14192 // Note that if we get here, CondResult is 0, and at least one of
14193 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000014194 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000014195 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000014196 return TrueResult;
14197 }
14198 case Expr::CXXDefaultArgExprClass:
14199 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000014200 case Expr::CXXDefaultInitExprClass:
14201 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000014202 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000014203 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000014204 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000014205 case Expr::BuiltinBitCastExprClass: {
14206 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
14207 return ICEDiag(IK_NotICE, E->getBeginLoc());
14208 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
14209 }
John McCall864e3962010-05-07 05:32:02 +000014210 }
14211
David Blaikiee4d798f2012-01-20 21:50:17 +000014212 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000014213}
14214
Richard Smithf57d8cb2011-12-09 22:58:01 +000014215/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000014216static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000014217 const Expr *E,
14218 llvm::APSInt *Value,
14219 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000014220 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000014221 if (Loc) *Loc = E->getExprLoc();
14222 return false;
14223 }
14224
Richard Smith66e05fe2012-01-18 05:21:49 +000014225 APValue Result;
14226 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000014227 return false;
14228
Richard Smith98710fc2014-11-13 23:03:19 +000014229 if (!Result.isInt()) {
14230 if (Loc) *Loc = E->getExprLoc();
14231 return false;
14232 }
14233
Richard Smith66e05fe2012-01-18 05:21:49 +000014234 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000014235 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000014236}
14237
Craig Toppera31a8822013-08-22 07:09:37 +000014238bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
14239 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014240 assert(!isValueDependent() &&
14241 "Expression evaluator can't be called on a dependent expression.");
14242
Richard Smith2bf7fdb2013-01-02 11:42:31 +000014243 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000014244 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000014245
Richard Smith9e575da2012-12-28 13:25:52 +000014246 ICEDiag D = CheckICE(this, Ctx);
14247 if (D.Kind != IK_ICE) {
14248 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000014249 return false;
14250 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000014251 return true;
14252}
14253
Craig Toppera31a8822013-08-22 07:09:37 +000014254bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000014255 SourceLocation *Loc, bool isEvaluated) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014256 assert(!isValueDependent() &&
14257 "Expression evaluator can't be called on a dependent expression.");
14258
Richard Smith2bf7fdb2013-01-02 11:42:31 +000014259 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000014260 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
14261
14262 if (!isIntegerConstantExpr(Ctx, Loc))
14263 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000014264
Richard Smith5c40f092015-12-04 03:00:44 +000014265 // The only possible side-effects here are due to UB discovered in the
14266 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
14267 // required to treat the expression as an ICE, so we produce the folded
14268 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000014269 EvalResult ExprResult;
14270 Expr::EvalStatus Status;
14271 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
14272 Info.InConstantContext = true;
14273
14274 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000014275 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000014276
14277 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000014278 return true;
14279}
Richard Smith66e05fe2012-01-18 05:21:49 +000014280
Craig Toppera31a8822013-08-22 07:09:37 +000014281bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014282 assert(!isValueDependent() &&
14283 "Expression evaluator can't be called on a dependent expression.");
14284
Richard Smith9e575da2012-12-28 13:25:52 +000014285 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000014286}
14287
Craig Toppera31a8822013-08-22 07:09:37 +000014288bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000014289 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014290 assert(!isValueDependent() &&
14291 "Expression evaluator can't be called on a dependent expression.");
14292
Richard Smith66e05fe2012-01-18 05:21:49 +000014293 // We support this checking in C++98 mode in order to diagnose compatibility
14294 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000014295 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000014296
Richard Smith98a0a492012-02-14 21:38:30 +000014297 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000014298 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000014299 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000014300 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000014301 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000014302
14303 APValue Scratch;
Richard Smith457226e2019-09-23 03:48:44 +000014304 bool IsConstExpr =
14305 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
14306 // FIXME: We don't produce a diagnostic for this, but the callers that
14307 // call us on arbitrary full-expressions should generally not care.
Richard Smithda1b4342019-09-27 01:26:47 +000014308 Info.discardCleanups() && !Status.HasSideEffects;
Richard Smith66e05fe2012-01-18 05:21:49 +000014309
14310 if (!Diags.empty()) {
14311 IsConstExpr = false;
14312 if (Loc) *Loc = Diags[0].first;
14313 } else if (!IsConstExpr) {
14314 // FIXME: This shouldn't happen.
14315 if (Loc) *Loc = getExprLoc();
14316 }
14317
14318 return IsConstExpr;
14319}
Richard Smith253c2a32012-01-27 01:14:48 +000014320
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014321bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
14322 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000014323 ArrayRef<const Expr*> Args,
14324 const Expr *This) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014325 assert(!isValueDependent() &&
14326 "Expression evaluator can't be called on a dependent expression.");
14327
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014328 Expr::EvalStatus Status;
14329 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000014330 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014331
George Burgess IV177399e2017-01-09 04:12:14 +000014332 LValue ThisVal;
14333 const LValue *ThisPtr = nullptr;
14334 if (This) {
14335#ifndef NDEBUG
14336 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
14337 assert(MD && "Don't provide `this` for non-methods.");
14338 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
14339#endif
Richard Smithbb061492019-10-30 13:32:52 -070014340 if (!This->isValueDependent() &&
14341 EvaluateObjectArgument(Info, This, ThisVal) &&
14342 !Info.EvalStatus.HasSideEffects)
George Burgess IV177399e2017-01-09 04:12:14 +000014343 ThisPtr = &ThisVal;
Richard Smithbb061492019-10-30 13:32:52 -070014344
14345 // Ignore any side-effects from a failed evaluation. This is safe because
14346 // they can't interfere with any other argument evaluation.
14347 Info.EvalStatus.HasSideEffects = false;
George Burgess IV177399e2017-01-09 04:12:14 +000014348 }
14349
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014350 ArgVector ArgValues(Args.size());
14351 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
14352 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000014353 if ((*I)->isValueDependent() ||
Richard Smithbb061492019-10-30 13:32:52 -070014354 !Evaluate(ArgValues[I - Args.begin()], Info, *I) ||
14355 Info.EvalStatus.HasSideEffects)
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014356 // If evaluation fails, throw away the argument entirely.
14357 ArgValues[I - Args.begin()] = APValue();
Richard Smithbb061492019-10-30 13:32:52 -070014358
14359 // Ignore any side-effects from a failed evaluation. This is safe because
14360 // they can't interfere with any other argument evaluation.
14361 Info.EvalStatus.HasSideEffects = false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014362 }
14363
Richard Smithbb061492019-10-30 13:32:52 -070014364 // Parameter cleanups happen in the caller and are not part of this
14365 // evaluation.
14366 Info.discardCleanups();
14367 Info.EvalStatus.HasSideEffects = false;
14368
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014369 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000014370 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014371 ArgValues.data());
Richard Smithbb061492019-10-30 13:32:52 -070014372 // FIXME: Missing ExprWithCleanups in enable_if conditions?
14373 FullExpressionRAII Scope(Info);
14374 return Evaluate(Value, Info, this) && Scope.destroy() &&
Richard Smith457226e2019-09-23 03:48:44 +000014375 !Info.EvalStatus.HasSideEffects;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014376}
14377
Richard Smith253c2a32012-01-27 01:14:48 +000014378bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000014379 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000014380 PartialDiagnosticAt> &Diags) {
14381 // FIXME: It would be useful to check constexpr function templates, but at the
14382 // moment the constant expression evaluator cannot cope with the non-rigorous
14383 // ASTs which we build for dependent expressions.
14384 if (FD->isDependentContext())
14385 return true;
14386
14387 Expr::EvalStatus Status;
14388 Status.Diag = &Diags;
14389
Richard Smith045b2272019-09-10 21:24:09 +000014390 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000014391 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000014392 Info.CheckingPotentialConstantExpression = true;
Richard Smith253c2a32012-01-27 01:14:48 +000014393
Nandor Licker950b70d2019-09-13 09:46:16 +000014394 // The constexpr VM attempts to compile all methods to bytecode here.
14395 if (Info.EnableNewConstInterp) {
Nandor Lickerf584f042019-11-11 11:13:34 +000014396 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
14397 return Diags.empty();
Nandor Licker950b70d2019-09-13 09:46:16 +000014398 }
14399
Richard Smith253c2a32012-01-27 01:14:48 +000014400 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000014401 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000014402
Richard Smith7525ff62013-05-09 07:14:00 +000014403 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000014404 // is a temporary being used as the 'this' pointer.
14405 LValue This;
14406 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000014407 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000014408
Richard Smith253c2a32012-01-27 01:14:48 +000014409 ArrayRef<const Expr*> Args;
14410
Richard Smith2e312c82012-03-03 22:46:17 +000014411 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000014412 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
14413 // Evaluate the call as a constant initializer, to allow the construction
14414 // of objects of non-literal types.
14415 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000014416 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
14417 } else {
14418 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000014419 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000014420 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000014421 }
Richard Smith253c2a32012-01-27 01:14:48 +000014422
14423 return Diags.empty();
14424}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014425
14426bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
14427 const FunctionDecl *FD,
14428 SmallVectorImpl<
14429 PartialDiagnosticAt> &Diags) {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000014430 assert(!E->isValueDependent() &&
14431 "Expression evaluator can't be called on a dependent expression.");
14432
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014433 Expr::EvalStatus Status;
14434 Status.Diag = &Diags;
14435
14436 EvalInfo Info(FD->getASTContext(), Status,
Richard Smith045b2272019-09-10 21:24:09 +000014437 EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000014438 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000014439 Info.CheckingPotentialConstantExpression = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014440
14441 // Fabricate a call stack frame to give the arguments a plausible cover story.
14442 ArrayRef<const Expr*> Args;
14443 ArgVector ArgValues(0);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000014444 bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014445 (void)Success;
14446 assert(Success &&
14447 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000014448 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000014449
14450 APValue ResultScratch;
14451 Evaluate(ResultScratch, Info, E);
14452 return Diags.empty();
14453}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000014454
14455bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
14456 unsigned Type) const {
14457 if (!getType()->isPointerType())
14458 return false;
14459
14460 Expr::EvalStatus Status;
14461 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000014462 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000014463}