blob: 3282bc0a0afd0bba39858b59a1375288b90e9c78 [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
35#include "clang/AST/APValue.h"
36#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000037#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000038#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Eric Fiselier708afb52019-05-16 21:04:15 +000040#include "clang/AST/CurrentSourceLocExprScope.h"
Richard Smith921f1322019-05-13 23:35:21 +000041#include "clang/AST/CXXInheritance.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000042#include "clang/AST/Expr.h"
Tim Northover314fbfa2018-11-02 13:14:11 +000043#include "clang/AST/OSLog.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000044#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000045#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000046#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000047#include "clang/Basic/Builtins.h"
Leonard Chand3f3e162019-01-18 21:04:25 +000048#include "clang/Basic/FixedPoint.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000049#include "clang/Basic/TargetInfo.h"
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000050#include "llvm/ADT/SmallBitVector.h"
Fangrui Song407659a2018-11-30 23:41:18 +000051#include "llvm/Support/SaveAndRestore.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000052#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000053#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000054#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000055
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000056#define DEBUG_TYPE "exprconstant"
57
Anders Carlsson7a241ba2008-07-03 04:20:39 +000058using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000059using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000060using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062static bool IsGlobalLValue(APValue::LValueBase B);
63
John McCall93d91dc2010-05-07 17:22:02 +000064namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000065 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000066 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000067 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000068
Eric Fiselier708afb52019-05-16 21:04:15 +000069 using SourceLocExprScopeGuard =
70 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
71
Richard Smithb228a862012-02-15 02:18:13 +000072 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000073 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000074 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000075 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000076 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000077 //
78 // extern int arr[]; void f() { extern int arr[3]; };
79 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000080 //
81 // For now, we take the array bound from the most recent declaration.
82 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
83 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
84 QualType T = Redecl->getType();
85 if (!T->isIncompleteArrayType())
86 return T;
87 }
88 return D->getType();
89 }
Richard Smith84401042013-06-03 05:03:02 +000090
Mikael Holmen3b6b2e32019-05-20 11:38:33 +000091 if (B.is<TypeInfoLValue>())
Richard Smithee0ce3022019-05-17 07:06:46 +000092 return B.getTypeInfoType();
93
Richard Smith84401042013-06-03 05:03:02 +000094 const Expr *Base = B.get<const Expr*>();
95
96 // For a materialized temporary, the type of the temporary we materialized
97 // may not be the type of the expression.
98 if (const MaterializeTemporaryExpr *MTE =
99 dyn_cast<MaterializeTemporaryExpr>(Base)) {
100 SmallVector<const Expr *, 2> CommaLHSs;
101 SmallVector<SubobjectAdjustment, 2> Adjustments;
102 const Expr *Temp = MTE->GetTemporaryExpr();
103 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
104 Adjustments);
105 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +0000106 // for it directly. Otherwise use the type after adjustment.
107 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +0000108 return Inner->getType();
109 }
110
111 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000112 }
113
Richard Smithd62306a2011-11-10 06:34:14 +0000114 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000115 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000116 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000117 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000118 }
119 /// Get an LValue path entry, which is known to not be an array index, as a
120 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000121 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000122 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000123 }
124 /// Determine whether this LValue path entry for a base class names a virtual
125 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000126 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000127 return E.getAsBaseOrMember().getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000128 }
129
George Burgess IVe3763372016-12-22 02:50:20 +0000130 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
131 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
132 const FunctionDecl *Callee = CE->getDirectCallee();
133 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
134 }
135
136 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
137 /// This will look through a single cast.
138 ///
139 /// Returns null if we couldn't unwrap a function with alloc_size.
140 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
141 if (!E->getType()->isPointerType())
142 return nullptr;
143
144 E = E->IgnoreParens();
145 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000146 // probably be a cast of some kind. In exotic cases, we might also see a
147 // top-level ExprWithCleanups. Ignore them either way.
Bill Wendling7c44da22018-10-31 03:48:47 +0000148 if (const auto *FE = dyn_cast<FullExpr>(E))
149 E = FE->getSubExpr()->IgnoreParens();
George Burgess IV47638762018-03-07 04:52:34 +0000150
George Burgess IVe3763372016-12-22 02:50:20 +0000151 if (const auto *Cast = dyn_cast<CastExpr>(E))
152 E = Cast->getSubExpr()->IgnoreParens();
153
154 if (const auto *CE = dyn_cast<CallExpr>(E))
155 return getAllocSizeAttr(CE) ? CE : nullptr;
156 return nullptr;
157 }
158
159 /// Determines whether or not the given Base contains a call to a function
160 /// with the alloc_size attribute.
161 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
162 const auto *E = Base.dyn_cast<const Expr *>();
163 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
164 }
165
Richard Smith6f4f0f12017-10-20 22:56:25 +0000166 /// The bound to claim that an array of unknown bound has.
167 /// The value in MostDerivedArraySize is undefined in this case. So, set it
168 /// to an arbitrary value that's likely to loudly break things if it's used.
169 static const uint64_t AssumedSizeForUnsizedArray =
170 std::numeric_limits<uint64_t>::max() / 2;
171
George Burgess IVe3763372016-12-22 02:50:20 +0000172 /// Determines if an LValue with the given LValueBase will have an unsized
173 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000174 /// Find the path length and type of the most-derived subobject in the given
175 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000176 static unsigned
177 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
178 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000179 uint64_t &ArraySize, QualType &Type, bool &IsArray,
180 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000181 // This only accepts LValueBases from APValues, and APValues don't support
182 // arrays that lack size info.
183 assert(!isBaseAnAllocSizeCall(Base) &&
184 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000185 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000186 Type = getType(Base);
187
Richard Smith80815602011-11-07 05:07:52 +0000188 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000189 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000190 const ArrayType *AT = Ctx.getAsArrayType(Type);
191 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000192 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000193 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000194
195 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
196 ArraySize = CAT->getSize().getZExtValue();
197 } else {
198 assert(I == 0 && "unexpected unsized array designator");
199 FirstEntryIsUnsizedArray = true;
200 ArraySize = AssumedSizeForUnsizedArray;
201 }
Richard Smith66c96992012-02-18 22:04:06 +0000202 } else if (Type->isAnyComplexType()) {
203 const ComplexType *CT = Type->castAs<ComplexType>();
204 Type = CT->getElementType();
205 ArraySize = 2;
206 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000207 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000208 } else if (const FieldDecl *FD = getAsField(Path[I])) {
209 Type = FD->getType();
210 ArraySize = 0;
211 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000212 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000213 } else {
Richard Smith80815602011-11-07 05:07:52 +0000214 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000215 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000216 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 }
Richard Smith80815602011-11-07 05:07:52 +0000218 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000219 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000220 }
221
Richard Smitha8105bc2012-01-06 16:39:00 +0000222 // The order of this enum is important for diagnostics.
223 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000224 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smithdebad642019-05-12 09:39:08 +0000225 CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000226 };
227
Richard Smith96e0c102011-11-04 02:25:55 +0000228 /// A path from a glvalue to a subobject of that glvalue.
229 struct SubobjectDesignator {
230 /// True if the subobject was named in a manner not supported by C++11. Such
231 /// lvalues can still be folded, but they are not core constant expressions
232 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000233 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000234
Richard Smitha8105bc2012-01-06 16:39:00 +0000235 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000236 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000237
Daniel Jasperffdee092017-05-02 19:21:42 +0000238 /// Indicator of whether the first entry is an unsized array.
239 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000240
George Burgess IVa51c4072015-10-16 01:49:01 +0000241 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000242 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000243
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 /// The length of the path to the most-derived object of which this is a
245 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000246 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000247
George Burgess IVa51c4072015-10-16 01:49:01 +0000248 /// The size of the array of which the most-derived object is an element.
249 /// This will always be 0 if the most-derived object is not an array
250 /// element. 0 is not an indicator of whether or not the most-derived object
251 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000252 ///
253 /// If the current array is an unsized array, the value of this is
254 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000255 uint64_t MostDerivedArraySize;
256
257 /// The type of the most derived object referred to by this address.
258 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000259
Richard Smith80815602011-11-07 05:07:52 +0000260 typedef APValue::LValuePathEntry PathEntry;
261
Richard Smith96e0c102011-11-04 02:25:55 +0000262 /// The entries on the path from the glvalue to the designated subobject.
263 SmallVector<PathEntry, 8> Entries;
264
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000266
Richard Smitha8105bc2012-01-06 16:39:00 +0000267 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000268 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000269 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000270 MostDerivedPathLength(0), MostDerivedArraySize(0),
271 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000272
273 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000274 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000275 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000276 MostDerivedPathLength(0), MostDerivedArraySize(0) {
277 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000278 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000279 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000280 ArrayRef<PathEntry> VEntries = V.getLValuePath();
281 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000282 if (V.getLValueBase()) {
283 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000284 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000285 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000286 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000287 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000288 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000289 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000290 }
Richard Smith80815602011-11-07 05:07:52 +0000291 }
292 }
293
Richard Smith31c69a32019-05-21 23:15:20 +0000294 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
295 unsigned NewLength) {
296 if (Invalid)
297 return;
298
299 assert(Base && "cannot truncate path for null pointer");
300 assert(NewLength <= Entries.size() && "not a truncation");
301
302 if (NewLength == Entries.size())
303 return;
304 Entries.resize(NewLength);
305
306 bool IsArray = false;
307 bool FirstIsUnsizedArray = false;
308 MostDerivedPathLength = findMostDerivedSubobject(
309 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
310 FirstIsUnsizedArray);
311 MostDerivedIsArrayElement = IsArray;
312 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
313 }
314
Richard Smith96e0c102011-11-04 02:25:55 +0000315 void setInvalid() {
316 Invalid = true;
317 Entries.clear();
318 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000319
George Burgess IVe3763372016-12-22 02:50:20 +0000320 /// Determine whether the most derived subobject is an array without a
321 /// known bound.
322 bool isMostDerivedAnUnsizedArray() const {
323 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000324 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000325 }
326
327 /// Determine what the most derived array's size is. Results in an assertion
328 /// failure if the most derived array lacks a size.
329 uint64_t getMostDerivedArraySize() const {
330 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
331 return MostDerivedArraySize;
332 }
333
Richard Smitha8105bc2012-01-06 16:39:00 +0000334 /// Determine whether this is a one-past-the-end pointer.
335 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000336 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000337 if (IsOnePastTheEnd)
338 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000339 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smith5b5e27a2019-05-10 20:05:31 +0000340 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
341 MostDerivedArraySize)
Richard Smitha8105bc2012-01-06 16:39:00 +0000342 return true;
343 return false;
344 }
345
Richard Smith06f71b52018-08-04 00:57:17 +0000346 /// Get the range of valid index adjustments in the form
347 /// {maximum value that can be subtracted from this pointer,
348 /// maximum value that can be added to this pointer}
349 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
350 if (Invalid || isMostDerivedAnUnsizedArray())
351 return {0, 0};
352
353 // [expr.add]p4: For the purposes of these operators, a pointer to a
354 // nonarray object behaves the same as a pointer to the first element of
355 // an array of length one with the type of the object as its element type.
356 bool IsArray = MostDerivedPathLength == Entries.size() &&
357 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000358 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
359 : (uint64_t)IsOnePastTheEnd;
Richard Smith06f71b52018-08-04 00:57:17 +0000360 uint64_t ArraySize =
361 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
362 return {ArrayIndex, ArraySize - ArrayIndex};
363 }
364
Richard Smitha8105bc2012-01-06 16:39:00 +0000365 /// Check that this refers to a valid subobject.
366 bool isValidSubobject() const {
367 if (Invalid)
368 return false;
369 return !isOnePastTheEnd();
370 }
371 /// Check that this refers to a valid subobject, and if not, produce a
372 /// relevant diagnostic and set the designator as invalid.
373 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
374
Richard Smith06f71b52018-08-04 00:57:17 +0000375 /// Get the type of the designated object.
376 QualType getType(ASTContext &Ctx) const {
377 assert(!Invalid && "invalid designator has no subobject type");
378 return MostDerivedPathLength == Entries.size()
379 ? MostDerivedType
380 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
381 }
382
Richard Smitha8105bc2012-01-06 16:39:00 +0000383 /// Update this designator to refer to the first element within this array.
384 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000385 Entries.push_back(PathEntry::ArrayIndex(0));
Richard Smitha8105bc2012-01-06 16:39:00 +0000386
387 // This is a most-derived object.
388 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000389 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000390 MostDerivedArraySize = CAT->getSize().getZExtValue();
391 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000392 }
George Burgess IVe3763372016-12-22 02:50:20 +0000393 /// Update this designator to refer to the first element within the array of
394 /// elements of type T. This is an array of unknown size.
395 void addUnsizedArrayUnchecked(QualType ElemTy) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000396 Entries.push_back(PathEntry::ArrayIndex(0));
George Burgess IVe3763372016-12-22 02:50:20 +0000397
398 MostDerivedType = ElemTy;
399 MostDerivedIsArrayElement = true;
400 // The value in MostDerivedArraySize is undefined in this case. So, set it
401 // to an arbitrary value that's likely to loudly break things if it's
402 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000403 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000404 MostDerivedPathLength = Entries.size();
405 }
Richard Smith96e0c102011-11-04 02:25:55 +0000406 /// Update this designator to refer to the given base or member of this
407 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000408 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000409 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
Richard Smitha8105bc2012-01-06 16:39:00 +0000410
411 // If this isn't a base class, it's a new most-derived object.
412 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
413 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000414 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000415 MostDerivedArraySize = 0;
416 MostDerivedPathLength = Entries.size();
417 }
Richard Smith96e0c102011-11-04 02:25:55 +0000418 }
Richard Smith66c96992012-02-18 22:04:06 +0000419 /// Update this designator to refer to the given complex component.
420 void addComplexUnchecked(QualType EltTy, bool Imag) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000421 Entries.push_back(PathEntry::ArrayIndex(Imag));
Richard Smith66c96992012-02-18 22:04:06 +0000422
423 // This is technically a most-derived object, though in practice this
424 // is unlikely to matter.
425 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000426 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000427 MostDerivedArraySize = 2;
428 MostDerivedPathLength = Entries.size();
429 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000430 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000431 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
432 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000433 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000434 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
435 if (Invalid || !N) return;
436 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
437 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000438 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000439 // Can't verify -- trust that the user is doing the right thing (or if
440 // not, trust that the caller will catch the bad behavior).
441 // FIXME: Should we reject if this overflows, at least?
Richard Smith5b5e27a2019-05-10 20:05:31 +0000442 Entries.back() = PathEntry::ArrayIndex(
443 Entries.back().getAsArrayIndex() + TruncatedN);
Daniel Jasperffdee092017-05-02 19:21:42 +0000444 return;
445 }
446
447 // [expr.add]p4: For the purposes of these operators, a pointer to a
448 // nonarray object behaves the same as a pointer to the first element of
449 // an array of length one with the type of the object as its element type.
450 bool IsArray = MostDerivedPathLength == Entries.size() &&
451 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000452 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
453 : (uint64_t)IsOnePastTheEnd;
Daniel Jasperffdee092017-05-02 19:21:42 +0000454 uint64_t ArraySize =
455 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
456
457 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
458 // Calculate the actual index in a wide enough type, so we can include
459 // it in the note.
460 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
461 (llvm::APInt&)N += ArrayIndex;
462 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
463 diagnosePointerArithmetic(Info, E, N);
464 setInvalid();
465 return;
466 }
467
468 ArrayIndex += TruncatedN;
469 assert(ArrayIndex <= ArraySize &&
470 "bounds check succeeded for out-of-bounds index");
471
472 if (IsArray)
Richard Smith5b5e27a2019-05-10 20:05:31 +0000473 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
Daniel Jasperffdee092017-05-02 19:21:42 +0000474 else
475 IsOnePastTheEnd = (ArrayIndex != 0);
476 }
Richard Smith96e0c102011-11-04 02:25:55 +0000477 };
478
Richard Smith254a73d2011-10-28 22:34:42 +0000479 /// A stack frame in the constexpr call stack.
480 struct CallStackFrame {
481 EvalInfo &Info;
482
483 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000484 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000485
Richard Smithf6f003a2011-12-16 19:06:07 +0000486 /// Callee - The function which was called.
487 const FunctionDecl *Callee;
488
Richard Smithd62306a2011-11-10 06:34:14 +0000489 /// This - The binding for the this pointer in this call, if any.
490 const LValue *This;
491
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000492 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000493 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000494 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000495
Eric Fiselier708afb52019-05-16 21:04:15 +0000496 /// Source location information about the default argument or default
497 /// initializer expression we're evaluating, if any.
498 CurrentSourceLocExprScope CurSourceLocExprScope;
499
Eli Friedman4830ec82012-06-25 21:21:08 +0000500 // Note that we intentionally use std::map here so that references to
501 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000502 typedef std::pair<const void *, unsigned> MapKeyTy;
503 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000504 /// Temporaries - Temporary lvalues materialized within this stack frame.
505 MapTy Temporaries;
506
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000507 /// CallLoc - The location of the call expression for this call.
508 SourceLocation CallLoc;
509
510 /// Index - The call index of this call.
511 unsigned Index;
512
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000513 /// The stack of integers for tracking version numbers for temporaries.
514 SmallVector<unsigned, 2> TempVersionStack = {1};
515 unsigned CurTempVersion = TempVersionStack.back();
516
517 unsigned getTempVersion() const { return TempVersionStack.back(); }
518
519 void pushTempVersion() {
520 TempVersionStack.push_back(++CurTempVersion);
521 }
522
523 void popTempVersion() {
524 TempVersionStack.pop_back();
525 }
526
Faisal Vali051e3a22017-02-16 04:12:21 +0000527 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000528 // on the overall stack usage of deeply-recursing constexpr evaluations.
Faisal Vali051e3a22017-02-16 04:12:21 +0000529 // (We should cache this map rather than recomputing it repeatedly.)
530 // But let's try this and see how it goes; we can look into caching the map
531 // as a later change.
532
533 /// LambdaCaptureFields - Mapping from captured variables/this to
534 /// corresponding data members in the closure class.
535 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
536 FieldDecl *LambdaThisCaptureField;
537
Richard Smithf6f003a2011-12-16 19:06:07 +0000538 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
539 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000540 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000541 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000542
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000543 // Return the temporary for Key whose version number is Version.
544 APValue *getTemporary(const void *Key, unsigned Version) {
545 MapKeyTy KV(Key, Version);
546 auto LB = Temporaries.lower_bound(KV);
547 if (LB != Temporaries.end() && LB->first == KV)
548 return &LB->second;
549 // Pair (Key,Version) wasn't found in the map. Check that no elements
550 // in the map have 'Key' as their key.
551 assert((LB == Temporaries.end() || LB->first.first != Key) &&
552 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
553 "Element with key 'Key' found in map");
554 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000555 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000556
557 // Return the current temporary for Key in the map.
558 APValue *getCurrentTemporary(const void *Key) {
559 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
560 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
561 return &std::prev(UB)->second;
562 return nullptr;
563 }
564
565 // Return the version number of the current temporary for Key.
566 unsigned getCurrentTemporaryVersion(const void *Key) const {
567 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
568 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
569 return std::prev(UB)->first.second;
570 return 0;
571 }
572
Richard Smith08d6a2c2013-07-24 07:11:57 +0000573 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000574 };
575
Richard Smith852c9db2013-04-20 22:23:05 +0000576 /// Temporarily override 'this'.
577 class ThisOverrideRAII {
578 public:
579 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
580 : Frame(Frame), OldThis(Frame.This) {
581 if (Enable)
582 Frame.This = NewThis;
583 }
584 ~ThisOverrideRAII() {
585 Frame.This = OldThis;
586 }
587 private:
588 CallStackFrame &Frame;
589 const LValue *OldThis;
590 };
591
Richard Smith92b1ce02011-12-12 09:28:41 +0000592 /// A partial diagnostic which we might know in advance that we are not going
593 /// to emit.
594 class OptionalDiagnostic {
595 PartialDiagnostic *Diag;
596
597 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000598 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
599 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000600
601 template<typename T>
602 OptionalDiagnostic &operator<<(const T &v) {
603 if (Diag)
604 *Diag << v;
605 return *this;
606 }
Richard Smithfe800032012-01-31 04:08:20 +0000607
608 OptionalDiagnostic &operator<<(const APSInt &I) {
609 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000610 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000611 I.toString(Buffer);
612 *Diag << StringRef(Buffer.data(), Buffer.size());
613 }
614 return *this;
615 }
616
617 OptionalDiagnostic &operator<<(const APFloat &F) {
618 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000619 // FIXME: Force the precision of the source value down so we don't
620 // print digits which are usually useless (we don't really care here if
621 // we truncate a digit by accident in edge cases). Ideally,
Fangrui Song6907ce22018-07-30 19:24:48 +0000622 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000623 // representation which rounds to the correct value, but it's a bit
624 // tricky to implement.
625 unsigned precision =
626 llvm::APFloat::semanticsPrecision(F.getSemantics());
627 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000628 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000629 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000630 *Diag << StringRef(Buffer.data(), Buffer.size());
631 }
632 return *this;
633 }
Leonard Chand3f3e162019-01-18 21:04:25 +0000634
635 OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
636 if (Diag) {
637 SmallVector<char, 32> Buffer;
638 FX.toString(Buffer);
639 *Diag << StringRef(Buffer.data(), Buffer.size());
640 }
641 return *this;
642 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000643 };
644
Richard Smith08d6a2c2013-07-24 07:11:57 +0000645 /// A cleanup, and a flag indicating whether it is lifetime-extended.
646 class Cleanup {
647 llvm::PointerIntPair<APValue*, 1, bool> Value;
648
649 public:
650 Cleanup(APValue *Val, bool IsLifetimeExtended)
651 : Value(Val, IsLifetimeExtended) {}
652
653 bool isLifetimeExtended() const { return Value.getInt(); }
654 void endLifetime() {
655 *Value.getPointer() = APValue();
656 }
657 };
658
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000659 /// A reference to an object whose construction we are currently evaluating.
660 struct ObjectUnderConstruction {
661 APValue::LValueBase Base;
662 ArrayRef<APValue::LValuePathEntry> Path;
663 friend bool operator==(const ObjectUnderConstruction &LHS,
664 const ObjectUnderConstruction &RHS) {
665 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
666 }
667 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
668 return llvm::hash_combine(Obj.Base, Obj.Path);
669 }
670 };
671 enum class ConstructionPhase { None, Bases, AfterBases };
672}
673
674namespace llvm {
675template<> struct DenseMapInfo<ObjectUnderConstruction> {
676 using Base = DenseMapInfo<APValue::LValueBase>;
677 static ObjectUnderConstruction getEmptyKey() {
678 return {Base::getEmptyKey(), {}}; }
679 static ObjectUnderConstruction getTombstoneKey() {
680 return {Base::getTombstoneKey(), {}};
681 }
682 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
683 return hash_value(Object);
684 }
685 static bool isEqual(const ObjectUnderConstruction &LHS,
686 const ObjectUnderConstruction &RHS) {
687 return LHS == RHS;
688 }
689};
690}
691
692namespace {
Richard Smithb228a862012-02-15 02:18:13 +0000693 /// EvalInfo - This is a private struct used by the evaluator to capture
694 /// information about a subexpression as it is folded. It retains information
695 /// about the AST context, but also maintains information about the folded
696 /// expression.
697 ///
698 /// If an expression could be evaluated, it is still possible it is not a C
699 /// "integer constant expression" or constant expression. If not, this struct
700 /// captures information about how and why not.
701 ///
702 /// One bit of information passed *into* the request for constant folding
703 /// indicates whether the subexpression is "evaluated" or not according to C
704 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
705 /// evaluate the expression regardless of what the RHS is, but C only allows
706 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000707 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000708 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000709
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000710 /// EvalStatus - Contains information about the evaluation.
711 Expr::EvalStatus &EvalStatus;
712
713 /// CurrentCall - The top of the constexpr call stack.
714 CallStackFrame *CurrentCall;
715
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000716 /// CallStackDepth - The number of calls in the call stack right now.
717 unsigned CallStackDepth;
718
Richard Smithb228a862012-02-15 02:18:13 +0000719 /// NextCallIndex - The next call index to assign.
720 unsigned NextCallIndex;
721
Richard Smitha3d3bd22013-05-08 02:12:03 +0000722 /// StepsLeft - The remaining number of evaluation steps we're permitted
723 /// to perform. This is essentially a limit for the number of statements
724 /// we will evaluate.
725 unsigned StepsLeft;
726
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000727 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000728 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000729 CallStackFrame BottomFrame;
730
Richard Smith08d6a2c2013-07-24 07:11:57 +0000731 /// A stack of values whose lifetimes end at the end of some surrounding
732 /// evaluation frame.
733 llvm::SmallVector<Cleanup, 16> CleanupStack;
734
Richard Smithd62306a2011-11-10 06:34:14 +0000735 /// EvaluatingDecl - This is the declaration whose initializer is being
736 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000737 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000738
739 /// EvaluatingDeclValue - This is the value being constructed for the
740 /// declaration whose initializer is being evaluated, if any.
741 APValue *EvaluatingDeclValue;
742
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000743 /// Set of objects that are currently being constructed.
744 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
745 ObjectsUnderConstruction;
Erik Pilkington42925492017-10-04 00:18:55 +0000746
747 struct EvaluatingConstructorRAII {
748 EvalInfo &EI;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000749 ObjectUnderConstruction Object;
Erik Pilkington42925492017-10-04 00:18:55 +0000750 bool DidInsert;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000751 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
752 bool HasBases)
Erik Pilkington42925492017-10-04 00:18:55 +0000753 : EI(EI), Object(Object) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000754 DidInsert =
755 EI.ObjectsUnderConstruction
756 .insert({Object, HasBases ? ConstructionPhase::Bases
757 : ConstructionPhase::AfterBases})
758 .second;
759 }
760 void finishedConstructingBases() {
761 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
Erik Pilkington42925492017-10-04 00:18:55 +0000762 }
763 ~EvaluatingConstructorRAII() {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000764 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
Erik Pilkington42925492017-10-04 00:18:55 +0000765 }
766 };
767
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000768 ConstructionPhase
769 isEvaluatingConstructor(APValue::LValueBase Base,
770 ArrayRef<APValue::LValuePathEntry> Path) {
771 return ObjectsUnderConstruction.lookup({Base, Path});
Erik Pilkington42925492017-10-04 00:18:55 +0000772 }
773
Richard Smith37be3362019-05-04 04:00:45 +0000774 /// If we're currently speculatively evaluating, the outermost call stack
775 /// depth at which we can mutate state, otherwise 0.
776 unsigned SpeculativeEvaluationDepth = 0;
777
Richard Smith410306b2016-12-12 02:53:20 +0000778 /// The current array initialization index, if we're performing array
779 /// initialization.
780 uint64_t ArrayInitIndex = -1;
781
Richard Smith357362d2011-12-13 06:39:58 +0000782 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
783 /// notes attached to it will also be stored, otherwise they will not be.
784 bool HasActiveDiagnostic;
785
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000786 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000787 /// fold (not just why it's not strictly a constant expression)?
788 bool HasFoldFailureDiagnostic;
789
Fangrui Song407659a2018-11-30 23:41:18 +0000790 /// Whether or not we're in a context where the front end requires a
791 /// constant value.
792 bool InConstantContext;
793
Richard Smith6d4c6582013-11-05 22:18:15 +0000794 enum EvaluationMode {
795 /// Evaluate as a constant expression. Stop if we find that the expression
796 /// is not a constant expression.
797 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000798
Richard Smith6d4c6582013-11-05 22:18:15 +0000799 /// Evaluate as a potential constant expression. Keep going if we hit a
800 /// construct that we can't evaluate yet (because we don't yet know the
801 /// value of something) but stop if we hit something that could never be
802 /// a constant expression.
803 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000804
Richard Smith6d4c6582013-11-05 22:18:15 +0000805 /// Fold the expression to a constant. Stop if we hit a side-effect that
806 /// we can't model.
807 EM_ConstantFold,
808
809 /// Evaluate the expression looking for integer overflow and similar
810 /// issues. Don't worry about side-effects, and try to visit all
811 /// subexpressions.
812 EM_EvaluateForOverflow,
813
814 /// Evaluate in any way we know how. Don't worry about side-effects that
815 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000816 EM_IgnoreSideEffects,
817
818 /// Evaluate as a constant expression. Stop if we find that the expression
819 /// is not a constant expression. Some expressions can be retried in the
820 /// optimizer if we don't constant fold them here, but in an unevaluated
821 /// context we try to fold them immediately since the optimizer never
822 /// gets a chance to look at it.
823 EM_ConstantExpressionUnevaluated,
824
825 /// Evaluate as a potential constant expression. Keep going if we hit a
826 /// construct that we can't evaluate yet (because we don't yet know the
827 /// value of something) but stop if we hit something that could never be
828 /// a constant expression. Some expressions can be retried in the
829 /// optimizer if we don't constant fold them here, but in an unevaluated
830 /// context we try to fold them immediately since the optimizer never
831 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000832 EM_PotentialConstantExpressionUnevaluated,
Richard Smith6d4c6582013-11-05 22:18:15 +0000833 } EvalMode;
834
835 /// Are we checking whether the expression is a potential constant
836 /// expression?
837 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000838 return EvalMode == EM_PotentialConstantExpression ||
839 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000840 }
841
842 /// Are we checking an expression for overflow?
843 // FIXME: We should check for any kind of undefined or suspicious behavior
844 // in such constructs, not just overflow.
845 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
846
847 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000848 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000849 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000850 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000851 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
852 EvaluatingDecl((const ValueDecl *)nullptr),
853 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
Richard Smith37be3362019-05-04 04:00:45 +0000854 HasFoldFailureDiagnostic(false),
Fangrui Song407659a2018-11-30 23:41:18 +0000855 InConstantContext(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000856
Richard Smith7525ff62013-05-09 07:14:00 +0000857 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
858 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000859 EvaluatingDeclValue = &Value;
860 }
861
David Blaikiebbafb8a2012-03-11 07:00:24 +0000862 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000863
Richard Smith357362d2011-12-13 06:39:58 +0000864 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000865 // Don't perform any constexpr calls (other than the call we're checking)
866 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000867 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000868 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000869 if (NextCallIndex == 0) {
870 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000871 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000872 return false;
873 }
Richard Smith357362d2011-12-13 06:39:58 +0000874 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
875 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000876 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000877 << getLangOpts().ConstexprCallDepth;
878 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000879 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000880
Richard Smith37be3362019-05-04 04:00:45 +0000881 std::pair<CallStackFrame *, unsigned>
882 getCallFrameAndDepth(unsigned CallIndex) {
883 assert(CallIndex && "no call index in getCallFrameAndDepth");
Richard Smithb228a862012-02-15 02:18:13 +0000884 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
885 // be null in this loop.
Richard Smith37be3362019-05-04 04:00:45 +0000886 unsigned Depth = CallStackDepth;
Richard Smithb228a862012-02-15 02:18:13 +0000887 CallStackFrame *Frame = CurrentCall;
Richard Smith37be3362019-05-04 04:00:45 +0000888 while (Frame->Index > CallIndex) {
Richard Smithb228a862012-02-15 02:18:13 +0000889 Frame = Frame->Caller;
Richard Smith37be3362019-05-04 04:00:45 +0000890 --Depth;
891 }
892 if (Frame->Index == CallIndex)
893 return {Frame, Depth};
894 return {nullptr, 0};
Richard Smithb228a862012-02-15 02:18:13 +0000895 }
896
Richard Smitha3d3bd22013-05-08 02:12:03 +0000897 bool nextStep(const Stmt *S) {
898 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000899 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000900 return false;
901 }
902 --StepsLeft;
903 return true;
904 }
905
Richard Smith357362d2011-12-13 06:39:58 +0000906 private:
907 /// Add a diagnostic to the diagnostics list.
908 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
909 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
910 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
911 return EvalStatus.Diag->back().second;
912 }
913
Richard Smithf6f003a2011-12-16 19:06:07 +0000914 /// Add notes containing a call stack to the current point of evaluation.
915 void addCallStack(unsigned Limit);
916
Faisal Valie690b7a2016-07-02 22:34:24 +0000917 private:
918 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
919 unsigned ExtraNotes, bool IsCCEDiag) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000920
Richard Smith92b1ce02011-12-12 09:28:41 +0000921 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000922 // If we have a prior diagnostic, it will be noting that the expression
923 // isn't a constant expression. This diagnostic is more important,
924 // unless we require this evaluation to produce a constant expression.
925 //
926 // FIXME: We might want to show both diagnostics to the user in
927 // EM_ConstantFold mode.
928 if (!EvalStatus.Diag->empty()) {
929 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000930 case EM_ConstantFold:
931 case EM_IgnoreSideEffects:
932 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000933 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000934 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000935 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000936 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000937 case EM_ConstantExpression:
938 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000939 case EM_ConstantExpressionUnevaluated:
940 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000941 HasActiveDiagnostic = false;
942 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000943 }
944 }
945
Richard Smithf6f003a2011-12-16 19:06:07 +0000946 unsigned CallStackNotes = CallStackDepth - 1;
947 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
948 if (Limit)
949 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000950 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000951 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000952
Richard Smith357362d2011-12-13 06:39:58 +0000953 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000954 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000955 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000956 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
957 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000958 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000959 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000960 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000961 }
Richard Smith357362d2011-12-13 06:39:58 +0000962 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000963 return OptionalDiagnostic();
964 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000965 public:
966 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
967 OptionalDiagnostic
968 FFDiag(SourceLocation Loc,
969 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
970 unsigned ExtraNotes = 0) {
971 return Diag(Loc, DiagId, ExtraNotes, false);
972 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000973
Faisal Valie690b7a2016-07-02 22:34:24 +0000974 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000975 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000976 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000977 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000978 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000979 HasActiveDiagnostic = false;
980 return OptionalDiagnostic();
981 }
982
Richard Smith92b1ce02011-12-12 09:28:41 +0000983 /// Diagnose that the evaluation does not produce a C++11 core constant
984 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000985 ///
986 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
987 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000988 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000989 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000990 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000991 // Don't override a previous diagnostic. Don't bother collecting
992 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000993 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000994 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000995 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000996 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000997 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000998 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000999 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
1000 = diag::note_invalid_subexpr_in_const_expr,
1001 unsigned ExtraNotes = 0) {
1002 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
1003 }
Richard Smith357362d2011-12-13 06:39:58 +00001004 /// Add a note to a prior diagnostic.
1005 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
1006 if (!HasActiveDiagnostic)
1007 return OptionalDiagnostic();
1008 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +00001009 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00001010
1011 /// Add a stack of notes to a prior diagnostic.
1012 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
1013 if (HasActiveDiagnostic) {
1014 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
1015 Diags.begin(), Diags.end());
1016 }
1017 }
Richard Smith253c2a32012-01-27 01:14:48 +00001018
Richard Smith6d4c6582013-11-05 22:18:15 +00001019 /// Should we continue evaluation after encountering a side-effect that we
1020 /// couldn't model?
1021 bool keepEvaluatingAfterSideEffect() {
1022 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00001023 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001024 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001025 case EM_EvaluateForOverflow:
1026 case EM_IgnoreSideEffects:
1027 return true;
1028
Richard Smith6d4c6582013-11-05 22:18:15 +00001029 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001030 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001031 case EM_ConstantFold:
1032 return false;
1033 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001034 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +00001035 }
1036
1037 /// Note that we have had a side-effect, and determine whether we should
1038 /// keep evaluating.
1039 bool noteSideEffect() {
1040 EvalStatus.HasSideEffects = true;
1041 return keepEvaluatingAfterSideEffect();
1042 }
1043
Richard Smithce8eca52015-12-08 03:21:47 +00001044 /// Should we continue evaluation after encountering undefined behavior?
1045 bool keepEvaluatingAfterUndefinedBehavior() {
1046 switch (EvalMode) {
1047 case EM_EvaluateForOverflow:
1048 case EM_IgnoreSideEffects:
1049 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +00001050 return true;
1051
1052 case EM_PotentialConstantExpression:
1053 case EM_PotentialConstantExpressionUnevaluated:
1054 case EM_ConstantExpression:
1055 case EM_ConstantExpressionUnevaluated:
1056 return false;
1057 }
1058 llvm_unreachable("Missed EvalMode case");
1059 }
1060
1061 /// Note that we hit something that was technically undefined behavior, but
1062 /// that we can evaluate past it (such as signed overflow or floating-point
1063 /// division by zero.)
1064 bool noteUndefinedBehavior() {
1065 EvalStatus.HasUndefinedBehavior = true;
1066 return keepEvaluatingAfterUndefinedBehavior();
1067 }
1068
Richard Smith253c2a32012-01-27 01:14:48 +00001069 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001070 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +00001071 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +00001072 if (!StepsLeft)
1073 return false;
1074
1075 switch (EvalMode) {
1076 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001077 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001078 case EM_EvaluateForOverflow:
1079 return true;
1080
1081 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001082 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001083 case EM_ConstantFold:
1084 case EM_IgnoreSideEffects:
1085 return false;
1086 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001087 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001088 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001089
George Burgess IV8c892b52016-05-25 22:31:54 +00001090 /// Notes that we failed to evaluate an expression that other expressions
1091 /// directly depend on, and determine if we should keep evaluating. This
1092 /// should only be called if we actually intend to keep evaluating.
1093 ///
1094 /// Call noteSideEffect() instead if we may be able to ignore the value that
1095 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1096 ///
1097 /// (Foo(), 1) // use noteSideEffect
1098 /// (Foo() || true) // use noteSideEffect
1099 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001100 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001101 // Failure when evaluating some expression often means there is some
1102 // subexpression whose evaluation was skipped. Therefore, (because we
1103 // don't track whether we skipped an expression when unwinding after an
1104 // evaluation failure) every evaluation failure that bubbles up from a
1105 // subexpression implies that a side-effect has potentially happened. We
1106 // skip setting the HasSideEffects flag to true until we decide to
1107 // continue evaluating after that point, which happens here.
1108 bool KeepGoing = keepEvaluatingAfterFailure();
1109 EvalStatus.HasSideEffects |= KeepGoing;
1110 return KeepGoing;
1111 }
1112
Richard Smith410306b2016-12-12 02:53:20 +00001113 class ArrayInitLoopIndex {
1114 EvalInfo &Info;
1115 uint64_t OuterIndex;
1116
1117 public:
1118 ArrayInitLoopIndex(EvalInfo &Info)
1119 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1120 Info.ArrayInitIndex = 0;
1121 }
1122 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1123
1124 operator uint64_t&() { return Info.ArrayInitIndex; }
1125 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001126 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001127
1128 /// Object used to treat all foldable expressions as constant expressions.
1129 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001130 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001131 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001132 bool HadNoPriorDiags;
1133 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001134
Richard Smith6d4c6582013-11-05 22:18:15 +00001135 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1136 : Info(Info),
1137 Enabled(Enabled),
1138 HadNoPriorDiags(Info.EvalStatus.Diag &&
1139 Info.EvalStatus.Diag->empty() &&
1140 !Info.EvalStatus.HasSideEffects),
1141 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001142 if (Enabled &&
1143 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1144 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001145 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001146 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001147 void keepDiagnostics() { Enabled = false; }
1148 ~FoldConstant() {
1149 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001150 !Info.EvalStatus.HasSideEffects)
1151 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001152 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001153 }
1154 };
Richard Smith17100ba2012-02-16 02:46:34 +00001155
James Y Knight892b09b2018-10-10 02:53:43 +00001156 /// RAII object used to set the current evaluation mode to ignore
1157 /// side-effects.
1158 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001159 EvalInfo &Info;
1160 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001161 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001162 : Info(Info), OldMode(Info.EvalMode) {
1163 if (!Info.checkingPotentialConstantExpression())
James Y Knight892b09b2018-10-10 02:53:43 +00001164 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001165 }
1166
James Y Knight892b09b2018-10-10 02:53:43 +00001167 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001168 };
1169
George Burgess IV8c892b52016-05-25 22:31:54 +00001170 /// RAII object used to optionally suppress diagnostics and side-effects from
1171 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001172 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001173 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001174 Expr::EvalStatus OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001175 unsigned OldSpeculativeEvaluationDepth;
Richard Smith17100ba2012-02-16 02:46:34 +00001176
George Burgess IV8c892b52016-05-25 22:31:54 +00001177 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001178 Info = Other.Info;
1179 OldStatus = Other.OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001180 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001181 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001182 }
1183
1184 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001185 if (!Info)
1186 return;
1187
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001188 Info->EvalStatus = OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001189 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
George Burgess IV8c892b52016-05-25 22:31:54 +00001190 }
1191
Richard Smith17100ba2012-02-16 02:46:34 +00001192 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001193 SpeculativeEvaluationRAII() = default;
1194
1195 SpeculativeEvaluationRAII(
1196 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001197 : Info(&Info), OldStatus(Info.EvalStatus),
Richard Smith37be3362019-05-04 04:00:45 +00001198 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
Richard Smith17100ba2012-02-16 02:46:34 +00001199 Info.EvalStatus.Diag = NewDiag;
Richard Smith37be3362019-05-04 04:00:45 +00001200 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
Richard Smith17100ba2012-02-16 02:46:34 +00001201 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001202
1203 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1204 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1205 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001206 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001207
1208 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1209 maybeRestoreState();
1210 moveFromAndCancel(std::move(Other));
1211 return *this;
1212 }
1213
1214 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001215 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001216
1217 /// RAII object wrapping a full-expression or block scope, and handling
1218 /// the ending of the lifetime of temporaries created within it.
1219 template<bool IsFullExpression>
1220 class ScopeRAII {
1221 EvalInfo &Info;
1222 unsigned OldStackSize;
1223 public:
1224 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001225 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1226 // Push a new temporary version. This is needed to distinguish between
1227 // temporaries created in different iterations of a loop.
1228 Info.CurrentCall->pushTempVersion();
1229 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001230 ~ScopeRAII() {
1231 // Body moved to a static method to encourage the compiler to inline away
1232 // instances of this class.
1233 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001234 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001235 }
1236 private:
1237 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1238 unsigned NewEnd = OldStackSize;
1239 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1240 I != N; ++I) {
1241 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1242 // Full-expression cleanup of a lifetime-extended temporary: nothing
1243 // to do, just move this cleanup to the right place in the stack.
1244 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1245 ++NewEnd;
1246 } else {
1247 // End the lifetime of the object.
1248 Info.CleanupStack[I].endLifetime();
1249 }
1250 }
1251 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1252 Info.CleanupStack.end());
1253 }
1254 };
1255 typedef ScopeRAII<false> BlockScopeRAII;
1256 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001257}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001258
Richard Smitha8105bc2012-01-06 16:39:00 +00001259bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1260 CheckSubobjectKind CSK) {
1261 if (Invalid)
1262 return false;
1263 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001264 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001265 << CSK;
1266 setInvalid();
1267 return false;
1268 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001269 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1270 // must actually be at least one array element; even a VLA cannot have a
1271 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001272 return true;
1273}
1274
Richard Smith6f4f0f12017-10-20 22:56:25 +00001275void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1276 const Expr *E) {
1277 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1278 // Do not set the designator as invalid: we can represent this situation,
1279 // and correct handling of __builtin_object_size requires us to do so.
1280}
1281
Richard Smitha8105bc2012-01-06 16:39:00 +00001282void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001283 const Expr *E,
1284 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001285 // If we're complaining, we must be able to statically determine the size of
1286 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001287 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001288 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001289 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001290 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001291 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001292 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001293 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001294 setInvalid();
1295}
1296
Richard Smithf6f003a2011-12-16 19:06:07 +00001297CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1298 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001299 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001300 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1301 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001302 Info.CurrentCall = this;
1303 ++Info.CallStackDepth;
1304}
1305
1306CallStackFrame::~CallStackFrame() {
1307 assert(Info.CurrentCall == this && "calls retired out of order");
1308 --Info.CallStackDepth;
1309 Info.CurrentCall = Caller;
1310}
1311
Richard Smith08d6a2c2013-07-24 07:11:57 +00001312APValue &CallStackFrame::createTemporary(const void *Key,
1313 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001314 unsigned Version = Info.CurrentCall->getTempVersion();
1315 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smithe637cbe2019-05-21 23:15:18 +00001316 assert(Result.isAbsent() && "temporary created multiple times");
Richard Smith08d6a2c2013-07-24 07:11:57 +00001317 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1318 return Result;
1319}
1320
Richard Smith84401042013-06-03 05:03:02 +00001321static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001322
1323void EvalInfo::addCallStack(unsigned Limit) {
1324 // Determine which calls to skip, if any.
1325 unsigned ActiveCalls = CallStackDepth - 1;
1326 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1327 if (Limit && Limit < ActiveCalls) {
1328 SkipStart = Limit / 2 + Limit % 2;
1329 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001330 }
1331
Richard Smithf6f003a2011-12-16 19:06:07 +00001332 // Walk the call stack and add the diagnostics.
1333 unsigned CallIdx = 0;
1334 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1335 Frame = Frame->Caller, ++CallIdx) {
1336 // Skip this call?
1337 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1338 if (CallIdx == SkipStart) {
1339 // Note that we're skipping calls.
1340 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1341 << unsigned(ActiveCalls - Limit);
1342 }
1343 continue;
1344 }
1345
Richard Smith5179eb72016-06-28 19:03:57 +00001346 // Use a different note for an inheriting constructor, because from the
1347 // user's perspective it's not really a function at all.
1348 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1349 if (CD->isInheritingConstructor()) {
1350 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1351 << CD->getParent();
1352 continue;
1353 }
1354 }
1355
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001356 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001357 llvm::raw_svector_ostream Out(Buffer);
1358 describeCall(Frame, Out);
1359 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1360 }
1361}
1362
Richard Smithdebad642019-05-12 09:39:08 +00001363/// Kinds of access we can perform on an object, for diagnostics. Note that
1364/// we consider a member function call to be a kind of access, even though
1365/// it is not formally an access of the object, because it has (largely) the
1366/// same set of semantic restrictions.
Hubert Tong147b7432018-12-12 16:53:43 +00001367enum AccessKinds {
1368 AK_Read,
1369 AK_Assign,
1370 AK_Increment,
Richard Smithdebad642019-05-12 09:39:08 +00001371 AK_Decrement,
1372 AK_MemberCall,
Richard Smith7bd54ab2019-05-15 20:22:21 +00001373 AK_DynamicCast,
Richard Smitha9330302019-05-17 19:19:28 +00001374 AK_TypeId,
Hubert Tong147b7432018-12-12 16:53:43 +00001375};
1376
Richard Smithdebad642019-05-12 09:39:08 +00001377static bool isModification(AccessKinds AK) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00001378 switch (AK) {
1379 case AK_Read:
1380 case AK_MemberCall:
1381 case AK_DynamicCast:
Richard Smitha9330302019-05-17 19:19:28 +00001382 case AK_TypeId:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001383 return false;
1384 case AK_Assign:
1385 case AK_Increment:
1386 case AK_Decrement:
1387 return true;
1388 }
1389 llvm_unreachable("unknown access kind");
1390}
1391
1392/// Is this an access per the C++ definition?
1393static bool isFormalAccess(AccessKinds AK) {
1394 return AK == AK_Read || isModification(AK);
Richard Smithdebad642019-05-12 09:39:08 +00001395}
1396
Richard Smithf6f003a2011-12-16 19:06:07 +00001397namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001398 struct ComplexValue {
1399 private:
1400 bool IsInt;
1401
1402 public:
1403 APSInt IntReal, IntImag;
1404 APFloat FloatReal, FloatImag;
1405
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001406 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001407
1408 void makeComplexFloat() { IsInt = false; }
1409 bool isComplexFloat() const { return !IsInt; }
1410 APFloat &getComplexFloatReal() { return FloatReal; }
1411 APFloat &getComplexFloatImag() { return FloatImag; }
1412
1413 void makeComplexInt() { IsInt = true; }
1414 bool isComplexInt() const { return IsInt; }
1415 APSInt &getComplexIntReal() { return IntReal; }
1416 APSInt &getComplexIntImag() { return IntImag; }
1417
Richard Smith2e312c82012-03-03 22:46:17 +00001418 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001419 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001420 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001421 else
Richard Smith2e312c82012-03-03 22:46:17 +00001422 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001423 }
Richard Smith2e312c82012-03-03 22:46:17 +00001424 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001425 assert(v.isComplexFloat() || v.isComplexInt());
1426 if (v.isComplexFloat()) {
1427 makeComplexFloat();
1428 FloatReal = v.getComplexFloatReal();
1429 FloatImag = v.getComplexFloatImag();
1430 } else {
1431 makeComplexInt();
1432 IntReal = v.getComplexIntReal();
1433 IntImag = v.getComplexIntImag();
1434 }
1435 }
John McCall93d91dc2010-05-07 17:22:02 +00001436 };
John McCall45d55e42010-05-07 21:00:08 +00001437
1438 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001439 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001440 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001441 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001442 bool IsNullPtr : 1;
1443 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001444
Richard Smithce40ad62011-11-12 22:28:03 +00001445 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001446 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001447 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001448 SubobjectDesignator &getLValueDesignator() { return Designator; }
1449 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001450 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001451
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001452 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1453 unsigned getLValueVersion() const { return Base.getVersion(); }
1454
Richard Smith2e312c82012-03-03 22:46:17 +00001455 void moveInto(APValue &V) const {
1456 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001457 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001458 else {
1459 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001460 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001461 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001462 }
John McCall45d55e42010-05-07 21:00:08 +00001463 }
Richard Smith2e312c82012-03-03 22:46:17 +00001464 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001465 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001466 Base = V.getLValueBase();
1467 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001468 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001469 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001470 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001471 }
1472
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001473 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001474#ifndef NDEBUG
1475 // We only allow a few types of invalid bases. Enforce that here.
1476 if (BInvalid) {
1477 const auto *E = B.get<const Expr *>();
1478 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1479 "Unexpected type of invalid base");
1480 }
1481#endif
1482
Richard Smithce40ad62011-11-12 22:28:03 +00001483 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001484 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001485 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001486 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001487 IsNullPtr = false;
1488 }
1489
1490 void setNull(QualType PointerTy, uint64_t TargetVal) {
1491 Base = (Expr *)nullptr;
1492 Offset = CharUnits::fromQuantity(TargetVal);
1493 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001494 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1495 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001496 }
1497
George Burgess IV3a03fab2015-09-04 21:28:13 +00001498 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001499 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001500 }
1501
Hubert Tong147b7432018-12-12 16:53:43 +00001502 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001503 // Check that this LValue is not based on a null pointer. If it is, produce
1504 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001505 template <typename GenDiagType>
1506 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001507 if (Designator.Invalid)
1508 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001509 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001510 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001511 Designator.setInvalid();
1512 return false;
1513 }
1514 return true;
1515 }
1516
Hubert Tong147b7432018-12-12 16:53:43 +00001517 public:
1518 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1519 CheckSubobjectKind CSK) {
1520 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1521 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1522 });
1523 }
1524
1525 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1526 AccessKinds AK) {
1527 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1528 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1529 });
1530 }
1531
Richard Smitha8105bc2012-01-06 16:39:00 +00001532 // Check this LValue refers to an object. If not, set the designator to be
1533 // invalid and emit a diagnostic.
1534 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001535 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001536 Designator.checkSubobject(Info, E, CSK);
1537 }
1538
1539 void addDecl(EvalInfo &Info, const Expr *E,
1540 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001541 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1542 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001543 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001544 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1545 if (!Designator.Entries.empty()) {
1546 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1547 Designator.setInvalid();
1548 return;
1549 }
Richard Smithefdb5032017-11-15 03:03:56 +00001550 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1551 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1552 Designator.FirstEntryIsAnUnsizedArray = true;
1553 Designator.addUnsizedArrayUnchecked(ElemTy);
1554 }
George Burgess IVe3763372016-12-22 02:50:20 +00001555 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001556 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001557 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1558 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001559 }
Richard Smith66c96992012-02-18 22:04:06 +00001560 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001561 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1562 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001563 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001564 void clearIsNullPointer() {
1565 IsNullPtr = false;
1566 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001567 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1568 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001569 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1570 // but we're not required to diagnose it and it's valid in C++.)
1571 if (!Index)
1572 return;
1573
1574 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1575 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1576 // offsets.
1577 uint64_t Offset64 = Offset.getQuantity();
1578 uint64_t ElemSize64 = ElementSize.getQuantity();
1579 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1580 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1581
1582 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001583 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001584 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001585 }
1586 void adjustOffset(CharUnits N) {
1587 Offset += N;
1588 if (N.getQuantity())
1589 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001590 }
John McCall45d55e42010-05-07 21:00:08 +00001591 };
Richard Smith027bf112011-11-17 22:56:20 +00001592
1593 struct MemberPtr {
1594 MemberPtr() {}
1595 explicit MemberPtr(const ValueDecl *Decl) :
1596 DeclAndIsDerivedMember(Decl, false), Path() {}
1597
1598 /// The member or (direct or indirect) field referred to by this member
1599 /// pointer, or 0 if this is a null member pointer.
1600 const ValueDecl *getDecl() const {
1601 return DeclAndIsDerivedMember.getPointer();
1602 }
1603 /// Is this actually a member of some type derived from the relevant class?
1604 bool isDerivedMember() const {
1605 return DeclAndIsDerivedMember.getInt();
1606 }
1607 /// Get the class which the declaration actually lives in.
1608 const CXXRecordDecl *getContainingRecord() const {
1609 return cast<CXXRecordDecl>(
1610 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1611 }
1612
Richard Smith2e312c82012-03-03 22:46:17 +00001613 void moveInto(APValue &V) const {
1614 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001615 }
Richard Smith2e312c82012-03-03 22:46:17 +00001616 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001617 assert(V.isMemberPointer());
1618 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1619 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1620 Path.clear();
1621 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1622 Path.insert(Path.end(), P.begin(), P.end());
1623 }
1624
1625 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1626 /// whether the member is a member of some class derived from the class type
1627 /// of the member pointer.
1628 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1629 /// Path - The path of base/derived classes from the member declaration's
1630 /// class (exclusive) to the class type of the member pointer (inclusive).
1631 SmallVector<const CXXRecordDecl*, 4> Path;
1632
1633 /// Perform a cast towards the class of the Decl (either up or down the
1634 /// hierarchy).
1635 bool castBack(const CXXRecordDecl *Class) {
1636 assert(!Path.empty());
1637 const CXXRecordDecl *Expected;
1638 if (Path.size() >= 2)
1639 Expected = Path[Path.size() - 2];
1640 else
1641 Expected = getContainingRecord();
1642 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1643 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1644 // if B does not contain the original member and is not a base or
1645 // derived class of the class containing the original member, the result
1646 // of the cast is undefined.
1647 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1648 // (D::*). We consider that to be a language defect.
1649 return false;
1650 }
1651 Path.pop_back();
1652 return true;
1653 }
1654 /// Perform a base-to-derived member pointer cast.
1655 bool castToDerived(const CXXRecordDecl *Derived) {
1656 if (!getDecl())
1657 return true;
1658 if (!isDerivedMember()) {
1659 Path.push_back(Derived);
1660 return true;
1661 }
1662 if (!castBack(Derived))
1663 return false;
1664 if (Path.empty())
1665 DeclAndIsDerivedMember.setInt(false);
1666 return true;
1667 }
1668 /// Perform a derived-to-base member pointer cast.
1669 bool castToBase(const CXXRecordDecl *Base) {
1670 if (!getDecl())
1671 return true;
1672 if (Path.empty())
1673 DeclAndIsDerivedMember.setInt(true);
1674 if (isDerivedMember()) {
1675 Path.push_back(Base);
1676 return true;
1677 }
1678 return castBack(Base);
1679 }
1680 };
Richard Smith357362d2011-12-13 06:39:58 +00001681
Richard Smith7bb00672012-02-01 01:42:44 +00001682 /// Compare two member pointers, which are assumed to be of the same type.
1683 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1684 if (!LHS.getDecl() || !RHS.getDecl())
1685 return !LHS.getDecl() && !RHS.getDecl();
1686 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1687 return false;
1688 return LHS.Path == RHS.Path;
1689 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001690}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001691
Richard Smith2e312c82012-03-03 22:46:17 +00001692static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001693static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1694 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001695 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001696static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1697 bool InvalidBaseOK = false);
1698static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1699 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001700static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1701 EvalInfo &Info);
1702static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001703static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001704static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001705 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001706static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001707static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001708static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1709 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001710static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001711
Leonard Chand3f3e162019-01-18 21:04:25 +00001712/// Evaluate an integer or fixed point expression into an APResult.
1713static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1714 EvalInfo &Info);
1715
1716/// Evaluate only a fixed point expression into an APResult.
1717static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1718 EvalInfo &Info);
1719
Chris Lattner05706e882008-07-11 18:11:29 +00001720//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001721// Misc utilities
1722//===----------------------------------------------------------------------===//
1723
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001724/// A helper function to create a temporary and set an LValue.
1725template <class KeyTy>
1726static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1727 LValue &LV, CallStackFrame &Frame) {
1728 LV.set({Key, Frame.Info.CurrentCall->Index,
1729 Frame.Info.CurrentCall->getTempVersion()});
1730 return Frame.createTemporary(Key, IsLifetimeExtended);
1731}
1732
Richard Smithd6cc1982017-01-31 02:23:02 +00001733/// Negate an APSInt in place, converting it to a signed form if necessary, and
1734/// preserving its value (by extending by up to one bit as needed).
1735static void negateAsSigned(APSInt &Int) {
1736 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1737 Int = Int.extend(Int.getBitWidth() + 1);
1738 Int.setIsSigned(true);
1739 }
1740 Int = -Int;
1741}
1742
Richard Smith84401042013-06-03 05:03:02 +00001743/// Produce a string describing the given constexpr call.
1744static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1745 unsigned ArgIndex = 0;
1746 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1747 !isa<CXXConstructorDecl>(Frame->Callee) &&
1748 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1749
1750 if (!IsMemberCall)
1751 Out << *Frame->Callee << '(';
1752
1753 if (Frame->This && IsMemberCall) {
1754 APValue Val;
1755 Frame->This->moveInto(Val);
1756 Val.printPretty(Out, Frame->Info.Ctx,
1757 Frame->This->Designator.MostDerivedType);
1758 // FIXME: Add parens around Val if needed.
1759 Out << "->" << *Frame->Callee << '(';
1760 IsMemberCall = false;
1761 }
1762
1763 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1764 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1765 if (ArgIndex > (unsigned)IsMemberCall)
1766 Out << ", ";
1767
1768 const ParmVarDecl *Param = *I;
1769 const APValue &Arg = Frame->Arguments[ArgIndex];
1770 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1771
1772 if (ArgIndex == 0 && IsMemberCall)
1773 Out << "->" << *Frame->Callee << '(';
1774 }
1775
1776 Out << ')';
1777}
1778
Richard Smithd9f663b2013-04-22 15:31:51 +00001779/// Evaluate an expression to see if it had side-effects, and discard its
1780/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001781/// \return \c true if the caller should keep evaluating.
1782static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001783 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001784 if (!Evaluate(Scratch, Info, E))
1785 // We don't need the value, but we might have skipped a side effect here.
1786 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001787 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001788}
1789
Richard Smithd62306a2011-11-10 06:34:14 +00001790/// Should this call expression be treated as a string literal?
1791static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001792 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001793 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1794 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1795}
1796
Richard Smithce40ad62011-11-12 22:28:03 +00001797static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001798 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1799 // constant expression of pointer type that evaluates to...
1800
1801 // ... a null pointer value, or a prvalue core constant expression of type
1802 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001803 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001804
Richard Smithce40ad62011-11-12 22:28:03 +00001805 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1806 // ... the address of an object with static storage duration,
1807 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1808 return VD->hasGlobalStorage();
1809 // ... the address of a function,
1810 return isa<FunctionDecl>(D);
1811 }
1812
Richard Smithee0ce3022019-05-17 07:06:46 +00001813 if (B.is<TypeInfoLValue>())
1814 return true;
1815
Richard Smithce40ad62011-11-12 22:28:03 +00001816 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001817 switch (E->getStmtClass()) {
1818 default:
1819 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001820 case Expr::CompoundLiteralExprClass: {
1821 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1822 return CLE->isFileScope() && CLE->isLValue();
1823 }
Richard Smithe6c01442013-06-05 00:46:14 +00001824 case Expr::MaterializeTemporaryExprClass:
1825 // A materialized temporary might have been lifetime-extended to static
1826 // storage duration.
1827 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001828 // A string literal has static storage duration.
1829 case Expr::StringLiteralClass:
1830 case Expr::PredefinedExprClass:
1831 case Expr::ObjCStringLiteralClass:
1832 case Expr::ObjCEncodeExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001833 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001834 return true;
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001835 case Expr::ObjCBoxedExprClass:
1836 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
Richard Smithd62306a2011-11-10 06:34:14 +00001837 case Expr::CallExprClass:
1838 return IsStringLiteralCall(cast<CallExpr>(E));
1839 // For GCC compatibility, &&label has static storage duration.
1840 case Expr::AddrLabelExprClass:
1841 return true;
1842 // A Block literal expression may be used as the initialization value for
1843 // Block variables at global or local static scope.
1844 case Expr::BlockExprClass:
1845 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001846 case Expr::ImplicitValueInitExprClass:
1847 // FIXME:
1848 // We can never form an lvalue with an implicit value initialization as its
1849 // base through expression evaluation, so these only appear in one case: the
1850 // implicit variable declaration we invent when checking whether a constexpr
1851 // constructor can produce a constant expression. We must assume that such
1852 // an expression might be a global lvalue.
1853 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001854 }
John McCall95007602010-05-10 23:27:23 +00001855}
1856
Richard Smith06f71b52018-08-04 00:57:17 +00001857static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1858 return LVal.Base.dyn_cast<const ValueDecl*>();
1859}
1860
1861static bool IsLiteralLValue(const LValue &Value) {
1862 if (Value.getLValueCallIndex())
1863 return false;
1864 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1865 return E && !isa<MaterializeTemporaryExpr>(E);
1866}
1867
1868static bool IsWeakLValue(const LValue &Value) {
1869 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1870 return Decl && Decl->isWeak();
1871}
1872
1873static bool isZeroSized(const LValue &Value) {
1874 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1875 if (Decl && isa<VarDecl>(Decl)) {
1876 QualType Ty = Decl->getType();
1877 if (Ty->isArrayType())
1878 return Ty->isIncompleteType() ||
1879 Decl->getASTContext().getTypeSize(Ty) == 0;
1880 }
1881 return false;
1882}
1883
1884static bool HasSameBase(const LValue &A, const LValue &B) {
1885 if (!A.getLValueBase())
1886 return !B.getLValueBase();
1887 if (!B.getLValueBase())
1888 return false;
1889
1890 if (A.getLValueBase().getOpaqueValue() !=
1891 B.getLValueBase().getOpaqueValue()) {
1892 const Decl *ADecl = GetLValueBaseDecl(A);
1893 if (!ADecl)
1894 return false;
1895 const Decl *BDecl = GetLValueBaseDecl(B);
1896 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1897 return false;
1898 }
1899
1900 return IsGlobalLValue(A.getLValueBase()) ||
1901 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1902 A.getLValueVersion() == B.getLValueVersion());
1903}
1904
Richard Smithb228a862012-02-15 02:18:13 +00001905static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1906 assert(Base && "no location for a null lvalue");
1907 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1908 if (VD)
1909 Info.Note(VD->getLocation(), diag::note_declared_at);
Richard Smithee0ce3022019-05-17 07:06:46 +00001910 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1911 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1912 // We have no information to show for a typeid(T) object.
Richard Smithb228a862012-02-15 02:18:13 +00001913}
1914
Richard Smith80815602011-11-07 05:07:52 +00001915/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001916/// value for an address or reference constant expression. Return true if we
1917/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001918static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001919 QualType Type, const LValue &LVal,
1920 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001921 bool IsReferenceType = Type->isReferenceType();
1922
Richard Smith357362d2011-12-13 06:39:58 +00001923 APValue::LValueBase Base = LVal.getLValueBase();
1924 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1925
Richard Smith0dea49e2012-02-18 04:58:18 +00001926 // Check that the object is a global. Note that the fake 'this' object we
1927 // manufacture when checking potential constant expressions is conservatively
1928 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001929 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001930 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001931 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001932 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001933 << IsReferenceType << !Designator.Entries.empty()
1934 << !!VD << VD;
1935 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001936 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001937 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001938 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001939 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001940 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001941 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001942 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001943 LVal.getLValueCallIndex() == 0) &&
1944 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001945
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001946 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1947 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001948 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001949 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001950 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001951
Hans Wennborg82dd8772014-06-25 22:19:48 +00001952 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001953 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001954 return false;
1955 }
1956 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1957 // __declspec(dllimport) must be handled very carefully:
1958 // We must never initialize an expression with the thunk in C++.
1959 // Doing otherwise would allow the same id-expression to yield
1960 // different addresses for the same function in different translation
1961 // units. However, this means that we must dynamically initialize the
1962 // expression with the contents of the import address table at runtime.
1963 //
1964 // The C language has no notion of ODR; furthermore, it has no notion of
1965 // dynamic initialization. This means that we are permitted to
1966 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001967 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1968 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001969 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001970 }
1971 }
1972
Richard Smitha8105bc2012-01-06 16:39:00 +00001973 // Allow address constant expressions to be past-the-end pointers. This is
1974 // an extension: the standard requires them to point to an object.
1975 if (!IsReferenceType)
1976 return true;
1977
1978 // A reference constant expression must refer to an object.
1979 if (!Base) {
1980 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001981 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001982 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001983 }
1984
Richard Smith357362d2011-12-13 06:39:58 +00001985 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001986 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001987 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001988 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001989 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001990 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001991 }
1992
Richard Smith80815602011-11-07 05:07:52 +00001993 return true;
1994}
1995
Reid Klecknercd016d82017-07-07 22:04:29 +00001996/// Member pointers are constant expressions unless they point to a
1997/// non-virtual dllimport member function.
1998static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1999 SourceLocation Loc,
2000 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00002001 const APValue &Value,
2002 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00002003 const ValueDecl *Member = Value.getMemberPointerDecl();
2004 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2005 if (!FD)
2006 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002007 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2008 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00002009}
2010
Richard Smithfddd3842011-12-30 21:15:51 +00002011/// Check that this core constant expression is of literal type, and if not,
2012/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00002013static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00002014 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002015 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00002016 return true;
2017
Richard Smith7525ff62013-05-09 07:14:00 +00002018 // C++1y: A constant initializer for an object o [...] may also invoke
2019 // constexpr constructors for o and its subobjects even if those objects
2020 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00002021 //
2022 // C++11 missed this detail for aggregates, so classes like this:
2023 // struct foo_t { union { int i; volatile int j; } u; };
2024 // are not (obviously) initializable like so:
2025 // __attribute__((__require_constant_initialization__))
2026 // static const foo_t x = {{0}};
2027 // because "i" is a subobject with non-literal initialization (due to the
2028 // volatile member of the union). See:
2029 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2030 // Therefore, we use the C++1y behavior.
2031 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00002032 return true;
2033
Richard Smithfddd3842011-12-30 21:15:51 +00002034 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002035 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002036 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00002037 << E->getType();
2038 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002039 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00002040 return false;
2041}
2042
Richard Smith0b0a0b62011-10-29 20:57:55 +00002043/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00002044/// constant expression. If not, report an appropriate diagnostic. Does not
2045/// check that the expression is of literal type.
Reid Kleckner1a840d22018-05-10 18:57:35 +00002046static bool
2047CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2048 const APValue &Value,
Richard Smith31c69a32019-05-21 23:15:20 +00002049 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen,
2050 SourceLocation SubobjectLoc = SourceLocation()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002051 if (!Value.hasValue()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002052 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00002053 << true << Type;
Richard Smith31c69a32019-05-21 23:15:20 +00002054 if (SubobjectLoc.isValid())
2055 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
Richard Smith1a90f592013-06-18 17:51:51 +00002056 return false;
2057 }
2058
Richard Smith77be48a2014-07-31 06:31:19 +00002059 // We allow _Atomic(T) to be initialized from anything that T can be
2060 // initialized from.
2061 if (const AtomicType *AT = Type->getAs<AtomicType>())
2062 Type = AT->getValueType();
2063
Richard Smithb228a862012-02-15 02:18:13 +00002064 // Core issue 1454: For a literal constant expression of array or class type,
2065 // each subobject of its value shall have been initialized by a constant
2066 // expression.
2067 if (Value.isArray()) {
2068 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2069 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2070 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
Richard Smith31c69a32019-05-21 23:15:20 +00002071 Value.getArrayInitializedElt(I), Usage,
2072 SubobjectLoc))
Richard Smithb228a862012-02-15 02:18:13 +00002073 return false;
2074 }
2075 if (!Value.hasArrayFiller())
2076 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002077 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
Richard Smith31c69a32019-05-21 23:15:20 +00002078 Usage, SubobjectLoc);
Richard Smith80815602011-11-07 05:07:52 +00002079 }
Richard Smithb228a862012-02-15 02:18:13 +00002080 if (Value.isUnion() && Value.getUnionField()) {
2081 return CheckConstantExpression(Info, DiagLoc,
2082 Value.getUnionField()->getType(),
Richard Smith31c69a32019-05-21 23:15:20 +00002083 Value.getUnionValue(), Usage,
2084 Value.getUnionField()->getLocation());
Richard Smithb228a862012-02-15 02:18:13 +00002085 }
2086 if (Value.isStruct()) {
2087 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2088 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2089 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002090 for (const CXXBaseSpecifier &BS : CD->bases()) {
2091 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
Richard Smith31c69a32019-05-21 23:15:20 +00002092 Value.getStructBase(BaseIndex), Usage,
2093 BS.getBeginLoc()))
Richard Smithb228a862012-02-15 02:18:13 +00002094 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002095 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00002096 }
2097 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002098 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00002099 if (I->isUnnamedBitfield())
2100 continue;
2101
David Blaikie2d7c57e2012-04-30 02:36:29 +00002102 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00002103 Value.getStructField(I->getFieldIndex()),
Richard Smith31c69a32019-05-21 23:15:20 +00002104 Usage, I->getLocation()))
Richard Smithb228a862012-02-15 02:18:13 +00002105 return false;
2106 }
2107 }
2108
2109 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00002110 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00002111 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00002112 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00002113 }
2114
Reid Klecknercd016d82017-07-07 22:04:29 +00002115 if (Value.isMemberPointer())
Reid Kleckner1a840d22018-05-10 18:57:35 +00002116 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00002117
Richard Smithb228a862012-02-15 02:18:13 +00002118 // Everything else is fine.
2119 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002120}
2121
Richard Smith2e312c82012-03-03 22:46:17 +00002122static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00002123 // A null base expression indicates a null pointer. These are always
2124 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00002125 if (!Value.getLValueBase()) {
2126 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002127 return true;
2128 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002129
Richard Smith027bf112011-11-17 22:56:20 +00002130 // We have a non-null base. These are generally known to be true, but if it's
2131 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002132 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002133 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002134 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002135}
2136
Richard Smith2e312c82012-03-03 22:46:17 +00002137static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002138 switch (Val.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002139 case APValue::None:
2140 case APValue::Indeterminate:
Richard Smith11562c52011-10-28 17:51:58 +00002141 return false;
2142 case APValue::Int:
2143 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002144 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00002145 case APValue::FixedPoint:
2146 Result = Val.getFixedPoint().getBoolValue();
2147 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002148 case APValue::Float:
2149 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002150 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002151 case APValue::ComplexInt:
2152 Result = Val.getComplexIntReal().getBoolValue() ||
2153 Val.getComplexIntImag().getBoolValue();
2154 return true;
2155 case APValue::ComplexFloat:
2156 Result = !Val.getComplexFloatReal().isZero() ||
2157 !Val.getComplexFloatImag().isZero();
2158 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002159 case APValue::LValue:
2160 return EvalPointerValueAsBool(Val, Result);
2161 case APValue::MemberPointer:
2162 Result = Val.getMemberPointerDecl();
2163 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002164 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002165 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002166 case APValue::Struct:
2167 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002168 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002169 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002170 }
2171
Richard Smith11562c52011-10-28 17:51:58 +00002172 llvm_unreachable("unknown APValue kind");
2173}
2174
2175static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2176 EvalInfo &Info) {
2177 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002178 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002179 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002180 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002181 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002182}
2183
Richard Smith357362d2011-12-13 06:39:58 +00002184template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002185static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002186 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002187 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002188 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002189 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002190}
2191
2192static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2193 QualType SrcType, const APFloat &Value,
2194 QualType DestType, APSInt &Result) {
2195 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002196 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002197 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002198
Richard Smith357362d2011-12-13 06:39:58 +00002199 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002200 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002201 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2202 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002203 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002204 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002205}
2206
Richard Smith357362d2011-12-13 06:39:58 +00002207static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2208 QualType SrcType, QualType DestType,
2209 APFloat &Result) {
2210 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002211 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002212 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2213 APFloat::rmNearestTiesToEven, &ignored)
2214 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002215 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002216 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002217}
2218
Richard Smith911e1422012-01-30 22:27:01 +00002219static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2220 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002221 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002222 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002223 // Figure out if this is a truncate, extend or noop cast.
2224 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002225 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002226 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002227 if (DestType->isBooleanType())
2228 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002229 return Result;
2230}
2231
Richard Smith357362d2011-12-13 06:39:58 +00002232static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2233 QualType SrcType, const APSInt &Value,
2234 QualType DestType, APFloat &Result) {
2235 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2236 if (Result.convertFromAPInt(Value, Value.isSigned(),
2237 APFloat::rmNearestTiesToEven)
2238 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002239 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002240 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002241}
2242
Richard Smith49ca8aa2013-08-06 07:09:20 +00002243static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2244 APValue &Value, const FieldDecl *FD) {
2245 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2246
2247 if (!Value.isInt()) {
2248 // Trying to store a pointer-cast-to-integer into a bitfield.
2249 // FIXME: In this case, we should provide the diagnostic for casting
2250 // a pointer to an integer.
2251 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002252 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002253 return false;
2254 }
2255
2256 APSInt &Int = Value.getInt();
2257 unsigned OldBitWidth = Int.getBitWidth();
2258 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2259 if (NewBitWidth < OldBitWidth)
2260 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2261 return true;
2262}
2263
Eli Friedman803acb32011-12-22 03:51:45 +00002264static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2265 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002266 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002267 if (!Evaluate(SVal, Info, E))
2268 return false;
2269 if (SVal.isInt()) {
2270 Res = SVal.getInt();
2271 return true;
2272 }
2273 if (SVal.isFloat()) {
2274 Res = SVal.getFloat().bitcastToAPInt();
2275 return true;
2276 }
2277 if (SVal.isVector()) {
2278 QualType VecTy = E->getType();
2279 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2280 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2281 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2282 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2283 Res = llvm::APInt::getNullValue(VecSize);
2284 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2285 APValue &Elt = SVal.getVectorElt(i);
2286 llvm::APInt EltAsInt;
2287 if (Elt.isInt()) {
2288 EltAsInt = Elt.getInt();
2289 } else if (Elt.isFloat()) {
2290 EltAsInt = Elt.getFloat().bitcastToAPInt();
2291 } else {
2292 // Don't try to handle vectors of anything other than int or float
2293 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002294 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002295 return false;
2296 }
2297 unsigned BaseEltSize = EltAsInt.getBitWidth();
2298 if (BigEndian)
2299 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2300 else
2301 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2302 }
2303 return true;
2304 }
2305 // Give up if the input isn't an int, float, or vector. For example, we
2306 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002307 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002308 return false;
2309}
2310
Richard Smith43e77732013-05-07 04:50:00 +00002311/// Perform the given integer operation, which is known to need at most BitWidth
2312/// bits, and check for overflow in the original type (if that type was not an
2313/// unsigned type).
2314template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002315static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2316 const APSInt &LHS, const APSInt &RHS,
2317 unsigned BitWidth, Operation Op,
2318 APSInt &Result) {
2319 if (LHS.isUnsigned()) {
2320 Result = Op(LHS, RHS);
2321 return true;
2322 }
Richard Smith43e77732013-05-07 04:50:00 +00002323
2324 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002325 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002326 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002327 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002328 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002329 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002330 << Result.toString(10) << E->getType();
2331 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002332 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002333 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002334 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002335}
2336
2337/// Perform the given binary integer operation.
2338static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2339 BinaryOperatorKind Opcode, APSInt RHS,
2340 APSInt &Result) {
2341 switch (Opcode) {
2342 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002343 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002344 return false;
2345 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002346 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2347 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002348 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002349 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2350 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002351 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002352 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2353 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002354 case BO_And: Result = LHS & RHS; return true;
2355 case BO_Xor: Result = LHS ^ RHS; return true;
2356 case BO_Or: Result = LHS | RHS; return true;
2357 case BO_Div:
2358 case BO_Rem:
2359 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002360 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002361 return false;
2362 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002363 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2364 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2365 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002366 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2367 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002368 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2369 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002370 return true;
2371 case BO_Shl: {
2372 if (Info.getLangOpts().OpenCL)
2373 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2374 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2375 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2376 RHS.isUnsigned());
2377 else if (RHS.isSigned() && RHS.isNegative()) {
2378 // During constant-folding, a negative shift is an opposite shift. Such
2379 // a shift is not a constant expression.
2380 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2381 RHS = -RHS;
2382 goto shift_right;
2383 }
2384 shift_left:
2385 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2386 // the shifted type.
2387 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2388 if (SA != RHS) {
2389 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2390 << RHS << E->getType() << LHS.getBitWidth();
2391 } else if (LHS.isSigned()) {
2392 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2393 // operand, and must not overflow the corresponding unsigned type.
2394 if (LHS.isNegative())
2395 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2396 else if (LHS.countLeadingZeros() < SA)
2397 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2398 }
2399 Result = LHS << SA;
2400 return true;
2401 }
2402 case BO_Shr: {
2403 if (Info.getLangOpts().OpenCL)
2404 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2405 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2406 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2407 RHS.isUnsigned());
2408 else if (RHS.isSigned() && RHS.isNegative()) {
2409 // During constant-folding, a negative shift is an opposite shift. Such a
2410 // shift is not a constant expression.
2411 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2412 RHS = -RHS;
2413 goto shift_left;
2414 }
2415 shift_right:
2416 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2417 // shifted type.
2418 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2419 if (SA != RHS)
2420 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2421 << RHS << E->getType() << LHS.getBitWidth();
2422 Result = LHS >> SA;
2423 return true;
2424 }
2425
2426 case BO_LT: Result = LHS < RHS; return true;
2427 case BO_GT: Result = LHS > RHS; return true;
2428 case BO_LE: Result = LHS <= RHS; return true;
2429 case BO_GE: Result = LHS >= RHS; return true;
2430 case BO_EQ: Result = LHS == RHS; return true;
2431 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002432 case BO_Cmp:
2433 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002434 }
2435}
2436
Richard Smith861b5b52013-05-07 23:34:45 +00002437/// Perform the given binary floating-point operation, in-place, on LHS.
2438static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2439 APFloat &LHS, BinaryOperatorKind Opcode,
2440 const APFloat &RHS) {
2441 switch (Opcode) {
2442 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002443 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002444 return false;
2445 case BO_Mul:
2446 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2447 break;
2448 case BO_Add:
2449 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2450 break;
2451 case BO_Sub:
2452 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2453 break;
2454 case BO_Div:
2455 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2456 break;
2457 }
2458
Richard Smith0c6124b2015-12-03 01:36:22 +00002459 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002460 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002461 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002462 }
Richard Smith861b5b52013-05-07 23:34:45 +00002463 return true;
2464}
2465
Richard Smitha8105bc2012-01-06 16:39:00 +00002466/// Cast an lvalue referring to a base subobject to a derived class, by
2467/// truncating the lvalue's path to the given length.
2468static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2469 const RecordDecl *TruncatedType,
2470 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002471 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002472
2473 // Check we actually point to a derived class object.
2474 if (TruncatedElements == D.Entries.size())
2475 return true;
2476 assert(TruncatedElements >= D.MostDerivedPathLength &&
2477 "not casting to a derived class");
2478 if (!Result.checkSubobject(Info, E, CSK_Derived))
2479 return false;
2480
2481 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002482 const RecordDecl *RD = TruncatedType;
2483 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002484 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002485 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2486 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002487 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002488 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002489 else
Richard Smithd62306a2011-11-10 06:34:14 +00002490 Result.Offset -= Layout.getBaseClassOffset(Base);
2491 RD = Base;
2492 }
Richard Smith027bf112011-11-17 22:56:20 +00002493 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002494 return true;
2495}
2496
John McCalld7bca762012-05-01 00:38:49 +00002497static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002498 const CXXRecordDecl *Derived,
2499 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002500 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002501 if (!RL) {
2502 if (Derived->isInvalidDecl()) return false;
2503 RL = &Info.Ctx.getASTRecordLayout(Derived);
2504 }
2505
Richard Smithd62306a2011-11-10 06:34:14 +00002506 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002507 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002508 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002509}
2510
Richard Smitha8105bc2012-01-06 16:39:00 +00002511static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002512 const CXXRecordDecl *DerivedDecl,
2513 const CXXBaseSpecifier *Base) {
2514 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2515
John McCalld7bca762012-05-01 00:38:49 +00002516 if (!Base->isVirtual())
2517 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002518
Richard Smitha8105bc2012-01-06 16:39:00 +00002519 SubobjectDesignator &D = Obj.Designator;
2520 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002521 return false;
2522
Richard Smitha8105bc2012-01-06 16:39:00 +00002523 // Extract most-derived object and corresponding type.
2524 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2525 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2526 return false;
2527
2528 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002529 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002530 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2531 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002532 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002533 return true;
2534}
2535
Richard Smith84401042013-06-03 05:03:02 +00002536static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2537 QualType Type, LValue &Result) {
2538 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2539 PathE = E->path_end();
2540 PathI != PathE; ++PathI) {
2541 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2542 *PathI))
2543 return false;
2544 Type = (*PathI)->getType();
2545 }
2546 return true;
2547}
2548
Richard Smith921f1322019-05-13 23:35:21 +00002549/// Cast an lvalue referring to a derived class to a known base subobject.
2550static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2551 const CXXRecordDecl *DerivedRD,
2552 const CXXRecordDecl *BaseRD) {
2553 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2554 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2555 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2556 llvm_unreachable("Class must be derived from the passed in base class!");
2557
2558 for (CXXBasePathElement &Elem : Paths.front())
2559 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2560 return false;
2561 return true;
2562}
2563
Richard Smithd62306a2011-11-10 06:34:14 +00002564/// Update LVal to refer to the given field, which must be a member of the type
2565/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002566static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002567 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002568 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002569 if (!RL) {
2570 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002571 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002572 }
Richard Smithd62306a2011-11-10 06:34:14 +00002573
2574 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002575 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002576 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002577 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002578}
2579
Richard Smith1b78b3d2012-01-25 22:15:11 +00002580/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002581static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002582 LValue &LVal,
2583 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002584 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002585 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002586 return false;
2587 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002588}
2589
Richard Smithd62306a2011-11-10 06:34:14 +00002590/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002591static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2592 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002593 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2594 // extension.
2595 if (Type->isVoidType() || Type->isFunctionType()) {
2596 Size = CharUnits::One();
2597 return true;
2598 }
2599
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002600 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002601 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002602 return false;
2603 }
2604
Richard Smithd62306a2011-11-10 06:34:14 +00002605 if (!Type->isConstantSizeType()) {
2606 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002607 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002608 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002609 return false;
2610 }
2611
2612 Size = Info.Ctx.getTypeSizeInChars(Type);
2613 return true;
2614}
2615
2616/// Update a pointer value to model pointer arithmetic.
2617/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002618/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002619/// \param LVal - The pointer value to be updated.
2620/// \param EltTy - The pointee type represented by LVal.
2621/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002622static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2623 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002624 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002625 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002626 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002627 return false;
2628
Yaxun Liu402804b2016-12-15 08:09:08 +00002629 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002630 return true;
2631}
2632
Richard Smithd6cc1982017-01-31 02:23:02 +00002633static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2634 LValue &LVal, QualType EltTy,
2635 int64_t Adjustment) {
2636 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2637 APSInt::get(Adjustment));
2638}
2639
Richard Smith66c96992012-02-18 22:04:06 +00002640/// Update an lvalue to refer to a component of a complex number.
2641/// \param Info - Information about the ongoing evaluation.
2642/// \param LVal - The lvalue to be updated.
2643/// \param EltTy - The complex number's component type.
2644/// \param Imag - False for the real component, true for the imaginary.
2645static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2646 LValue &LVal, QualType EltTy,
2647 bool Imag) {
2648 if (Imag) {
2649 CharUnits SizeOfComponent;
2650 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2651 return false;
2652 LVal.Offset += SizeOfComponent;
2653 }
2654 LVal.addComplex(Info, E, EltTy, Imag);
2655 return true;
2656}
2657
Faisal Vali051e3a22017-02-16 04:12:21 +00002658static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2659 QualType Type, const LValue &LVal,
2660 APValue &RVal);
2661
Richard Smith27908702011-10-24 17:54:18 +00002662/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002663///
2664/// \param Info Information about the ongoing evaluation.
2665/// \param E An expression to be used when printing diagnostics.
2666/// \param VD The variable whose initializer should be obtained.
2667/// \param Frame The frame in which the variable was created. Must be null
2668/// if this variable is not local to the evaluation.
2669/// \param Result Filled in with a pointer to the value of the variable.
2670static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2671 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002672 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002673
Richard Smith254a73d2011-10-28 22:34:42 +00002674 // If this is a parameter to an active constexpr function call, perform
2675 // argument substitution.
2676 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002677 // Assume arguments of a potential constant expression are unknown
2678 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002679 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002680 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002681 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002682 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002683 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002684 }
Richard Smith3229b742013-05-05 21:17:10 +00002685 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002686 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002687 }
Richard Smith27908702011-10-24 17:54:18 +00002688
Richard Smithd9f663b2013-04-22 15:31:51 +00002689 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002690 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002691 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2692 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002693 if (!Result) {
2694 // Assume variables referenced within a lambda's call operator that were
2695 // not declared within the call operator are captures and during checking
2696 // of a potential constant expression, assume they are unknown constant
2697 // expressions.
2698 assert(isLambdaCallOperator(Frame->Callee) &&
2699 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2700 "missing value for local variable");
2701 if (Info.checkingPotentialConstantExpression())
2702 return false;
2703 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002704 Info.FFDiag(E->getBeginLoc(),
2705 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002706 << "captures not currently allowed";
2707 return false;
2708 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002709 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002710 }
2711
Richard Smithd0b4dd62011-12-19 06:19:21 +00002712 // Dig out the initializer, and use the declaration which it's attached to.
2713 const Expr *Init = VD->getAnyInitializer(VD);
2714 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002715 // If we're checking a potential constant expression, the variable could be
2716 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002717 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002718 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002719 return false;
2720 }
2721
Richard Smithd62306a2011-11-10 06:34:14 +00002722 // If we're currently evaluating the initializer of this declaration, use that
2723 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002724 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002725 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002726 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002727 }
2728
Richard Smithcecf1842011-11-01 21:06:14 +00002729 // Never evaluate the initializer of a weak variable. We can't be sure that
2730 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002731 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002732 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002733 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002734 }
Richard Smithcecf1842011-11-01 21:06:14 +00002735
Richard Smithd0b4dd62011-12-19 06:19:21 +00002736 // Check that we can fold the initializer. In C++, we will have already done
2737 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002738 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002739 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002740 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002741 Notes.size() + 1) << VD;
2742 Info.Note(VD->getLocation(), diag::note_declared_at);
2743 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002744 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002745 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002746 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002747 Notes.size() + 1) << VD;
2748 Info.Note(VD->getLocation(), diag::note_declared_at);
2749 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002750 }
Richard Smith27908702011-10-24 17:54:18 +00002751
Richard Smith3229b742013-05-05 21:17:10 +00002752 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002753 return true;
Richard Smith27908702011-10-24 17:54:18 +00002754}
2755
Richard Smith11562c52011-10-28 17:51:58 +00002756static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002757 Qualifiers Quals = T.getQualifiers();
2758 return Quals.hasConst() && !Quals.hasVolatile();
2759}
2760
Richard Smithe97cbd72011-11-11 04:05:33 +00002761/// Get the base index of the given base class within an APValue representing
2762/// the given derived class.
2763static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2764 const CXXRecordDecl *Base) {
2765 Base = Base->getCanonicalDecl();
2766 unsigned Index = 0;
2767 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2768 E = Derived->bases_end(); I != E; ++I, ++Index) {
2769 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2770 return Index;
2771 }
2772
2773 llvm_unreachable("base class missing from derived class's bases list");
2774}
2775
Richard Smith3da88fa2013-04-26 14:36:30 +00002776/// Extract the value of a character from a string literal.
2777static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2778 uint64_t Index) {
Eric Fiselier708afb52019-05-16 21:04:15 +00002779 assert(!isa<SourceLocExpr>(Lit) &&
2780 "SourceLocExpr should have already been converted to a StringLiteral");
2781
Akira Hatanakabc332642017-01-31 02:31:39 +00002782 // FIXME: Support MakeStringConstant
2783 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2784 std::string Str;
2785 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2786 assert(Index <= Str.size() && "Index too large");
2787 return APSInt::getUnsigned(Str.c_str()[Index]);
2788 }
2789
Alexey Bataevec474782014-10-09 08:45:04 +00002790 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2791 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002792 const StringLiteral *S = cast<StringLiteral>(Lit);
2793 const ConstantArrayType *CAT =
2794 Info.Ctx.getAsConstantArrayType(S->getType());
2795 assert(CAT && "string literal isn't an array");
2796 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002797 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002798
2799 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002800 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002801 if (Index < S->getLength())
2802 Value = S->getCodeUnit(Index);
2803 return Value;
2804}
2805
Richard Smith3da88fa2013-04-26 14:36:30 +00002806// Expand a string literal into an array of characters.
Eli Friedman3bf72d72019-02-08 21:18:46 +00002807//
2808// FIXME: This is inefficient; we should probably introduce something similar
2809// to the LLVM ConstantDataArray to make this cheaper.
2810static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
Richard Smith3da88fa2013-04-26 14:36:30 +00002811 APValue &Result) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002812 const ConstantArrayType *CAT =
2813 Info.Ctx.getAsConstantArrayType(S->getType());
2814 assert(CAT && "string literal isn't an array");
2815 QualType CharType = CAT->getElementType();
2816 assert(CharType->isIntegerType() && "unexpected character type");
2817
2818 unsigned Elts = CAT->getSize().getZExtValue();
2819 Result = APValue(APValue::UninitArray(),
2820 std::min(S->getLength(), Elts), Elts);
2821 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2822 CharType->isUnsignedIntegerType());
2823 if (Result.hasArrayFiller())
2824 Result.getArrayFiller() = APValue(Value);
2825 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2826 Value = S->getCodeUnit(I);
2827 Result.getArrayInitializedElt(I) = APValue(Value);
2828 }
2829}
2830
2831// Expand an array so that it has more than Index filled elements.
2832static void expandArray(APValue &Array, unsigned Index) {
2833 unsigned Size = Array.getArraySize();
2834 assert(Index < Size);
2835
2836 // Always at least double the number of elements for which we store a value.
2837 unsigned OldElts = Array.getArrayInitializedElts();
2838 unsigned NewElts = std::max(Index+1, OldElts * 2);
2839 NewElts = std::min(Size, std::max(NewElts, 8u));
2840
2841 // Copy the data across.
2842 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2843 for (unsigned I = 0; I != OldElts; ++I)
2844 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2845 for (unsigned I = OldElts; I != NewElts; ++I)
2846 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2847 if (NewValue.hasArrayFiller())
2848 NewValue.getArrayFiller() = Array.getArrayFiller();
2849 Array.swap(NewValue);
2850}
2851
Richard Smithb01fe402014-09-16 01:24:02 +00002852/// Determine whether a type would actually be read by an lvalue-to-rvalue
2853/// conversion. If it's of class type, we may assume that the copy operation
2854/// is trivial. Note that this is never true for a union type with fields
2855/// (because the copy always "reads" the active member) and always true for
2856/// a non-class type.
2857static bool isReadByLvalueToRvalueConversion(QualType T) {
2858 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2859 if (!RD || (RD->isUnion() && !RD->field_empty()))
2860 return true;
2861 if (RD->isEmpty())
2862 return false;
2863
2864 for (auto *Field : RD->fields())
2865 if (isReadByLvalueToRvalueConversion(Field->getType()))
2866 return true;
2867
2868 for (auto &BaseSpec : RD->bases())
2869 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2870 return true;
2871
2872 return false;
2873}
2874
2875/// Diagnose an attempt to read from any unreadable field within the specified
2876/// type, which might be a class type.
2877static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2878 QualType T) {
2879 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2880 if (!RD)
2881 return false;
2882
2883 if (!RD->hasMutableFields())
2884 return false;
2885
2886 for (auto *Field : RD->fields()) {
2887 // If we're actually going to read this field in some way, then it can't
2888 // be mutable. If we're in a union, then assigning to a mutable field
2889 // (even an empty one) can change the active member, so that's not OK.
2890 // FIXME: Add core issue number for the union case.
2891 if (Field->isMutable() &&
2892 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002893 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002894 Info.Note(Field->getLocation(), diag::note_declared_at);
2895 return true;
2896 }
2897
2898 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2899 return true;
2900 }
2901
2902 for (auto &BaseSpec : RD->bases())
2903 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2904 return true;
2905
2906 // All mutable fields were empty, and thus not actually read.
2907 return false;
2908}
2909
Richard Smithdebad642019-05-12 09:39:08 +00002910static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2911 APValue::LValueBase Base) {
2912 // A temporary we created.
2913 if (Base.getCallIndex())
2914 return true;
2915
2916 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2917 if (!Evaluating)
2918 return false;
2919
2920 // The variable whose initializer we're evaluating.
2921 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2922 if (declaresSameEntity(Evaluating, BaseD))
2923 return true;
2924
2925 // A temporary lifetime-extended by the variable whose initializer we're
2926 // evaluating.
2927 if (auto *BaseE = Base.dyn_cast<const Expr *>())
2928 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2929 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2930 return true;
2931
2932 return false;
2933}
2934
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002935namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002936/// A handle to a complete object (an object that is not a subobject of
2937/// another object).
2938struct CompleteObject {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002939 /// The identity of the object.
2940 APValue::LValueBase Base;
Richard Smith3229b742013-05-05 21:17:10 +00002941 /// The value of the complete object.
2942 APValue *Value;
2943 /// The type of the complete object.
2944 QualType Type;
2945
Craig Topper36250ad2014-05-12 05:36:57 +00002946 CompleteObject() : Value(nullptr) {}
Richard Smithdebad642019-05-12 09:39:08 +00002947 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2948 : Base(Base), Value(Value), Type(Type) {}
2949
2950 bool mayReadMutableMembers(EvalInfo &Info) const {
2951 // In C++14 onwards, it is permitted to read a mutable member whose
2952 // lifetime began within the evaluation.
2953 // FIXME: Should we also allow this in C++11?
2954 if (!Info.getLangOpts().CPlusPlus14)
2955 return false;
2956 return lifetimeStartedInEvaluation(Info, Base);
Richard Smith3229b742013-05-05 21:17:10 +00002957 }
2958
Richard Smithdebad642019-05-12 09:39:08 +00002959 explicit operator bool() const { return !Type.isNull(); }
Richard Smith3229b742013-05-05 21:17:10 +00002960};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002961} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002962
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002963static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2964 bool IsMutable = false) {
2965 // C++ [basic.type.qualifier]p1:
2966 // - A const object is an object of type const T or a non-mutable subobject
2967 // of a const object.
2968 if (ObjType.isConstQualified() && !IsMutable)
2969 SubobjType.addConst();
2970 // - A volatile object is an object of type const T or a subobject of a
2971 // volatile object.
2972 if (ObjType.isVolatileQualified())
2973 SubobjType.addVolatile();
2974 return SubobjType;
2975}
2976
Richard Smith3da88fa2013-04-26 14:36:30 +00002977/// Find the designated sub-object of an rvalue.
2978template<typename SubobjectHandler>
2979typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002980findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002981 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002982 if (Sub.Invalid)
2983 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002984 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002985 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002986 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002987 Info.FFDiag(E, Sub.isOnePastTheEnd()
2988 ? diag::note_constexpr_access_past_end
2989 : diag::note_constexpr_access_unsized_array)
2990 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002991 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002992 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002993 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002994 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002995
Richard Smith3229b742013-05-05 21:17:10 +00002996 APValue *O = Obj.Value;
2997 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002998 const FieldDecl *LastField = nullptr;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002999 const FieldDecl *VolatileField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00003000
Richard Smithd62306a2011-11-10 06:34:14 +00003001 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003002 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
Richard Smith31c69a32019-05-21 23:15:20 +00003003 // Reading an indeterminate value is undefined, but assigning over one is OK.
3004 if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003005 if (!Info.checkingPotentialConstantExpression())
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003006 Info.FFDiag(E, diag::note_constexpr_access_uninit)
Richard Smithe637cbe2019-05-21 23:15:18 +00003007 << handler.AccessKind << O->isIndeterminate();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003008 return handler.failed();
3009 }
3010
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003011 // C++ [class.ctor]p5:
3012 // const and volatile semantics are not applied on an object under
3013 // construction.
3014 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3015 ObjType->isRecordType() &&
3016 Info.isEvaluatingConstructor(
3017 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3018 Sub.Entries.begin() + I)) !=
3019 ConstructionPhase::None) {
3020 ObjType = Info.Ctx.getCanonicalType(ObjType);
3021 ObjType.removeLocalConst();
3022 ObjType.removeLocalVolatile();
3023 }
3024
3025 // If this is our last pass, check that the final object type is OK.
3026 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3027 // Accesses to volatile objects are prohibited.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003028 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003029 if (Info.getLangOpts().CPlusPlus) {
3030 int DiagKind;
3031 SourceLocation Loc;
3032 const NamedDecl *Decl = nullptr;
3033 if (VolatileField) {
3034 DiagKind = 2;
3035 Loc = VolatileField->getLocation();
3036 Decl = VolatileField;
3037 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3038 DiagKind = 1;
3039 Loc = VD->getLocation();
3040 Decl = VD;
3041 } else {
3042 DiagKind = 0;
3043 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3044 Loc = E->getExprLoc();
3045 }
3046 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3047 << handler.AccessKind << DiagKind << Decl;
3048 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3049 } else {
3050 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3051 }
3052 return handler.failed();
3053 }
3054
Richard Smithb01fe402014-09-16 01:24:02 +00003055 // If we are reading an object of class type, there may still be more
3056 // things we need to check: if there are any mutable subobjects, we
3057 // cannot perform this read. (This only happens when performing a trivial
3058 // copy or assignment.)
3059 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smithdebad642019-05-12 09:39:08 +00003060 !Obj.mayReadMutableMembers(Info) &&
3061 diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00003062 return handler.failed();
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003063 }
Richard Smithb01fe402014-09-16 01:24:02 +00003064
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003065 if (I == N) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00003066 if (!handler.found(*O, ObjType))
3067 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003068
Richard Smith49ca8aa2013-08-06 07:09:20 +00003069 // If we modified a bit-field, truncate it to the right width.
Richard Smithdebad642019-05-12 09:39:08 +00003070 if (isModification(handler.AccessKind) &&
Richard Smith49ca8aa2013-08-06 07:09:20 +00003071 LastField && LastField->isBitField() &&
3072 !truncateBitfieldValue(Info, E, *O, LastField))
3073 return false;
3074
3075 return true;
3076 }
3077
Craig Topper36250ad2014-05-12 05:36:57 +00003078 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00003079 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00003080 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00003081 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003082 assert(CAT && "vla in literal type?");
Richard Smith5b5e27a2019-05-10 20:05:31 +00003083 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003084 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00003085 // Note, it should not be possible to form a pointer with a valid
3086 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00003087 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003088 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003089 << handler.AccessKind;
3090 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003091 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003092 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003093 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003094
3095 ObjType = CAT->getElementType();
3096
Richard Smith3da88fa2013-04-26 14:36:30 +00003097 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00003098 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00003099 else if (handler.AccessKind != AK_Read) {
3100 expandArray(*O, Index);
3101 O = &O->getArrayInitializedElt(Index);
3102 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00003103 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00003104 } else if (ObjType->isAnyComplexType()) {
3105 // Next subobject is a complex number.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003106 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smith66c96992012-02-18 22:04:06 +00003107 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003108 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003109 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003110 << handler.AccessKind;
3111 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003112 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003113 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00003114 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003115
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003116 ObjType = getSubobjectType(
3117 ObjType, ObjType->castAs<ComplexType>()->getElementType());
Richard Smith3da88fa2013-04-26 14:36:30 +00003118
Richard Smith66c96992012-02-18 22:04:06 +00003119 assert(I == N - 1 && "extracting subobject of scalar?");
3120 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003121 return handler.found(Index ? O->getComplexIntImag()
3122 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003123 } else {
3124 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00003125 return handler.found(Index ? O->getComplexFloatImag()
3126 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003127 }
Richard Smithd62306a2011-11-10 06:34:14 +00003128 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00003129 if (Field->isMutable() && handler.AccessKind == AK_Read &&
Richard Smithdebad642019-05-12 09:39:08 +00003130 !Obj.mayReadMutableMembers(Info)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003131 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00003132 << Field;
3133 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00003134 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00003135 }
3136
Richard Smithd62306a2011-11-10 06:34:14 +00003137 // Next subobject is a class, struct or union field.
3138 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3139 if (RD->isUnion()) {
3140 const FieldDecl *UnionField = O->getUnionField();
3141 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00003142 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003143 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00003144 << handler.AccessKind << Field << !UnionField << UnionField;
3145 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003146 }
Richard Smithd62306a2011-11-10 06:34:14 +00003147 O = &O->getUnionValue();
3148 } else
3149 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00003150
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003151 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
Richard Smith49ca8aa2013-08-06 07:09:20 +00003152 LastField = Field;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003153 if (Field->getType().isVolatileQualified())
3154 VolatileField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00003155 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00003156 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00003157 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3158 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3159 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00003160
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003161 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
Richard Smithf3e9e432011-11-07 09:22:26 +00003162 }
3163 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003164}
3165
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003166namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003167struct ExtractSubobjectHandler {
3168 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00003169 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00003170
3171 static const AccessKinds AccessKind = AK_Read;
3172
3173 typedef bool result_type;
3174 bool failed() { return false; }
3175 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003176 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00003177 return true;
3178 }
3179 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003180 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003181 return true;
3182 }
3183 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003184 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003185 return true;
3186 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003187};
Richard Smith3229b742013-05-05 21:17:10 +00003188} // end anonymous namespace
3189
Richard Smith3da88fa2013-04-26 14:36:30 +00003190const AccessKinds ExtractSubobjectHandler::AccessKind;
3191
3192/// Extract the designated sub-object of an rvalue.
3193static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003194 const CompleteObject &Obj,
3195 const SubobjectDesignator &Sub,
3196 APValue &Result) {
3197 ExtractSubobjectHandler Handler = { Info, Result };
3198 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003199}
3200
Richard Smith3229b742013-05-05 21:17:10 +00003201namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003202struct ModifySubobjectHandler {
3203 EvalInfo &Info;
3204 APValue &NewVal;
3205 const Expr *E;
3206
3207 typedef bool result_type;
3208 static const AccessKinds AccessKind = AK_Assign;
3209
3210 bool checkConst(QualType QT) {
3211 // Assigning to a const object has undefined behavior.
3212 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003213 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003214 return false;
3215 }
3216 return true;
3217 }
3218
3219 bool failed() { return false; }
3220 bool found(APValue &Subobj, QualType SubobjType) {
3221 if (!checkConst(SubobjType))
3222 return false;
3223 // We've been given ownership of NewVal, so just swap it in.
3224 Subobj.swap(NewVal);
3225 return true;
3226 }
3227 bool found(APSInt &Value, QualType SubobjType) {
3228 if (!checkConst(SubobjType))
3229 return false;
3230 if (!NewVal.isInt()) {
3231 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003232 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003233 return false;
3234 }
3235 Value = NewVal.getInt();
3236 return true;
3237 }
3238 bool found(APFloat &Value, QualType SubobjType) {
3239 if (!checkConst(SubobjType))
3240 return false;
3241 Value = NewVal.getFloat();
3242 return true;
3243 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003244};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003245} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003246
Richard Smith3229b742013-05-05 21:17:10 +00003247const AccessKinds ModifySubobjectHandler::AccessKind;
3248
Richard Smith3da88fa2013-04-26 14:36:30 +00003249/// Update the designated sub-object of an rvalue to the given value.
3250static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003251 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003252 const SubobjectDesignator &Sub,
3253 APValue &NewVal) {
3254 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003255 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003256}
3257
Richard Smith84f6dcf2012-02-02 01:16:57 +00003258/// Find the position where two subobject designators diverge, or equivalently
3259/// the length of the common initial subsequence.
3260static unsigned FindDesignatorMismatch(QualType ObjType,
3261 const SubobjectDesignator &A,
3262 const SubobjectDesignator &B,
3263 bool &WasArrayIndex) {
3264 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3265 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003266 if (!ObjType.isNull() &&
3267 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003268 // Next subobject is an array element.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003269 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003270 WasArrayIndex = true;
3271 return I;
3272 }
Richard Smith66c96992012-02-18 22:04:06 +00003273 if (ObjType->isAnyComplexType())
3274 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3275 else
3276 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003277 } else {
Richard Smith5b5e27a2019-05-10 20:05:31 +00003278 if (A.Entries[I].getAsBaseOrMember() !=
3279 B.Entries[I].getAsBaseOrMember()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003280 WasArrayIndex = false;
3281 return I;
3282 }
3283 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3284 // Next subobject is a field.
3285 ObjType = FD->getType();
3286 else
3287 // Next subobject is a base class.
3288 ObjType = QualType();
3289 }
3290 }
3291 WasArrayIndex = false;
3292 return I;
3293}
3294
3295/// Determine whether the given subobject designators refer to elements of the
3296/// same array object.
3297static bool AreElementsOfSameArray(QualType ObjType,
3298 const SubobjectDesignator &A,
3299 const SubobjectDesignator &B) {
3300 if (A.Entries.size() != B.Entries.size())
3301 return false;
3302
George Burgess IVa51c4072015-10-16 01:49:01 +00003303 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003304 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3305 // A is a subobject of the array element.
3306 return false;
3307
3308 // If A (and B) designates an array element, the last entry will be the array
3309 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3310 // of length 1' case, and the entire path must match.
3311 bool WasArrayIndex;
3312 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3313 return CommonLength >= A.Entries.size() - IsArray;
3314}
3315
Richard Smith3229b742013-05-05 21:17:10 +00003316/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003317static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3318 AccessKinds AK, const LValue &LVal,
3319 QualType LValType) {
Richard Smith51ce8442019-05-17 08:01:34 +00003320 if (LVal.InvalidBase) {
3321 Info.FFDiag(E);
3322 return CompleteObject();
3323 }
3324
Richard Smith3229b742013-05-05 21:17:10 +00003325 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003326 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003327 return CompleteObject();
3328 }
3329
Craig Topper36250ad2014-05-12 05:36:57 +00003330 CallStackFrame *Frame = nullptr;
Richard Smith37be3362019-05-04 04:00:45 +00003331 unsigned Depth = 0;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003332 if (LVal.getLValueCallIndex()) {
Richard Smith37be3362019-05-04 04:00:45 +00003333 std::tie(Frame, Depth) =
3334 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003335 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003336 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003337 << AK << LVal.Base.is<const ValueDecl*>();
3338 NoteLValueLocation(Info, LVal.Base);
3339 return CompleteObject();
3340 }
Richard Smith3229b742013-05-05 21:17:10 +00003341 }
3342
Richard Smith7bd54ab2019-05-15 20:22:21 +00003343 bool IsAccess = isFormalAccess(AK);
3344
Richard Smith3229b742013-05-05 21:17:10 +00003345 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3346 // is not a constant expression (even if the object is non-volatile). We also
3347 // apply this rule to C++98, in order to conform to the expected 'volatile'
3348 // semantics.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003349 if (IsAccess && LValType.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003350 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003351 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003352 << AK << LValType;
3353 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003354 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003355 return CompleteObject();
3356 }
3357
3358 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003359 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003360 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00003361
3362 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3363 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3364 // In C++11, constexpr, non-volatile variables initialized with constant
3365 // expressions are constant expressions too. Inside constexpr functions,
3366 // parameters are constant expressions even if they're non-const.
3367 // In C++1y, objects local to a constant expression (those with a Frame) are
3368 // both readable and writable inside constant expressions.
3369 // In C, such things can also be folded, although they are not ICEs.
3370 const VarDecl *VD = dyn_cast<VarDecl>(D);
3371 if (VD) {
3372 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3373 VD = VDef;
3374 }
3375 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003376 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003377 return CompleteObject();
3378 }
3379
Richard Smith3229b742013-05-05 21:17:10 +00003380 // Unless we're looking at a local variable or argument in a constexpr call,
3381 // the variable we're reading must be const.
3382 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003383 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smithdebad642019-05-12 09:39:08 +00003384 declaresSameEntity(
3385 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003386 // OK, we can read and modify an object if we're in the process of
3387 // evaluating its initializer, because its lifetime began in this
3388 // evaluation.
Richard Smithdebad642019-05-12 09:39:08 +00003389 } else if (isModification(AK)) {
3390 // All the remaining cases do not permit modification of the object.
Faisal Valie690b7a2016-07-02 22:34:24 +00003391 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003392 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003393 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003394 // OK, we can read this variable.
3395 } else if (BaseType->isIntegralOrEnumerationType()) {
Richard Smithdebad642019-05-12 09:39:08 +00003396 // In OpenCL if a variable is in constant address space it is a const
3397 // value.
Xiuli Pan244e3f62016-06-07 04:34:00 +00003398 if (!(BaseType.isConstQualified() ||
3399 (Info.getLangOpts().OpenCL &&
3400 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003401 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003402 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003403 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003404 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003405 Info.Note(VD->getLocation(), diag::note_declared_at);
3406 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003407 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003408 }
3409 return CompleteObject();
3410 }
Richard Smith7bd54ab2019-05-15 20:22:21 +00003411 } else if (!IsAccess) {
Richard Smithdebad642019-05-12 09:39:08 +00003412 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003413 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3414 // We support folding of const floating-point types, in order to make
3415 // static const data members of such types (supported as an extension)
3416 // more useful.
3417 if (Info.getLangOpts().CPlusPlus11) {
3418 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3419 Info.Note(VD->getLocation(), diag::note_declared_at);
3420 } else {
3421 Info.CCEDiag(E);
3422 }
George Burgess IVb5316982016-12-27 05:33:20 +00003423 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3424 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3425 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003426 } else {
3427 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003428 if (Info.checkingPotentialConstantExpression() &&
3429 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3430 // The definition of this variable could be constexpr. We can't
3431 // access it right now, but may be able to in future.
3432 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003433 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003434 Info.Note(VD->getLocation(), diag::note_declared_at);
3435 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003436 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003437 }
3438 return CompleteObject();
3439 }
3440 }
3441
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003442 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003443 return CompleteObject();
3444 } else {
3445 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3446
3447 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003448 if (const MaterializeTemporaryExpr *MTE =
Richard Smithee0ce3022019-05-17 07:06:46 +00003449 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
Richard Smithe6c01442013-06-05 00:46:14 +00003450 assert(MTE->getStorageDuration() == SD_Static &&
3451 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003452
Richard Smithe6c01442013-06-05 00:46:14 +00003453 // Per C++1y [expr.const]p2:
3454 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3455 // - a [...] glvalue of integral or enumeration type that refers to
3456 // a non-volatile const object [...]
3457 // [...]
3458 // - a [...] glvalue of literal type that refers to a non-volatile
3459 // object whose lifetime began within the evaluation of e.
3460 //
3461 // C++11 misses the 'began within the evaluation of e' check and
3462 // instead allows all temporaries, including things like:
3463 // int &&r = 1;
3464 // int x = ++r;
3465 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003466 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003467 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3468 const ValueDecl *ED = MTE->getExtendingDecl();
3469 if (!(BaseType.isConstQualified() &&
3470 BaseType->isIntegralOrEnumerationType()) &&
3471 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003472 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003473 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Faisal Valie690b7a2016-07-02 22:34:24 +00003474 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003475 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3476 return CompleteObject();
3477 }
3478
3479 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3480 assert(BaseVal && "got reference to unevaluated temporary");
3481 } else {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003482 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003483 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smithee0ce3022019-05-17 07:06:46 +00003484 APValue Val;
3485 LVal.moveInto(Val);
3486 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3487 << AK
3488 << Val.getAsString(Info.Ctx,
3489 Info.Ctx.getLValueReferenceType(LValType));
3490 NoteLValueLocation(Info, LVal.Base);
Richard Smithe6c01442013-06-05 00:46:14 +00003491 return CompleteObject();
3492 }
3493 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003494 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003495 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003496 }
Richard Smith7525ff62013-05-09 07:14:00 +00003497 }
3498
Richard Smith9defb7d2018-02-21 03:38:30 +00003499 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003500 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003501 //
3502 // FIXME: Not all local state is mutable. Allow local constant subobjects
3503 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003504 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3505 Info.EvalStatus.HasSideEffects) ||
Richard Smithdebad642019-05-12 09:39:08 +00003506 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
Richard Smith3229b742013-05-05 21:17:10 +00003507 return CompleteObject();
3508
Richard Smithdebad642019-05-12 09:39:08 +00003509 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003510}
3511
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003512/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003513/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3514/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003515///
3516/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003517/// \param Conv - The expression for which we are performing the conversion.
3518/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003519/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3520/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003521/// \param LVal - The glvalue on which we are attempting to perform this action.
3522/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003523static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003524 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003525 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003526 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003527 return false;
3528
Richard Smith3229b742013-05-05 21:17:10 +00003529 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003530 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Eric Fiselier708afb52019-05-16 21:04:15 +00003531
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003532 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003533 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3534 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3535 // initializer until now for such expressions. Such an expression can't be
3536 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003537 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003538 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003539 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003540 }
Richard Smith3229b742013-05-05 21:17:10 +00003541 APValue Lit;
3542 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3543 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003544 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
Richard Smith3229b742013-05-05 21:17:10 +00003545 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003546 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00003547 // Special-case character extraction so we don't have to construct an
3548 // APValue for the whole string.
Eli Friedman041adb02019-02-09 02:22:17 +00003549 assert(LVal.Designator.Entries.size() <= 1 &&
Eli Friedman3bf72d72019-02-08 21:18:46 +00003550 "Can only read characters from string literals");
Eli Friedman041adb02019-02-09 02:22:17 +00003551 if (LVal.Designator.Entries.empty()) {
3552 // Fail for now for LValue to RValue conversion of an array.
3553 // (This shouldn't show up in C/C++, but it could be triggered by a
3554 // weird EvaluateAsRValue call from a tool.)
3555 Info.FFDiag(Conv);
3556 return false;
3557 }
Eli Friedman3bf72d72019-02-08 21:18:46 +00003558 if (LVal.Designator.isOnePastTheEnd()) {
3559 if (Info.getLangOpts().CPlusPlus11)
3560 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3561 else
3562 Info.FFDiag(Conv);
3563 return false;
3564 }
Richard Smith5b5e27a2019-05-10 20:05:31 +00003565 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
Eli Friedman3bf72d72019-02-08 21:18:46 +00003566 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3567 return true;
Richard Smith96e0c102011-11-04 02:25:55 +00003568 }
Richard Smith11562c52011-10-28 17:51:58 +00003569 }
3570
Richard Smith3229b742013-05-05 21:17:10 +00003571 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3572 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003573}
3574
3575/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003576static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003577 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003578 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003579 return false;
3580
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003581 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003582 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003583 return false;
3584 }
3585
Richard Smith3229b742013-05-05 21:17:10 +00003586 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003587 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3588}
3589
3590namespace {
3591struct CompoundAssignSubobjectHandler {
3592 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003593 const Expr *E;
3594 QualType PromotedLHSType;
3595 BinaryOperatorKind Opcode;
3596 const APValue &RHS;
3597
3598 static const AccessKinds AccessKind = AK_Assign;
3599
3600 typedef bool result_type;
3601
3602 bool checkConst(QualType QT) {
3603 // Assigning to a const object has undefined behavior.
3604 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003605 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003606 return false;
3607 }
3608 return true;
3609 }
3610
3611 bool failed() { return false; }
3612 bool found(APValue &Subobj, QualType SubobjType) {
3613 switch (Subobj.getKind()) {
3614 case APValue::Int:
3615 return found(Subobj.getInt(), SubobjType);
3616 case APValue::Float:
3617 return found(Subobj.getFloat(), SubobjType);
3618 case APValue::ComplexInt:
3619 case APValue::ComplexFloat:
3620 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003621 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003622 return false;
3623 case APValue::LValue:
3624 return foundPointer(Subobj, SubobjType);
3625 default:
3626 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003627 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003628 return false;
3629 }
3630 }
3631 bool found(APSInt &Value, QualType SubobjType) {
3632 if (!checkConst(SubobjType))
3633 return false;
3634
Tan S. B.9f935e82018-12-18 07:38:06 +00003635 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003636 // We don't support compound assignment on integer-cast-to-pointer
3637 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003638 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003639 return false;
3640 }
3641
Tan S. B.9f935e82018-12-18 07:38:06 +00003642 if (RHS.isInt()) {
3643 APSInt LHS =
3644 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3645 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3646 return false;
3647 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3648 return true;
3649 } else if (RHS.isFloat()) {
3650 APFloat FValue(0.0);
3651 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3652 FValue) &&
3653 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3654 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3655 Value);
3656 }
3657
3658 Info.FFDiag(E);
3659 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003660 }
3661 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003662 return checkConst(SubobjType) &&
3663 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3664 Value) &&
3665 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3666 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003667 }
3668 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3669 if (!checkConst(SubobjType))
3670 return false;
3671
3672 QualType PointeeType;
3673 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3674 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003675
3676 if (PointeeType.isNull() || !RHS.isInt() ||
3677 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003678 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003679 return false;
3680 }
3681
Richard Smithd6cc1982017-01-31 02:23:02 +00003682 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003683 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003684 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003685
3686 LValue LVal;
3687 LVal.setFrom(Info.Ctx, Subobj);
3688 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3689 return false;
3690 LVal.moveInto(Subobj);
3691 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003692 }
Richard Smith43e77732013-05-07 04:50:00 +00003693};
3694} // end anonymous namespace
3695
3696const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3697
3698/// Perform a compound assignment of LVal <op>= RVal.
3699static bool handleCompoundAssignment(
3700 EvalInfo &Info, const Expr *E,
3701 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3702 BinaryOperatorKind Opcode, const APValue &RVal) {
3703 if (LVal.Designator.Invalid)
3704 return false;
3705
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003706 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003707 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003708 return false;
3709 }
3710
3711 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3712 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3713 RVal };
3714 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3715}
3716
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003717namespace {
3718struct IncDecSubobjectHandler {
3719 EvalInfo &Info;
3720 const UnaryOperator *E;
3721 AccessKinds AccessKind;
3722 APValue *Old;
3723
Richard Smith243ef902013-05-05 23:31:59 +00003724 typedef bool result_type;
3725
3726 bool checkConst(QualType QT) {
3727 // Assigning to a const object has undefined behavior.
3728 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003729 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003730 return false;
3731 }
3732 return true;
3733 }
3734
3735 bool failed() { return false; }
3736 bool found(APValue &Subobj, QualType SubobjType) {
3737 // Stash the old value. Also clear Old, so we don't clobber it later
3738 // if we're post-incrementing a complex.
3739 if (Old) {
3740 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003741 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003742 }
3743
3744 switch (Subobj.getKind()) {
3745 case APValue::Int:
3746 return found(Subobj.getInt(), SubobjType);
3747 case APValue::Float:
3748 return found(Subobj.getFloat(), SubobjType);
3749 case APValue::ComplexInt:
3750 return found(Subobj.getComplexIntReal(),
3751 SubobjType->castAs<ComplexType>()->getElementType()
3752 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3753 case APValue::ComplexFloat:
3754 return found(Subobj.getComplexFloatReal(),
3755 SubobjType->castAs<ComplexType>()->getElementType()
3756 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3757 case APValue::LValue:
3758 return foundPointer(Subobj, SubobjType);
3759 default:
3760 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003761 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003762 return false;
3763 }
3764 }
3765 bool found(APSInt &Value, QualType SubobjType) {
3766 if (!checkConst(SubobjType))
3767 return false;
3768
3769 if (!SubobjType->isIntegerType()) {
3770 // We don't support increment / decrement on integer-cast-to-pointer
3771 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003772 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003773 return false;
3774 }
3775
3776 if (Old) *Old = APValue(Value);
3777
3778 // bool arithmetic promotes to int, and the conversion back to bool
3779 // doesn't reduce mod 2^n, so special-case it.
3780 if (SubobjType->isBooleanType()) {
3781 if (AccessKind == AK_Increment)
3782 Value = 1;
3783 else
3784 Value = !Value;
3785 return true;
3786 }
3787
3788 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003789 if (AccessKind == AK_Increment) {
3790 ++Value;
3791
3792 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3793 APSInt ActualValue(Value, /*IsUnsigned*/true);
3794 return HandleOverflow(Info, E, ActualValue, SubobjType);
3795 }
3796 } else {
3797 --Value;
3798
3799 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3800 unsigned BitWidth = Value.getBitWidth();
3801 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3802 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003803 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003804 }
3805 }
3806 return true;
3807 }
3808 bool found(APFloat &Value, QualType SubobjType) {
3809 if (!checkConst(SubobjType))
3810 return false;
3811
3812 if (Old) *Old = APValue(Value);
3813
3814 APFloat One(Value.getSemantics(), 1);
3815 if (AccessKind == AK_Increment)
3816 Value.add(One, APFloat::rmNearestTiesToEven);
3817 else
3818 Value.subtract(One, APFloat::rmNearestTiesToEven);
3819 return true;
3820 }
3821 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3822 if (!checkConst(SubobjType))
3823 return false;
3824
3825 QualType PointeeType;
3826 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3827 PointeeType = PT->getPointeeType();
3828 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003829 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003830 return false;
3831 }
3832
3833 LValue LVal;
3834 LVal.setFrom(Info.Ctx, Subobj);
3835 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3836 AccessKind == AK_Increment ? 1 : -1))
3837 return false;
3838 LVal.moveInto(Subobj);
3839 return true;
3840 }
Richard Smith243ef902013-05-05 23:31:59 +00003841};
3842} // end anonymous namespace
3843
3844/// Perform an increment or decrement on LVal.
3845static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3846 QualType LValType, bool IsIncrement, APValue *Old) {
3847 if (LVal.Designator.Invalid)
3848 return false;
3849
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003850 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003851 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003852 return false;
3853 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003854
3855 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3856 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3857 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3858 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3859}
3860
Richard Smithe97cbd72011-11-11 04:05:33 +00003861/// Build an lvalue for the object argument of a member function call.
3862static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3863 LValue &This) {
3864 if (Object->getType()->isPointerType())
3865 return EvaluatePointer(Object, This, Info);
3866
3867 if (Object->isGLValue())
3868 return EvaluateLValue(Object, This, Info);
3869
Richard Smithd9f663b2013-04-22 15:31:51 +00003870 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003871 return EvaluateTemporary(Object, This, Info);
3872
Faisal Valie690b7a2016-07-02 22:34:24 +00003873 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003874 return false;
3875}
3876
3877/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3878/// lvalue referring to the result.
3879///
3880/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003881/// \param LV - An lvalue referring to the base of the member pointer.
3882/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003883/// \param IncludeMember - Specifies whether the member itself is included in
3884/// the resulting LValue subobject designator. This is not possible when
3885/// creating a bound member function.
3886/// \return The field or method declaration to which the member pointer refers,
3887/// or 0 if evaluation fails.
3888static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003889 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003890 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003891 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003892 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003893 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003894 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003895 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003896
3897 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3898 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003899 if (!MemPtr.getDecl()) {
3900 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003901 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003902 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003903 }
Richard Smith253c2a32012-01-27 01:14:48 +00003904
Richard Smith027bf112011-11-17 22:56:20 +00003905 if (MemPtr.isDerivedMember()) {
3906 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003907 // The end of the derived-to-base path for the base object must match the
3908 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003909 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003910 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003911 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003912 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003913 }
Richard Smith027bf112011-11-17 22:56:20 +00003914 unsigned PathLengthToMember =
3915 LV.Designator.Entries.size() - MemPtr.Path.size();
3916 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3917 const CXXRecordDecl *LVDecl = getAsBaseClass(
3918 LV.Designator.Entries[PathLengthToMember + I]);
3919 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003920 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003921 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003922 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003923 }
Richard Smith027bf112011-11-17 22:56:20 +00003924 }
3925
3926 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003927 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003928 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003929 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003930 } else if (!MemPtr.Path.empty()) {
3931 // Extend the LValue path with the member pointer's path.
3932 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3933 MemPtr.Path.size() + IncludeMember);
3934
3935 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003936 if (const PointerType *PT = LVType->getAs<PointerType>())
3937 LVType = PT->getPointeeType();
3938 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3939 assert(RD && "member pointer access on non-class-type expression");
3940 // The first class in the path is that of the lvalue.
3941 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3942 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003943 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003944 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003945 RD = Base;
3946 }
3947 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003948 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3949 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003950 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003951 }
3952
3953 // Add the member. Note that we cannot build bound member functions here.
3954 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003955 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003956 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003957 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003958 } else if (const IndirectFieldDecl *IFD =
3959 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003960 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003961 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003962 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003963 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003964 }
Richard Smith027bf112011-11-17 22:56:20 +00003965 }
3966
3967 return MemPtr.getDecl();
3968}
3969
Richard Smith84401042013-06-03 05:03:02 +00003970static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3971 const BinaryOperator *BO,
3972 LValue &LV,
3973 bool IncludeMember = true) {
3974 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3975
3976 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003977 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003978 MemberPtr MemPtr;
3979 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3980 }
Craig Topper36250ad2014-05-12 05:36:57 +00003981 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003982 }
3983
3984 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3985 BO->getRHS(), IncludeMember);
3986}
3987
Richard Smith027bf112011-11-17 22:56:20 +00003988/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3989/// the provided lvalue, which currently refers to the base object.
3990static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3991 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003992 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003993 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003994 return false;
3995
Richard Smitha8105bc2012-01-06 16:39:00 +00003996 QualType TargetQT = E->getType();
3997 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3998 TargetQT = PT->getPointeeType();
3999
4000 // Check this cast lands within the final derived-to-base subobject path.
4001 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004002 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004003 << D.MostDerivedType << TargetQT;
4004 return false;
4005 }
4006
Richard Smith027bf112011-11-17 22:56:20 +00004007 // Check the type of the final cast. We don't need to check the path,
4008 // since a cast can only be formed if the path is unique.
4009 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00004010 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4011 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00004012 if (NewEntriesSize == D.MostDerivedPathLength)
4013 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4014 else
Richard Smith027bf112011-11-17 22:56:20 +00004015 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00004016 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004017 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004018 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00004019 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004020 }
Richard Smith027bf112011-11-17 22:56:20 +00004021
4022 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00004023 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00004024}
4025
Mike Stump876387b2009-10-27 22:09:17 +00004026namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00004027enum EvalStmtResult {
4028 /// Evaluation failed.
4029 ESR_Failed,
4030 /// Hit a 'return' statement.
4031 ESR_Returned,
4032 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00004033 ESR_Succeeded,
4034 /// Hit a 'continue' statement.
4035 ESR_Continue,
4036 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00004037 ESR_Break,
4038 /// Still scanning for 'case' or 'default' statement.
4039 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00004040};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004041}
Richard Smith254a73d2011-10-28 22:34:42 +00004042
Richard Smith97fcf4b2016-08-14 23:15:52 +00004043static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4044 // We don't need to evaluate the initializer for a static local.
4045 if (!VD->hasLocalStorage())
4046 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00004047
Richard Smith97fcf4b2016-08-14 23:15:52 +00004048 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004049 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00004050
Richard Smith97fcf4b2016-08-14 23:15:52 +00004051 const Expr *InitE = VD->getInit();
4052 if (!InitE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004053 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
4054 << false << VD->getType();
Richard Smith97fcf4b2016-08-14 23:15:52 +00004055 Val = APValue();
4056 return false;
4057 }
Richard Smith51f03172013-06-20 03:00:05 +00004058
Richard Smith97fcf4b2016-08-14 23:15:52 +00004059 if (InitE->isValueDependent())
4060 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00004061
Richard Smith97fcf4b2016-08-14 23:15:52 +00004062 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4063 // Wipe out any partially-computed value, to allow tracking that this
4064 // evaluation failed.
4065 Val = APValue();
4066 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00004067 }
4068
4069 return true;
4070}
4071
Richard Smith97fcf4b2016-08-14 23:15:52 +00004072static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4073 bool OK = true;
4074
4075 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4076 OK &= EvaluateVarDecl(Info, VD);
4077
4078 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4079 for (auto *BD : DD->bindings())
4080 if (auto *VD = BD->getHoldingVar())
4081 OK &= EvaluateDecl(Info, VD);
4082
4083 return OK;
4084}
4085
4086
Richard Smith4e18ca52013-05-06 05:56:11 +00004087/// Evaluate a condition (either a variable declaration or an expression).
4088static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4089 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004090 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004091 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4092 return false;
4093 return EvaluateAsBooleanCondition(Cond, Result, Info);
4094}
4095
Richard Smith89210072016-04-04 23:29:43 +00004096namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004097/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00004098/// statement should be stored.
4099struct StmtResult {
4100 /// The APValue that should be filled in with the returned value.
4101 APValue &Value;
4102 /// The location containing the result, if any (used to support RVO).
4103 const LValue *Slot;
4104};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004105
4106struct TempVersionRAII {
4107 CallStackFrame &Frame;
4108
4109 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4110 Frame.pushTempVersion();
4111 }
4112
4113 ~TempVersionRAII() {
4114 Frame.popTempVersion();
4115 }
4116};
4117
Richard Smith89210072016-04-04 23:29:43 +00004118}
Richard Smith52a980a2015-08-28 02:43:42 +00004119
4120static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00004121 const Stmt *S,
4122 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00004123
4124/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00004125static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004126 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00004127 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004128 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00004129 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00004130 case ESR_Break:
4131 return ESR_Succeeded;
4132 case ESR_Succeeded:
4133 case ESR_Continue:
4134 return ESR_Continue;
4135 case ESR_Failed:
4136 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00004137 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00004138 return ESR;
4139 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00004140 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00004141}
4142
Richard Smith496ddcf2013-05-12 17:32:42 +00004143/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004144static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004145 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004146 BlockScopeRAII Scope(Info);
4147
Richard Smith496ddcf2013-05-12 17:32:42 +00004148 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00004149 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004150 {
4151 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004152 if (const Stmt *Init = SS->getInit()) {
4153 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4154 if (ESR != ESR_Succeeded)
4155 return ESR;
4156 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004157 if (SS->getConditionVariable() &&
4158 !EvaluateDecl(Info, SS->getConditionVariable()))
4159 return ESR_Failed;
4160 if (!EvaluateInteger(SS->getCond(), Value, Info))
4161 return ESR_Failed;
4162 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004163
4164 // Find the switch case corresponding to the value of the condition.
4165 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00004166 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004167 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4168 SC = SC->getNextSwitchCase()) {
4169 if (isa<DefaultStmt>(SC)) {
4170 Found = SC;
4171 continue;
4172 }
4173
4174 const CaseStmt *CS = cast<CaseStmt>(SC);
4175 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4176 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4177 : LHS;
4178 if (LHS <= Value && Value <= RHS) {
4179 Found = SC;
4180 break;
4181 }
4182 }
4183
4184 if (!Found)
4185 return ESR_Succeeded;
4186
4187 // Search the switch body for the switch case and evaluate it from there.
4188 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4189 case ESR_Break:
4190 return ESR_Succeeded;
4191 case ESR_Succeeded:
4192 case ESR_Continue:
4193 case ESR_Failed:
4194 case ESR_Returned:
4195 return ESR;
4196 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004197 // This can only happen if the switch case is nested within a statement
4198 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004199 Info.FFDiag(Found->getBeginLoc(),
4200 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004201 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004202 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004203 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004204}
4205
Richard Smith254a73d2011-10-28 22:34:42 +00004206// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004207static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004208 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004209 if (!Info.nextStep(S))
4210 return ESR_Failed;
4211
Richard Smith496ddcf2013-05-12 17:32:42 +00004212 // If we're hunting down a 'case' or 'default' label, recurse through
4213 // substatements until we hit the label.
4214 if (Case) {
4215 // FIXME: We don't start the lifetime of objects whose initialization we
4216 // jump over. However, such objects must be of class type with a trivial
4217 // default constructor that initialize all subobjects, so must be empty,
4218 // so this almost never matters.
4219 switch (S->getStmtClass()) {
4220 case Stmt::CompoundStmtClass:
4221 // FIXME: Precompute which substatement of a compound statement we
4222 // would jump to, and go straight there rather than performing a
4223 // linear scan each time.
4224 case Stmt::LabelStmtClass:
4225 case Stmt::AttributedStmtClass:
4226 case Stmt::DoStmtClass:
4227 break;
4228
4229 case Stmt::CaseStmtClass:
4230 case Stmt::DefaultStmtClass:
4231 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004232 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004233 break;
4234
4235 case Stmt::IfStmtClass: {
4236 // FIXME: Precompute which side of an 'if' we would jump to, and go
4237 // straight there rather than scanning both sides.
4238 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004239
4240 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4241 // preceded by our switch label.
4242 BlockScopeRAII Scope(Info);
4243
Richard Smith496ddcf2013-05-12 17:32:42 +00004244 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4245 if (ESR != ESR_CaseNotFound || !IS->getElse())
4246 return ESR;
4247 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4248 }
4249
4250 case Stmt::WhileStmtClass: {
4251 EvalStmtResult ESR =
4252 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4253 if (ESR != ESR_Continue)
4254 return ESR;
4255 break;
4256 }
4257
4258 case Stmt::ForStmtClass: {
4259 const ForStmt *FS = cast<ForStmt>(S);
4260 EvalStmtResult ESR =
4261 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4262 if (ESR != ESR_Continue)
4263 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004264 if (FS->getInc()) {
4265 FullExpressionRAII IncScope(Info);
4266 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4267 return ESR_Failed;
4268 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004269 break;
4270 }
4271
4272 case Stmt::DeclStmtClass:
4273 // FIXME: If the variable has initialization that can't be jumped over,
4274 // bail out of any immediately-surrounding compound-statement too.
4275 default:
4276 return ESR_CaseNotFound;
4277 }
4278 }
4279
Richard Smith254a73d2011-10-28 22:34:42 +00004280 switch (S->getStmtClass()) {
4281 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004282 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004283 // Don't bother evaluating beyond an expression-statement which couldn't
4284 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004285 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004286 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004287 return ESR_Failed;
4288 return ESR_Succeeded;
4289 }
4290
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004291 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004292 return ESR_Failed;
4293
4294 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004295 return ESR_Succeeded;
4296
Richard Smithd9f663b2013-04-22 15:31:51 +00004297 case Stmt::DeclStmtClass: {
4298 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004299 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004300 // Each declaration initialization is its own full-expression.
4301 // FIXME: This isn't quite right; if we're performing aggregate
4302 // initialization, each braced subexpression is its own full-expression.
4303 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004304 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004305 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004306 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004307 return ESR_Succeeded;
4308 }
4309
Richard Smith357362d2011-12-13 06:39:58 +00004310 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004311 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004312 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004313 if (RetExpr &&
4314 !(Result.Slot
4315 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4316 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004317 return ESR_Failed;
4318 return ESR_Returned;
4319 }
Richard Smith254a73d2011-10-28 22:34:42 +00004320
4321 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004322 BlockScopeRAII Scope(Info);
4323
Richard Smith254a73d2011-10-28 22:34:42 +00004324 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004325 for (const auto *BI : CS->body()) {
4326 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004327 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004328 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004329 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004330 return ESR;
4331 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004332 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004333 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004334
4335 case Stmt::IfStmtClass: {
4336 const IfStmt *IS = cast<IfStmt>(S);
4337
4338 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004339 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004340 if (const Stmt *Init = IS->getInit()) {
4341 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4342 if (ESR != ESR_Succeeded)
4343 return ESR;
4344 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004345 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004346 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004347 return ESR_Failed;
4348
4349 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4350 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4351 if (ESR != ESR_Succeeded)
4352 return ESR;
4353 }
4354 return ESR_Succeeded;
4355 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004356
4357 case Stmt::WhileStmtClass: {
4358 const WhileStmt *WS = cast<WhileStmt>(S);
4359 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004360 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004361 bool Continue;
4362 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4363 Continue))
4364 return ESR_Failed;
4365 if (!Continue)
4366 break;
4367
4368 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4369 if (ESR != ESR_Continue)
4370 return ESR;
4371 }
4372 return ESR_Succeeded;
4373 }
4374
4375 case Stmt::DoStmtClass: {
4376 const DoStmt *DS = cast<DoStmt>(S);
4377 bool Continue;
4378 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004379 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004380 if (ESR != ESR_Continue)
4381 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004382 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004383
Richard Smith08d6a2c2013-07-24 07:11:57 +00004384 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004385 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4386 return ESR_Failed;
4387 } while (Continue);
4388 return ESR_Succeeded;
4389 }
4390
4391 case Stmt::ForStmtClass: {
4392 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004393 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004394 if (FS->getInit()) {
4395 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4396 if (ESR != ESR_Succeeded)
4397 return ESR;
4398 }
4399 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004400 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004401 bool Continue = true;
4402 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4403 FS->getCond(), Continue))
4404 return ESR_Failed;
4405 if (!Continue)
4406 break;
4407
4408 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4409 if (ESR != ESR_Continue)
4410 return ESR;
4411
Richard Smith08d6a2c2013-07-24 07:11:57 +00004412 if (FS->getInc()) {
4413 FullExpressionRAII IncScope(Info);
4414 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4415 return ESR_Failed;
4416 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004417 }
4418 return ESR_Succeeded;
4419 }
4420
Richard Smith896e0d72013-05-06 06:51:17 +00004421 case Stmt::CXXForRangeStmtClass: {
4422 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004423 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004424
Richard Smith8baa5002018-09-28 18:44:09 +00004425 // Evaluate the init-statement if present.
4426 if (FS->getInit()) {
4427 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4428 if (ESR != ESR_Succeeded)
4429 return ESR;
4430 }
4431
Richard Smith896e0d72013-05-06 06:51:17 +00004432 // Initialize the __range variable.
4433 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4434 if (ESR != ESR_Succeeded)
4435 return ESR;
4436
4437 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004438 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4439 if (ESR != ESR_Succeeded)
4440 return ESR;
4441 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004442 if (ESR != ESR_Succeeded)
4443 return ESR;
4444
4445 while (true) {
4446 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004447 {
4448 bool Continue = true;
4449 FullExpressionRAII CondExpr(Info);
4450 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4451 return ESR_Failed;
4452 if (!Continue)
4453 break;
4454 }
Richard Smith896e0d72013-05-06 06:51:17 +00004455
4456 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004457 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004458 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4459 if (ESR != ESR_Succeeded)
4460 return ESR;
4461
4462 // Loop body.
4463 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4464 if (ESR != ESR_Continue)
4465 return ESR;
4466
4467 // Increment: ++__begin
4468 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4469 return ESR_Failed;
4470 }
4471
4472 return ESR_Succeeded;
4473 }
4474
Richard Smith496ddcf2013-05-12 17:32:42 +00004475 case Stmt::SwitchStmtClass:
4476 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4477
Richard Smith4e18ca52013-05-06 05:56:11 +00004478 case Stmt::ContinueStmtClass:
4479 return ESR_Continue;
4480
4481 case Stmt::BreakStmtClass:
4482 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004483
4484 case Stmt::LabelStmtClass:
4485 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4486
4487 case Stmt::AttributedStmtClass:
4488 // As a general principle, C++11 attributes can be ignored without
4489 // any semantic impact.
4490 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4491 Case);
4492
4493 case Stmt::CaseStmtClass:
4494 case Stmt::DefaultStmtClass:
4495 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004496 case Stmt::CXXTryStmtClass:
4497 // Evaluate try blocks by evaluating all sub statements.
4498 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004499 }
4500}
4501
Richard Smithcc36f692011-12-22 02:22:31 +00004502/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4503/// default constructor. If so, we'll fold it whether or not it's marked as
4504/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4505/// so we need special handling.
4506static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004507 const CXXConstructorDecl *CD,
4508 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004509 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4510 return false;
4511
Richard Smith66e05fe2012-01-18 05:21:49 +00004512 // Value-initialization does not call a trivial default constructor, so such a
4513 // call is a core constant expression whether or not the constructor is
4514 // constexpr.
4515 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004516 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004517 // FIXME: If DiagDecl is an implicitly-declared special member function,
4518 // we should be much more explicit about why it's not constexpr.
4519 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4520 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4521 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004522 } else {
4523 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4524 }
4525 }
4526 return true;
4527}
4528
Richard Smith357362d2011-12-13 06:39:58 +00004529/// CheckConstexprFunction - Check that a function can be called in a constant
4530/// expression.
4531static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4532 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004533 const FunctionDecl *Definition,
4534 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004535 // Potential constant expressions can contain calls to declared, but not yet
4536 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004537 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004538 Declaration->isConstexpr())
4539 return false;
4540
James Y Knightc7d3e602018-10-05 17:49:48 +00004541 // Bail out if the function declaration itself is invalid. We will
4542 // have produced a relevant diagnostic while parsing it, so just
4543 // note the problematic sub-expression.
4544 if (Declaration->isInvalidDecl()) {
4545 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004546 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004547 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004548
Richard Smithd9c6b032019-05-09 19:45:49 +00004549 // DR1872: An instantiated virtual constexpr function can't be called in a
Richard Smith921f1322019-05-13 23:35:21 +00004550 // constant expression (prior to C++20). We can still constant-fold such a
4551 // call.
4552 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4553 cast<CXXMethodDecl>(Declaration)->isVirtual())
4554 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4555
4556 if (Definition && Definition->isInvalidDecl()) {
4557 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd9c6b032019-05-09 19:45:49 +00004558 return false;
4559 }
4560
Richard Smith357362d2011-12-13 06:39:58 +00004561 // Can we evaluate this function call?
Richard Smith921f1322019-05-13 23:35:21 +00004562 if (Definition && Definition->isConstexpr() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004563 return true;
4564
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004565 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004566 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004567
Richard Smith5179eb72016-06-28 19:03:57 +00004568 // If this function is not constexpr because it is an inherited
4569 // non-constexpr constructor, diagnose that directly.
4570 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4571 if (CD && CD->isInheritingConstructor()) {
4572 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004573 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004574 DiagDecl = CD = Inherited;
4575 }
4576
4577 // FIXME: If DiagDecl is an implicitly-declared special member function
4578 // or an inheriting constructor, we should be much more explicit about why
4579 // it's not constexpr.
4580 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004581 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004582 << CD->getInheritedConstructor().getConstructor()->getParent();
4583 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004584 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004585 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004586 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4587 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004588 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004589 }
4590 return false;
4591}
4592
Richard Smithdebad642019-05-12 09:39:08 +00004593namespace {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004594struct CheckDynamicTypeHandler {
4595 AccessKinds AccessKind;
Richard Smithdebad642019-05-12 09:39:08 +00004596 typedef bool result_type;
4597 bool failed() { return false; }
4598 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4599 bool found(APSInt &Value, QualType SubobjType) { return true; }
4600 bool found(APFloat &Value, QualType SubobjType) { return true; }
4601};
4602} // end anonymous namespace
4603
Richard Smith7bd54ab2019-05-15 20:22:21 +00004604/// Check that we can access the notional vptr of an object / determine its
4605/// dynamic type.
4606static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4607 AccessKinds AK, bool Polymorphic) {
Richard Smithdab287b2019-05-13 07:51:29 +00004608 if (This.Designator.Invalid)
4609 return false;
4610
Richard Smith7bd54ab2019-05-15 20:22:21 +00004611 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
Richard Smithdebad642019-05-12 09:39:08 +00004612
4613 if (!Obj)
4614 return false;
4615
4616 if (!Obj.Value) {
4617 // The object is not usable in constant expressions, so we can't inspect
4618 // its value to see if it's in-lifetime or what the active union members
4619 // are. We can still check for a one-past-the-end lvalue.
4620 if (This.Designator.isOnePastTheEnd() ||
4621 This.Designator.isMostDerivedAnUnsizedArray()) {
4622 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4623 ? diag::note_constexpr_access_past_end
4624 : diag::note_constexpr_access_unsized_array)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004625 << AK;
Richard Smithdebad642019-05-12 09:39:08 +00004626 return false;
Richard Smith7bd54ab2019-05-15 20:22:21 +00004627 } else if (Polymorphic) {
4628 // Conservatively refuse to perform a polymorphic operation if we would
Richard Smith921f1322019-05-13 23:35:21 +00004629 // not be able to read a notional 'vptr' value.
4630 APValue Val;
4631 This.moveInto(Val);
4632 QualType StarThisType =
4633 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
Richard Smith7bd54ab2019-05-15 20:22:21 +00004634 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4635 << AK << Val.getAsString(Info.Ctx, StarThisType);
Richard Smith921f1322019-05-13 23:35:21 +00004636 return false;
Richard Smithdebad642019-05-12 09:39:08 +00004637 }
4638 return true;
4639 }
4640
Richard Smith7bd54ab2019-05-15 20:22:21 +00004641 CheckDynamicTypeHandler Handler{AK};
Richard Smithdebad642019-05-12 09:39:08 +00004642 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4643}
4644
Richard Smith7bd54ab2019-05-15 20:22:21 +00004645/// Check that the pointee of the 'this' pointer in a member function call is
4646/// either within its lifetime or in its period of construction or destruction.
4647static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4648 const LValue &This) {
4649 return checkDynamicType(Info, E, This, AK_MemberCall, false);
4650}
4651
Richard Smith921f1322019-05-13 23:35:21 +00004652struct DynamicType {
4653 /// The dynamic class type of the object.
4654 const CXXRecordDecl *Type;
4655 /// The corresponding path length in the lvalue.
4656 unsigned PathLength;
4657};
4658
4659static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4660 unsigned PathLength) {
4661 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4662 Designator.Entries.size() && "invalid path length");
4663 return (PathLength == Designator.MostDerivedPathLength)
4664 ? Designator.MostDerivedType->getAsCXXRecordDecl()
4665 : getAsBaseClass(Designator.Entries[PathLength - 1]);
4666}
4667
4668/// Determine the dynamic type of an object.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004669static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4670 LValue &This, AccessKinds AK) {
Richard Smith921f1322019-05-13 23:35:21 +00004671 // If we don't have an lvalue denoting an object of class type, there is no
4672 // meaningful dynamic type. (We consider objects of non-class type to have no
4673 // dynamic type.)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004674 if (!checkDynamicType(Info, E, This, AK, true))
Richard Smith921f1322019-05-13 23:35:21 +00004675 return None;
4676
Richard Smith7bd54ab2019-05-15 20:22:21 +00004677 // Refuse to compute a dynamic type in the presence of virtual bases. This
4678 // shouldn't happen other than in constant-folding situations, since literal
4679 // types can't have virtual bases.
4680 //
4681 // Note that consumers of DynamicType assume that the type has no virtual
4682 // bases, and will need modifications if this restriction is relaxed.
4683 const CXXRecordDecl *Class =
4684 This.Designator.MostDerivedType->getAsCXXRecordDecl();
4685 if (!Class || Class->getNumVBases()) {
4686 Info.FFDiag(E);
4687 return None;
4688 }
4689
Richard Smith921f1322019-05-13 23:35:21 +00004690 // FIXME: For very deep class hierarchies, it might be beneficial to use a
4691 // binary search here instead. But the overwhelmingly common case is that
4692 // we're not in the middle of a constructor, so it probably doesn't matter
4693 // in practice.
4694 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4695 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4696 PathLength <= Path.size(); ++PathLength) {
4697 switch (Info.isEvaluatingConstructor(This.getLValueBase(),
4698 Path.slice(0, PathLength))) {
4699 case ConstructionPhase::Bases:
4700 // We're constructing a base class. This is not the dynamic type.
4701 break;
4702
4703 case ConstructionPhase::None:
4704 case ConstructionPhase::AfterBases:
4705 // We've finished constructing the base classes, so this is the dynamic
4706 // type.
4707 return DynamicType{getBaseClassType(This.Designator, PathLength),
4708 PathLength};
4709 }
4710 }
4711
4712 // CWG issue 1517: we're constructing a base class of the object described by
4713 // 'This', so that object has not yet begun its period of construction and
4714 // any polymorphic operation on it results in undefined behavior.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004715 Info.FFDiag(E);
Richard Smith921f1322019-05-13 23:35:21 +00004716 return None;
4717}
4718
4719/// Perform virtual dispatch.
4720static const CXXMethodDecl *HandleVirtualDispatch(
4721 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4722 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004723 Optional<DynamicType> DynType =
4724 ComputeDynamicType(Info, E, This, AK_MemberCall);
4725 if (!DynType)
Richard Smith921f1322019-05-13 23:35:21 +00004726 return nullptr;
Richard Smith921f1322019-05-13 23:35:21 +00004727
4728 // Find the final overrider. It must be declared in one of the classes on the
4729 // path from the dynamic type to the static type.
4730 // FIXME: If we ever allow literal types to have virtual base classes, that
4731 // won't be true.
4732 const CXXMethodDecl *Callee = Found;
4733 unsigned PathLength = DynType->PathLength;
4734 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4735 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
Richard Smith921f1322019-05-13 23:35:21 +00004736 const CXXMethodDecl *Overrider =
4737 Found->getCorrespondingMethodDeclaredInClass(Class, false);
4738 if (Overrider) {
4739 Callee = Overrider;
4740 break;
4741 }
4742 }
4743
4744 // C++2a [class.abstract]p6:
4745 // the effect of making a virtual call to a pure virtual function [...] is
4746 // undefined
4747 if (Callee->isPure()) {
4748 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4749 Info.Note(Callee->getLocation(), diag::note_declared_at);
4750 return nullptr;
4751 }
4752
4753 // If necessary, walk the rest of the path to determine the sequence of
4754 // covariant adjustment steps to apply.
4755 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4756 Found->getReturnType())) {
4757 CovariantAdjustmentPath.push_back(Callee->getReturnType());
4758 for (unsigned CovariantPathLength = PathLength + 1;
4759 CovariantPathLength != This.Designator.Entries.size();
4760 ++CovariantPathLength) {
4761 const CXXRecordDecl *NextClass =
4762 getBaseClassType(This.Designator, CovariantPathLength);
4763 const CXXMethodDecl *Next =
4764 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4765 if (Next && !Info.Ctx.hasSameUnqualifiedType(
4766 Next->getReturnType(), CovariantAdjustmentPath.back()))
4767 CovariantAdjustmentPath.push_back(Next->getReturnType());
4768 }
4769 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4770 CovariantAdjustmentPath.back()))
4771 CovariantAdjustmentPath.push_back(Found->getReturnType());
4772 }
4773
4774 // Perform 'this' adjustment.
4775 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4776 return nullptr;
4777
4778 return Callee;
4779}
4780
4781/// Perform the adjustment from a value returned by a virtual function to
4782/// a value of the statically expected type, which may be a pointer or
4783/// reference to a base class of the returned type.
4784static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4785 APValue &Result,
4786 ArrayRef<QualType> Path) {
4787 assert(Result.isLValue() &&
4788 "unexpected kind of APValue for covariant return");
4789 if (Result.isNullPointer())
4790 return true;
4791
4792 LValue LVal;
4793 LVal.setFrom(Info.Ctx, Result);
4794
4795 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4796 for (unsigned I = 1; I != Path.size(); ++I) {
4797 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4798 assert(OldClass && NewClass && "unexpected kind of covariant return");
4799 if (OldClass != NewClass &&
4800 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4801 return false;
4802 OldClass = NewClass;
4803 }
4804
4805 LVal.moveInto(Result);
4806 return true;
4807}
4808
Richard Smith7bd54ab2019-05-15 20:22:21 +00004809/// Determine whether \p Base, which is known to be a direct base class of
4810/// \p Derived, is a public base class.
4811static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4812 const CXXRecordDecl *Base) {
4813 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4814 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4815 if (BaseClass && declaresSameEntity(BaseClass, Base))
4816 return BaseSpec.getAccessSpecifier() == AS_public;
4817 }
4818 llvm_unreachable("Base is not a direct base of Derived");
4819}
4820
4821/// Apply the given dynamic cast operation on the provided lvalue.
4822///
4823/// This implements the hard case of dynamic_cast, requiring a "runtime check"
4824/// to find a suitable target subobject.
4825static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4826 LValue &Ptr) {
4827 // We can't do anything with a non-symbolic pointer value.
4828 SubobjectDesignator &D = Ptr.Designator;
4829 if (D.Invalid)
4830 return false;
4831
4832 // C++ [expr.dynamic.cast]p6:
4833 // If v is a null pointer value, the result is a null pointer value.
4834 if (Ptr.isNullPointer() && !E->isGLValue())
4835 return true;
4836
4837 // For all the other cases, we need the pointer to point to an object within
4838 // its lifetime / period of construction / destruction, and we need to know
4839 // its dynamic type.
4840 Optional<DynamicType> DynType =
4841 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4842 if (!DynType)
4843 return false;
4844
4845 // C++ [expr.dynamic.cast]p7:
4846 // If T is "pointer to cv void", then the result is a pointer to the most
4847 // derived object
4848 if (E->getType()->isVoidPointerType())
4849 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4850
4851 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
4852 assert(C && "dynamic_cast target is not void pointer nor class");
4853 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4854
4855 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4856 // C++ [expr.dynamic.cast]p9:
4857 if (!E->isGLValue()) {
4858 // The value of a failed cast to pointer type is the null pointer value
4859 // of the required result type.
4860 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4861 Ptr.setNull(E->getType(), TargetVal);
4862 return true;
4863 }
4864
4865 // A failed cast to reference type throws [...] std::bad_cast.
4866 unsigned DiagKind;
4867 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4868 DynType->Type->isDerivedFrom(C)))
4869 DiagKind = 0;
4870 else if (!Paths || Paths->begin() == Paths->end())
4871 DiagKind = 1;
4872 else if (Paths->isAmbiguous(CQT))
4873 DiagKind = 2;
4874 else {
4875 assert(Paths->front().Access != AS_public && "why did the cast fail?");
4876 DiagKind = 3;
4877 }
4878 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4879 << DiagKind << Ptr.Designator.getType(Info.Ctx)
4880 << Info.Ctx.getRecordType(DynType->Type)
4881 << E->getType().getUnqualifiedType();
4882 return false;
4883 };
4884
4885 // Runtime check, phase 1:
4886 // Walk from the base subobject towards the derived object looking for the
4887 // target type.
4888 for (int PathLength = Ptr.Designator.Entries.size();
4889 PathLength >= (int)DynType->PathLength; --PathLength) {
4890 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4891 if (declaresSameEntity(Class, C))
4892 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4893 // We can only walk across public inheritance edges.
4894 if (PathLength > (int)DynType->PathLength &&
4895 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4896 Class))
4897 return RuntimeCheckFailed(nullptr);
4898 }
4899
4900 // Runtime check, phase 2:
4901 // Search the dynamic type for an unambiguous public base of type C.
4902 CXXBasePaths Paths(/*FindAmbiguities=*/true,
4903 /*RecordPaths=*/true, /*DetectVirtual=*/false);
4904 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4905 Paths.front().Access == AS_public) {
4906 // Downcast to the dynamic type...
4907 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4908 return false;
4909 // ... then upcast to the chosen base class subobject.
4910 for (CXXBasePathElement &Elem : Paths.front())
4911 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4912 return false;
4913 return true;
4914 }
4915
4916 // Otherwise, the runtime check fails.
4917 return RuntimeCheckFailed(&Paths);
4918}
4919
Richard Smith31c69a32019-05-21 23:15:20 +00004920namespace {
4921struct StartLifetimeOfUnionMemberHandler {
4922 const FieldDecl *Field;
4923
4924 static const AccessKinds AccessKind = AK_Assign;
4925
4926 APValue getDefaultInitValue(QualType SubobjType) {
4927 if (auto *RD = SubobjType->getAsCXXRecordDecl()) {
4928 if (RD->isUnion())
4929 return APValue((const FieldDecl*)nullptr);
4930
4931 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4932 std::distance(RD->field_begin(), RD->field_end()));
4933
4934 unsigned Index = 0;
4935 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4936 End = RD->bases_end(); I != End; ++I, ++Index)
4937 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4938
4939 for (const auto *I : RD->fields()) {
4940 if (I->isUnnamedBitfield())
4941 continue;
4942 Struct.getStructField(I->getFieldIndex()) =
4943 getDefaultInitValue(I->getType());
4944 }
4945 return Struct;
4946 }
4947
4948 if (auto *AT = dyn_cast_or_null<ConstantArrayType>(
4949 SubobjType->getAsArrayTypeUnsafe())) {
4950 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4951 if (Array.hasArrayFiller())
4952 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4953 return Array;
4954 }
4955
4956 return APValue::IndeterminateValue();
4957 }
4958
4959 typedef bool result_type;
4960 bool failed() { return false; }
4961 bool found(APValue &Subobj, QualType SubobjType) {
4962 // We are supposed to perform no initialization but begin the lifetime of
4963 // the object. We interpret that as meaning to do what default
4964 // initialization of the object would do if all constructors involved were
4965 // trivial:
4966 // * All base, non-variant member, and array element subobjects' lifetimes
4967 // begin
4968 // * No variant members' lifetimes begin
4969 // * All scalar subobjects whose lifetimes begin have indeterminate values
4970 assert(SubobjType->isUnionType());
4971 if (!declaresSameEntity(Subobj.getUnionField(), Field))
4972 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
4973 return true;
4974 }
4975 bool found(APSInt &Value, QualType SubobjType) {
4976 llvm_unreachable("wrong value kind for union object");
4977 }
4978 bool found(APFloat &Value, QualType SubobjType) {
4979 llvm_unreachable("wrong value kind for union object");
4980 }
4981};
4982} // end anonymous namespace
4983
4984const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
4985
4986/// Handle a builtin simple-assignment or a call to a trivial assignment
4987/// operator whose left-hand side might involve a union member access. If it
4988/// does, implicitly start the lifetime of any accessed union elements per
4989/// C++20 [class.union]5.
4990static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
4991 const LValue &LHS) {
4992 if (LHS.InvalidBase || LHS.Designator.Invalid)
4993 return false;
4994
4995 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
4996 // C++ [class.union]p5:
4997 // define the set S(E) of subexpressions of E as follows:
Richard Smith31c69a32019-05-21 23:15:20 +00004998 unsigned PathLength = LHS.Designator.Entries.size();
Eric Fiselierffafdb92019-05-23 23:34:43 +00004999 for (const Expr *E = LHSExpr; E != nullptr;) {
Richard Smith31c69a32019-05-21 23:15:20 +00005000 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5001 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5002 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5003 if (!FD)
5004 break;
5005
5006 // ... and also contains A.B if B names a union member
5007 if (FD->getParent()->isUnion())
5008 UnionPathLengths.push_back({PathLength - 1, FD});
5009
5010 E = ME->getBase();
5011 --PathLength;
5012 assert(declaresSameEntity(FD,
5013 LHS.Designator.Entries[PathLength]
5014 .getAsBaseOrMember().getPointer()));
5015
5016 // -- If E is of the form A[B] and is interpreted as a built-in array
5017 // subscripting operator, S(E) is [S(the array operand, if any)].
5018 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5019 // Step over an ArrayToPointerDecay implicit cast.
5020 auto *Base = ASE->getBase()->IgnoreImplicit();
5021 if (!Base->getType()->isArrayType())
5022 break;
5023
5024 E = Base;
5025 --PathLength;
5026
5027 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5028 // Step over a derived-to-base conversion.
Eric Fiselierffafdb92019-05-23 23:34:43 +00005029 E = ICE->getSubExpr();
Richard Smith31c69a32019-05-21 23:15:20 +00005030 if (ICE->getCastKind() == CK_NoOp)
5031 continue;
5032 if (ICE->getCastKind() != CK_DerivedToBase &&
5033 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5034 break;
Richard Smitha481b012019-05-30 20:45:12 +00005035 // Walk path backwards as we walk up from the base to the derived class.
5036 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
Richard Smith31c69a32019-05-21 23:15:20 +00005037 --PathLength;
Dmitri Gribenkoa10fe832019-05-22 06:57:23 +00005038 (void)Elt;
Richard Smith31c69a32019-05-21 23:15:20 +00005039 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5040 LHS.Designator.Entries[PathLength]
5041 .getAsBaseOrMember().getPointer()));
5042 }
Richard Smith31c69a32019-05-21 23:15:20 +00005043
5044 // -- Otherwise, S(E) is empty.
5045 } else {
5046 break;
5047 }
5048 }
5049
5050 // Common case: no unions' lifetimes are started.
5051 if (UnionPathLengths.empty())
5052 return true;
5053
5054 // if modification of X [would access an inactive union member], an object
5055 // of the type of X is implicitly created
5056 CompleteObject Obj =
5057 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5058 if (!Obj)
5059 return false;
5060 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5061 llvm::reverse(UnionPathLengths)) {
5062 // Form a designator for the union object.
5063 SubobjectDesignator D = LHS.Designator;
5064 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5065
5066 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5067 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5068 return false;
5069 }
5070
5071 return true;
5072}
5073
Richard Smithbe6dd812014-11-19 21:27:17 +00005074/// Determine if a class has any fields that might need to be copied by a
5075/// trivial copy or move operation.
5076static bool hasFields(const CXXRecordDecl *RD) {
5077 if (!RD || RD->isEmpty())
5078 return false;
5079 for (auto *FD : RD->fields()) {
5080 if (FD->isUnnamedBitfield())
5081 continue;
5082 return true;
5083 }
5084 for (auto &Base : RD->bases())
5085 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5086 return true;
5087 return false;
5088}
5089
Richard Smithd62306a2011-11-10 06:34:14 +00005090namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00005091typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00005092}
5093
5094/// EvaluateArgs - Evaluate the arguments to a function call.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005095static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5096 EvalInfo &Info, const FunctionDecl *Callee) {
Richard Smith253c2a32012-01-27 01:14:48 +00005097 bool Success = true;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005098 llvm::SmallBitVector ForbiddenNullArgs;
5099 if (Callee->hasAttr<NonNullAttr>()) {
5100 ForbiddenNullArgs.resize(Args.size());
5101 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5102 if (!Attr->args_size()) {
5103 ForbiddenNullArgs.set();
5104 break;
5105 } else
5106 for (auto Idx : Attr->args()) {
5107 unsigned ASTIdx = Idx.getASTIndex();
5108 if (ASTIdx >= Args.size())
5109 continue;
5110 ForbiddenNullArgs[ASTIdx] = 1;
5111 }
5112 }
5113 }
Richard Smithd62306a2011-11-10 06:34:14 +00005114 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00005115 I != E; ++I) {
5116 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5117 // If we're checking for a potential constant expression, evaluate all
5118 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005119 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005120 return false;
5121 Success = false;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005122 } else if (!ForbiddenNullArgs.empty() &&
5123 ForbiddenNullArgs[I - Args.begin()] &&
5124 ArgValues[I - Args.begin()].isNullPointer()) {
5125 Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
5126 if (!Info.noteFailure())
5127 return false;
5128 Success = false;
Richard Smith253c2a32012-01-27 01:14:48 +00005129 }
5130 }
5131 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005132}
5133
Richard Smith254a73d2011-10-28 22:34:42 +00005134/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00005135static bool HandleFunctionCall(SourceLocation CallLoc,
5136 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005137 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00005138 EvalInfo &Info, APValue &Result,
5139 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00005140 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005141 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
Richard Smithd62306a2011-11-10 06:34:14 +00005142 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00005143
Richard Smith253c2a32012-01-27 01:14:48 +00005144 if (!Info.CheckCallLimit(CallLoc))
5145 return false;
5146
5147 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00005148
5149 // For a trivial copy or move assignment, perform an APValue copy. This is
5150 // essential for unions, where the operations performed by the assignment
5151 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00005152 //
5153 // Skip this for non-union classes with no fields; in that case, the defaulted
5154 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00005155 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00005156 if (MD && MD->isDefaulted() &&
5157 (MD->getParent()->isUnion() ||
5158 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00005159 assert(This &&
5160 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5161 LValue RHS;
5162 RHS.setFrom(Info.Ctx, ArgValues[0]);
5163 APValue RHSValue;
5164 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
5165 RHS, RHSValue))
5166 return false;
Richard Smith31c69a32019-05-21 23:15:20 +00005167 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5168 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5169 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00005170 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00005171 RHSValue))
5172 return false;
5173 This->moveInto(Result);
5174 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00005175 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00005176 // We're in a lambda; determine the lambda capture field maps unless we're
5177 // just constexpr checking a lambda's call operator. constexpr checking is
5178 // done before the captures have been added to the closure object (unless
5179 // we're inferring constexpr-ness), so we don't have access to them in this
5180 // case. But since we don't need the captures to constexpr check, we can
5181 // just ignore them.
5182 if (!Info.checkingPotentialConstantExpression())
5183 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5184 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00005185 }
5186
Richard Smith52a980a2015-08-28 02:43:42 +00005187 StmtResult Ret = {Result, ResultSlot};
5188 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00005189 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00005190 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00005191 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005192 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00005193 }
Richard Smithd9f663b2013-04-22 15:31:51 +00005194 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00005195}
5196
Richard Smithd62306a2011-11-10 06:34:14 +00005197/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00005198static bool HandleConstructorCall(const Expr *E, const LValue &This,
5199 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00005200 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00005201 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00005202 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00005203 if (!Info.CheckCallLimit(CallLoc))
5204 return false;
5205
Richard Smith3607ffe2012-02-13 03:54:03 +00005206 const CXXRecordDecl *RD = Definition->getParent();
5207 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005208 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00005209 return false;
5210 }
5211
Erik Pilkington42925492017-10-04 00:18:55 +00005212 EvalInfo::EvaluatingConstructorRAII EvalObj(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005213 Info,
5214 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5215 RD->getNumBases());
Richard Smith5179eb72016-06-28 19:03:57 +00005216 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00005217
Richard Smith52a980a2015-08-28 02:43:42 +00005218 // FIXME: Creating an APValue just to hold a nonexistent return value is
5219 // wasteful.
5220 APValue RetVal;
5221 StmtResult Ret = {RetVal, nullptr};
5222
Richard Smith5179eb72016-06-28 19:03:57 +00005223 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00005224 if (Definition->isDelegatingConstructor()) {
5225 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00005226 {
5227 FullExpressionRAII InitScope(Info);
5228 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
5229 return false;
5230 }
Richard Smith52a980a2015-08-28 02:43:42 +00005231 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005232 }
5233
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005234 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00005235 // essential for unions (or classes with anonymous union members), where the
5236 // operations performed by the constructor cannot be represented by
5237 // ctor-initializers.
5238 //
5239 // Skip this for empty non-union classes; we should not perform an
5240 // lvalue-to-rvalue conversion on them because their copy constructor does not
5241 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00005242 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00005243 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00005244 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005245 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00005246 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00005247 return handleLValueToRValueConversion(
5248 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5249 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005250 }
5251
5252 // Reserve space for the struct members.
Richard Smithe637cbe2019-05-21 23:15:18 +00005253 if (!RD->isUnion() && !Result.hasValue())
Richard Smithd62306a2011-11-10 06:34:14 +00005254 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005255 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005256
John McCalld7bca762012-05-01 00:38:49 +00005257 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005258 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5259
Richard Smith08d6a2c2013-07-24 07:11:57 +00005260 // A scope for temporaries lifetime-extended by reference members.
5261 BlockScopeRAII LifetimeExtendedScope(Info);
5262
Richard Smith253c2a32012-01-27 01:14:48 +00005263 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005264 unsigned BasesSeen = 0;
5265#ifndef NDEBUG
5266 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5267#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005268 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005269 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005270 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00005271 APValue *Value = &Result;
5272
5273 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00005274 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005275 if (I->isBaseInitializer()) {
5276 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00005277#ifndef NDEBUG
5278 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00005279 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00005280 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5281 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5282 "base class initializers not in expected order");
5283 ++BaseIt;
5284#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005285 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00005286 BaseType->getAsCXXRecordDecl(), &Layout))
5287 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005288 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00005289 } else if ((FD = I->getMember())) {
5290 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005291 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005292 if (RD->isUnion()) {
5293 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00005294 Value = &Result.getUnionValue();
5295 } else {
5296 Value = &Result.getStructField(FD->getFieldIndex());
5297 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00005298 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005299 // Walk the indirect field decl's chain to find the object to initialize,
5300 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005301 auto IndirectFieldChain = IFD->chain();
5302 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00005303 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005304 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5305 // Switch the union field if it differs. This happens if we had
5306 // preceding zero-initialization, and we're now initializing a union
5307 // subobject other than the first.
5308 // FIXME: In this case, the values of the other subobjects are
5309 // specified, since zero-initialization sets all padding bits to zero.
Richard Smithe637cbe2019-05-21 23:15:18 +00005310 if (!Value->hasValue() ||
Richard Smith1b78b3d2012-01-25 22:15:11 +00005311 (Value->isUnion() && Value->getUnionField() != FD)) {
5312 if (CD->isUnion())
5313 *Value = APValue(FD);
5314 else
5315 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005316 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00005317 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005318 // Store Subobject as its parent before updating it for the last element
5319 // in the chain.
5320 if (C == IndirectFieldChain.back())
5321 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005322 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00005323 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005324 if (CD->isUnion())
5325 Value = &Value->getUnionValue();
5326 else
5327 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00005328 }
Richard Smithd62306a2011-11-10 06:34:14 +00005329 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005330 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00005331 }
Richard Smith253c2a32012-01-27 01:14:48 +00005332
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005333 // Need to override This for implicit field initializers as in this case
5334 // This refers to innermost anonymous struct/union containing initializer,
5335 // not to currently constructed class.
5336 const Expr *Init = I->getInit();
5337 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5338 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00005339 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005340 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5341 (FD && FD->isBitField() &&
5342 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005343 // If we're checking for a potential constant expression, evaluate all
5344 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005345 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005346 return false;
5347 Success = false;
5348 }
Richard Smith921f1322019-05-13 23:35:21 +00005349
5350 // This is the point at which the dynamic type of the object becomes this
5351 // class type.
5352 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5353 EvalObj.finishedConstructingBases();
Richard Smithd62306a2011-11-10 06:34:14 +00005354 }
5355
Richard Smithd9f663b2013-04-22 15:31:51 +00005356 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00005357 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005358}
5359
Richard Smith5179eb72016-06-28 19:03:57 +00005360static bool HandleConstructorCall(const Expr *E, const LValue &This,
5361 ArrayRef<const Expr*> Args,
5362 const CXXConstructorDecl *Definition,
5363 EvalInfo &Info, APValue &Result) {
5364 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005365 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
Richard Smith5179eb72016-06-28 19:03:57 +00005366 return false;
5367
5368 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5369 Info, Result);
5370}
5371
Eli Friedman9a156e52008-11-12 09:44:48 +00005372//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00005373// Generic Evaluation
5374//===----------------------------------------------------------------------===//
5375namespace {
5376
Aaron Ballman68af21c2014-01-03 19:26:43 +00005377template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00005378class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005379 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00005380private:
Richard Smith52a980a2015-08-28 02:43:42 +00005381 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005382 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005383 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005384 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005385 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005386 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005387 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005388
Richard Smith17100ba2012-02-16 02:46:34 +00005389 // Check whether a conditional operator with a non-constant condition is a
5390 // potential constant expression. If neither arm is a potential constant
5391 // expression, then the conditional operator is not either.
5392 template<typename ConditionalOperator>
5393 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005394 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00005395
5396 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00005397 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00005398 {
Richard Smith17100ba2012-02-16 02:46:34 +00005399 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00005400 StmtVisitorTy::Visit(E->getFalseExpr());
5401 if (Diag.empty())
5402 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00005403 }
Richard Smith17100ba2012-02-16 02:46:34 +00005404
George Burgess IV8c892b52016-05-25 22:31:54 +00005405 {
5406 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00005407 Diag.clear();
5408 StmtVisitorTy::Visit(E->getTrueExpr());
5409 if (Diag.empty())
5410 return;
5411 }
5412
5413 Error(E, diag::note_constexpr_conditional_never_const);
5414 }
5415
5416
5417 template<typename ConditionalOperator>
5418 bool HandleConditionalOperator(const ConditionalOperator *E) {
5419 bool BoolResult;
5420 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00005421 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00005422 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00005423 return false;
5424 }
5425 if (Info.noteFailure()) {
5426 StmtVisitorTy::Visit(E->getTrueExpr());
5427 StmtVisitorTy::Visit(E->getFalseExpr());
5428 }
Richard Smith17100ba2012-02-16 02:46:34 +00005429 return false;
5430 }
5431
5432 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
5433 return StmtVisitorTy::Visit(EvalExpr);
5434 }
5435
Peter Collingbournee9200682011-05-13 03:29:01 +00005436protected:
5437 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005438 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00005439 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
5440
Richard Smith92b1ce02011-12-12 09:28:41 +00005441 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005442 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005443 }
5444
Aaron Ballman68af21c2014-01-03 19:26:43 +00005445 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005446
5447public:
5448 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
5449
5450 EvalInfo &getEvalInfo() { return Info; }
5451
Richard Smithf57d8cb2011-12-09 22:58:01 +00005452 /// Report an evaluation error. This should only be called when an error is
5453 /// first discovered. When propagating an error, just return false.
5454 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005455 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005456 return false;
5457 }
5458 bool Error(const Expr *E) {
5459 return Error(E, diag::note_invalid_subexpr_in_const_expr);
5460 }
5461
Aaron Ballman68af21c2014-01-03 19:26:43 +00005462 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00005463 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00005464 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005465 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005466 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005467 }
5468
Bill Wendling8003edc2018-11-09 00:41:36 +00005469 bool VisitConstantExpr(const ConstantExpr *E)
5470 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005471 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005472 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005473 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005474 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005475 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005476 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005477 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00005478 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005479 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005480 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005481 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00005482 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005483 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
5484 TempVersionRAII RAII(*Info.CurrentCall);
Eric Fiselier708afb52019-05-16 21:04:15 +00005485 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005486 return StmtVisitorTy::Visit(E->getExpr());
5487 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005488 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005489 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00005490 // The initializer may not have been parsed yet, or might be erroneous.
5491 if (!E->getExpr())
5492 return Error(E);
Eric Fiselier708afb52019-05-16 21:04:15 +00005493 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Richard Smith17e32462013-09-13 20:51:45 +00005494 return StmtVisitorTy::Visit(E->getExpr());
5495 }
Eric Fiselier708afb52019-05-16 21:04:15 +00005496
Richard Smith5894a912011-12-19 22:12:41 +00005497 // We cannot create any objects for which cleanups are required, so there is
5498 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00005499 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00005500 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005501
Aaron Ballman68af21c2014-01-03 19:26:43 +00005502 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005503 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
5504 return static_cast<Derived*>(this)->VisitCastExpr(E);
5505 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005506 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00005507 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
5508 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005509 return static_cast<Derived*>(this)->VisitCastExpr(E);
5510 }
5511
Aaron Ballman68af21c2014-01-03 19:26:43 +00005512 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005513 switch (E->getOpcode()) {
5514 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005515 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005516
5517 case BO_Comma:
5518 VisitIgnoredValue(E->getLHS());
5519 return StmtVisitorTy::Visit(E->getRHS());
5520
5521 case BO_PtrMemD:
5522 case BO_PtrMemI: {
5523 LValue Obj;
5524 if (!HandleMemberPointerAccess(Info, E, Obj))
5525 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005526 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00005527 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005528 return false;
5529 return DerivedSuccess(Result, E);
5530 }
5531 }
5532 }
5533
Aaron Ballman68af21c2014-01-03 19:26:43 +00005534 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00005535 // Evaluate and cache the common expression. We treat it as a temporary,
5536 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00005537 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00005538 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005539 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00005540
Richard Smith17100ba2012-02-16 02:46:34 +00005541 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005542 }
5543
Aaron Ballman68af21c2014-01-03 19:26:43 +00005544 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005545 bool IsBcpCall = false;
5546 // If the condition (ignoring parens) is a __builtin_constant_p call,
5547 // the result is a constant expression if it can be folded without
5548 // side-effects. This is an important GNU extension. See GCC PR38377
5549 // for discussion.
5550 if (const CallExpr *CallCE =
5551 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00005552 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00005553 IsBcpCall = true;
5554
5555 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
5556 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00005557 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00005558 return false;
5559
Richard Smith6d4c6582013-11-05 22:18:15 +00005560 FoldConstant Fold(Info, IsBcpCall);
5561 if (!HandleConditionalOperator(E)) {
5562 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00005563 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00005564 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00005565
5566 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00005567 }
5568
Aaron Ballman68af21c2014-01-03 19:26:43 +00005569 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005570 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00005571 return DerivedSuccess(*Value, E);
5572
5573 const Expr *Source = E->getSourceExpr();
5574 if (!Source)
5575 return Error(E);
5576 if (Source == E) { // sanity checking.
5577 assert(0 && "OpaqueValueExpr recursively refers to itself");
5578 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00005579 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00005580 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00005581 }
Richard Smith4ce706a2011-10-11 21:43:33 +00005582
Aaron Ballman68af21c2014-01-03 19:26:43 +00005583 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005584 APValue Result;
5585 if (!handleCallExpr(E, Result, nullptr))
5586 return false;
5587 return DerivedSuccess(Result, E);
5588 }
5589
5590 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00005591 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00005592 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00005593 QualType CalleeType = Callee->getType();
5594
Craig Topper36250ad2014-05-12 05:36:57 +00005595 const FunctionDecl *FD = nullptr;
5596 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00005597 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith921f1322019-05-13 23:35:21 +00005598 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00005599
Richard Smithe97cbd72011-11-11 04:05:33 +00005600 // Extract function decl and 'this' pointer from the callee.
5601 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smith921f1322019-05-13 23:35:21 +00005602 const CXXMethodDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005603 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
5604 // Explicit bound member calls, such as x.f() or p->g();
5605 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005606 return false;
Richard Smith921f1322019-05-13 23:35:21 +00005607 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
5608 if (!Member)
5609 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00005610 This = &ThisVal;
Richard Smith921f1322019-05-13 23:35:21 +00005611 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00005612 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
5613 // Indirect bound member calls ('.*' or '->*').
Richard Smith921f1322019-05-13 23:35:21 +00005614 Member = dyn_cast_or_null<CXXMethodDecl>(
5615 HandleMemberPointerAccess(Info, BE, ThisVal, false));
5616 if (!Member)
5617 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00005618 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00005619 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00005620 return Error(Callee);
Richard Smith921f1322019-05-13 23:35:21 +00005621 FD = Member;
Richard Smithe97cbd72011-11-11 04:05:33 +00005622 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00005623 LValue Call;
5624 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005625 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00005626
Richard Smitha8105bc2012-01-06 16:39:00 +00005627 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005628 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00005629 FD = dyn_cast_or_null<FunctionDecl>(
5630 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00005631 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005632 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00005633 // Don't call function pointers which have been cast to some other type.
5634 // Per DR (no number yet), the caller and callee can differ in noexcept.
5635 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
5636 CalleeType->getPointeeType(), FD->getType())) {
5637 return Error(E);
5638 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005639
5640 // Overloaded operator calls to member functions are represented as normal
5641 // calls with '*this' as the first argument.
5642 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
5643 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005644 // FIXME: When selecting an implicit conversion for an overloaded
5645 // operator delete, we sometimes try to evaluate calls to conversion
5646 // operators without a 'this' parameter!
5647 if (Args.empty())
5648 return Error(E);
5649
Nick Lewycky13073a62017-06-12 21:15:44 +00005650 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00005651 return false;
5652 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00005653 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00005654 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00005655 // Map the static invoker for the lambda back to the call operator.
5656 // Conveniently, we don't have to slice out the 'this' argument (as is
5657 // being done for the non-static case), since a static member function
5658 // doesn't have an implicit argument passed in.
5659 const CXXRecordDecl *ClosureClass = MD->getParent();
5660 assert(
5661 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
5662 "Number of captures must be zero for conversion to function-ptr");
5663
5664 const CXXMethodDecl *LambdaCallOp =
5665 ClosureClass->getLambdaCallOperator();
5666
5667 // Set 'FD', the function that will be called below, to the call
5668 // operator. If the closure object represents a generic lambda, find
5669 // the corresponding specialization of the call operator.
5670
5671 if (ClosureClass->isGenericLambda()) {
5672 assert(MD->isFunctionTemplateSpecialization() &&
5673 "A generic lambda's static-invoker function must be a "
5674 "template specialization");
5675 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
5676 FunctionTemplateDecl *CallOpTemplate =
5677 LambdaCallOp->getDescribedFunctionTemplate();
5678 void *InsertPos = nullptr;
5679 FunctionDecl *CorrespondingCallOpSpecialization =
5680 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
5681 assert(CorrespondingCallOpSpecialization &&
5682 "We must always have a function call operator specialization "
5683 "that corresponds to our static invoker specialization");
5684 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
5685 } else
5686 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00005687 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005688 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00005689 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00005690
Richard Smith921f1322019-05-13 23:35:21 +00005691 SmallVector<QualType, 4> CovariantAdjustmentPath;
5692 if (This) {
5693 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
Richard Smith7bd54ab2019-05-15 20:22:21 +00005694 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
5695 // Perform virtual dispatch, if necessary.
5696 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
5697 CovariantAdjustmentPath);
5698 if (!FD)
5699 return false;
5700 } else {
5701 // Check that the 'this' pointer points to an object of the right type.
5702 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
5703 return false;
5704 }
Richard Smith921f1322019-05-13 23:35:21 +00005705 }
Richard Smith47b34932012-02-01 02:39:43 +00005706
Craig Topper36250ad2014-05-12 05:36:57 +00005707 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00005708 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00005709
Nick Lewycky13073a62017-06-12 21:15:44 +00005710 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
5711 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00005712 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005713 return false;
5714
Richard Smith921f1322019-05-13 23:35:21 +00005715 if (!CovariantAdjustmentPath.empty() &&
5716 !HandleCovariantReturnAdjustment(Info, E, Result,
5717 CovariantAdjustmentPath))
5718 return false;
5719
Richard Smith52a980a2015-08-28 02:43:42 +00005720 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00005721 }
5722
Aaron Ballman68af21c2014-01-03 19:26:43 +00005723 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005724 return StmtVisitorTy::Visit(E->getInitializer());
5725 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005726 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00005727 if (E->getNumInits() == 0)
5728 return DerivedZeroInitialization(E);
5729 if (E->getNumInits() == 1)
5730 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00005731 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005732 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005733 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005734 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005735 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005736 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005737 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005738 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005739 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005740 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005741 }
Richard Smith4ce706a2011-10-11 21:43:33 +00005742
Richard Smithd62306a2011-11-10 06:34:14 +00005743 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00005744 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005745 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
5746 "missing temporary materialization conversion");
Richard Smithd62306a2011-11-10 06:34:14 +00005747 assert(!E->isArrow() && "missing call to bound member function?");
5748
Richard Smith2e312c82012-03-03 22:46:17 +00005749 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00005750 if (!Evaluate(Val, Info, E->getBase()))
5751 return false;
5752
5753 QualType BaseTy = E->getBase()->getType();
5754
5755 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00005756 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005757 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00005758 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00005759 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5760
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005761 // Note: there is no lvalue base here. But this case should only ever
5762 // happen in C or in C++98, where we cannot be evaluating a constexpr
5763 // constructor, which is the only case the base matters.
Richard Smithdebad642019-05-12 09:39:08 +00005764 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00005765 SubobjectDesignator Designator(BaseTy);
5766 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00005767
Richard Smith3229b742013-05-05 21:17:10 +00005768 APValue Result;
5769 return extractSubobject(Info, E, Obj, Designator, Result) &&
5770 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00005771 }
5772
Aaron Ballman68af21c2014-01-03 19:26:43 +00005773 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005774 switch (E->getCastKind()) {
5775 default:
5776 break;
5777
Richard Smitha23ab512013-05-23 00:30:41 +00005778 case CK_AtomicToNonAtomic: {
5779 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00005780 // This does not need to be done in place even for class/array types:
5781 // atomic-to-non-atomic conversion implies copying the object
5782 // representation.
5783 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00005784 return false;
5785 return DerivedSuccess(AtomicVal, E);
5786 }
5787
Richard Smith11562c52011-10-28 17:51:58 +00005788 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00005789 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00005790 return StmtVisitorTy::Visit(E->getSubExpr());
5791
5792 case CK_LValueToRValue: {
5793 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005794 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5795 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005796 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00005797 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00005798 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00005799 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005800 return false;
5801 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00005802 }
5803 }
5804
Richard Smithf57d8cb2011-12-09 22:58:01 +00005805 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005806 }
5807
Aaron Ballman68af21c2014-01-03 19:26:43 +00005808 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005809 return VisitUnaryPostIncDec(UO);
5810 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005811 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005812 return VisitUnaryPostIncDec(UO);
5813 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005814 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005815 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005816 return Error(UO);
5817
5818 LValue LVal;
5819 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5820 return false;
5821 APValue RVal;
5822 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5823 UO->isIncrementOp(), &RVal))
5824 return false;
5825 return DerivedSuccess(RVal, UO);
5826 }
5827
Aaron Ballman68af21c2014-01-03 19:26:43 +00005828 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00005829 // We will have checked the full-expressions inside the statement expression
5830 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00005831 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00005832 return Error(E);
5833
Richard Smith08d6a2c2013-07-24 07:11:57 +00005834 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00005835 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005836 if (CS->body_empty())
5837 return true;
5838
Richard Smith51f03172013-06-20 03:00:05 +00005839 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5840 BE = CS->body_end();
5841 /**/; ++BI) {
5842 if (BI + 1 == BE) {
5843 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5844 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005845 Info.FFDiag((*BI)->getBeginLoc(),
5846 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005847 return false;
5848 }
5849 return this->Visit(FinalExpr);
5850 }
5851
5852 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00005853 StmtResult Result = { ReturnValue, nullptr };
5854 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00005855 if (ESR != ESR_Succeeded) {
5856 // FIXME: If the statement-expression terminated due to 'return',
5857 // 'break', or 'continue', it would be nice to propagate that to
5858 // the outer statement evaluation rather than bailing out.
5859 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005860 Info.FFDiag((*BI)->getBeginLoc(),
5861 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005862 return false;
5863 }
5864 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005865
5866 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00005867 }
5868
Richard Smith4a678122011-10-24 18:44:57 +00005869 /// Visit a value which is evaluated, but whose value is ignored.
5870 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00005871 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00005872 }
David Majnemere9807b22016-02-26 04:23:19 +00005873
5874 /// Potentially visit a MemberExpr's base expression.
5875 void VisitIgnoredBaseExpression(const Expr *E) {
5876 // While MSVC doesn't evaluate the base expression, it does diagnose the
5877 // presence of side-effecting behavior.
5878 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5879 return;
5880 VisitIgnoredValue(E);
5881 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005882};
5883
Eric Fiselier0683c0e2018-05-07 21:07:10 +00005884} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00005885
5886//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005887// Common base class for lvalue and temporary evaluation.
5888//===----------------------------------------------------------------------===//
5889namespace {
5890template<class Derived>
5891class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005892 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00005893protected:
5894 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005895 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005896 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005897 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005898
5899 bool Success(APValue::LValueBase B) {
5900 Result.set(B);
5901 return true;
5902 }
5903
George Burgess IVf9013bf2017-02-10 22:52:29 +00005904 bool evaluatePointer(const Expr *E, LValue &Result) {
5905 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5906 }
5907
Richard Smith027bf112011-11-17 22:56:20 +00005908public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005909 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5910 : ExprEvaluatorBaseTy(Info), Result(Result),
5911 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005912
Richard Smith2e312c82012-03-03 22:46:17 +00005913 bool Success(const APValue &V, const Expr *E) {
5914 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005915 return true;
5916 }
Richard Smith027bf112011-11-17 22:56:20 +00005917
Richard Smith027bf112011-11-17 22:56:20 +00005918 bool VisitMemberExpr(const MemberExpr *E) {
5919 // Handle non-static data members.
5920 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005921 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005922 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005923 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005924 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005925 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005926 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005927 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005928 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005929 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005930 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005931 BaseTy = E->getBase()->getType();
5932 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005933 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005934 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005935 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005936 Result.setInvalid(E);
5937 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005938 }
Richard Smith027bf112011-11-17 22:56:20 +00005939
Richard Smith1b78b3d2012-01-25 22:15:11 +00005940 const ValueDecl *MD = E->getMemberDecl();
5941 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5942 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5943 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5944 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005945 if (!HandleLValueMember(this->Info, E, Result, FD))
5946 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005947 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005948 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5949 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005950 } else
5951 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005952
Richard Smith1b78b3d2012-01-25 22:15:11 +00005953 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005954 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005955 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005956 RefValue))
5957 return false;
5958 return Success(RefValue, E);
5959 }
5960 return true;
5961 }
5962
5963 bool VisitBinaryOperator(const BinaryOperator *E) {
5964 switch (E->getOpcode()) {
5965 default:
5966 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5967
5968 case BO_PtrMemD:
5969 case BO_PtrMemI:
5970 return HandleMemberPointerAccess(this->Info, E, Result);
5971 }
5972 }
5973
5974 bool VisitCastExpr(const CastExpr *E) {
5975 switch (E->getCastKind()) {
5976 default:
5977 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5978
5979 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005980 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005981 if (!this->Visit(E->getSubExpr()))
5982 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005983
5984 // Now figure out the necessary offset to add to the base LV to get from
5985 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005986 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5987 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005988 }
5989 }
5990};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005991}
Richard Smith027bf112011-11-17 22:56:20 +00005992
5993//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005994// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005995//
5996// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5997// function designators (in C), decl references to void objects (in C), and
5998// temporaries (if building with -Wno-address-of-temporary).
5999//
6000// LValue evaluation produces values comprising a base expression of one of the
6001// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00006002// - Declarations
6003// * VarDecl
6004// * FunctionDecl
6005// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00006006// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00006007// * StringLiteral
6008// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00006009// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00006010// * ObjCEncodeExpr
6011// * AddrLabelExpr
6012// * BlockExpr
6013// * CallExpr for a MakeStringConstant builtin
Richard Smithee0ce3022019-05-17 07:06:46 +00006014// - typeid(T) expressions, as TypeInfoLValues
Richard Smithce40ad62011-11-12 22:28:03 +00006015// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00006016// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00006017// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00006018// was evaluated, for cases where the MaterializeTemporaryExpr is missing
6019// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00006020// * A MaterializeTemporaryExpr that has static storage duration, with no
6021// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00006022// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00006023//===----------------------------------------------------------------------===//
6024namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006025class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00006026 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00006027public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006028 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
6029 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00006030
Richard Smith11562c52011-10-28 17:51:58 +00006031 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00006032 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00006033
Peter Collingbournee9200682011-05-13 03:29:01 +00006034 bool VisitDeclRefExpr(const DeclRefExpr *E);
6035 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006036 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006037 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
6038 bool VisitMemberExpr(const MemberExpr *E);
6039 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
6040 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00006041 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00006042 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006043 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
6044 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00006045 bool VisitUnaryReal(const UnaryOperator *E);
6046 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00006047 bool VisitUnaryPreInc(const UnaryOperator *UO) {
6048 return VisitUnaryPreIncDec(UO);
6049 }
6050 bool VisitUnaryPreDec(const UnaryOperator *UO) {
6051 return VisitUnaryPreIncDec(UO);
6052 }
Richard Smith3229b742013-05-05 21:17:10 +00006053 bool VisitBinAssign(const BinaryOperator *BO);
6054 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00006055
Peter Collingbournee9200682011-05-13 03:29:01 +00006056 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00006057 switch (E->getCastKind()) {
6058 default:
Richard Smith027bf112011-11-17 22:56:20 +00006059 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00006060
Eli Friedmance3e02a2011-10-11 00:13:24 +00006061 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00006062 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00006063 if (!Visit(E->getSubExpr()))
6064 return false;
6065 Result.Designator.setInvalid();
6066 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00006067
Richard Smith027bf112011-11-17 22:56:20 +00006068 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00006069 if (!Visit(E->getSubExpr()))
6070 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006071 return HandleBaseToDerivedCast(Info, E, Result);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006072
6073 case CK_Dynamic:
6074 if (!Visit(E->getSubExpr()))
6075 return false;
6076 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00006077 }
6078 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006079};
6080} // end anonymous namespace
6081
Richard Smith11562c52011-10-28 17:51:58 +00006082/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00006083/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00006084/// * function designators in C, and
6085/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00006086/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00006087static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
6088 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00006089 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00006090 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00006091 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006092}
6093
Peter Collingbournee9200682011-05-13 03:29:01 +00006094bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00006095 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00006096 return Success(FD);
6097 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00006098 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00006099 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00006100 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00006101 return Error(E);
6102}
Richard Smith733237d2011-10-24 23:14:33 +00006103
Faisal Vali0528a312016-11-13 06:09:16 +00006104
Richard Smith11562c52011-10-28 17:51:58 +00006105bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00006106
6107 // If we are within a lambda's call operator, check whether the 'VD' referred
6108 // to within 'E' actually represents a lambda-capture that maps to a
6109 // data-member/field within the closure object, and if so, evaluate to the
6110 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00006111 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
6112 isa<DeclRefExpr>(E) &&
6113 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
6114 // We don't always have a complete capture-map when checking or inferring if
6115 // the function call operator meets the requirements of a constexpr function
6116 // - but we don't need to evaluate the captures to determine constexprness
6117 // (dcl.constexpr C++17).
6118 if (Info.checkingPotentialConstantExpression())
6119 return false;
6120
Faisal Vali051e3a22017-02-16 04:12:21 +00006121 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00006122 // Start with 'Result' referring to the complete closure object...
6123 Result = *Info.CurrentCall->This;
6124 // ... then update it to refer to the field of the closure object
6125 // that represents the capture.
6126 if (!HandleLValueMember(Info, E, Result, FD))
6127 return false;
6128 // And if the field is of reference type, update 'Result' to refer to what
6129 // the field refers to.
6130 if (FD->getType()->isReferenceType()) {
6131 APValue RVal;
6132 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
6133 RVal))
6134 return false;
6135 Result.setFrom(Info.Ctx, RVal);
6136 }
6137 return true;
6138 }
6139 }
Craig Topper36250ad2014-05-12 05:36:57 +00006140 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00006141 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
6142 // Only if a local variable was declared in the function currently being
6143 // evaluated, do we expect to be able to find its value in the current
6144 // frame. (Otherwise it was likely declared in an enclosing context and
6145 // could either have a valid evaluatable value (for e.g. a constexpr
6146 // variable) or be ill-formed (and trigger an appropriate evaluation
6147 // diagnostic)).
6148 if (Info.CurrentCall->Callee &&
6149 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
6150 Frame = Info.CurrentCall;
6151 }
6152 }
Richard Smith3229b742013-05-05 21:17:10 +00006153
Richard Smithfec09922011-11-01 16:57:24 +00006154 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00006155 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006156 Result.set({VD, Frame->Index,
6157 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00006158 return true;
6159 }
Richard Smithce40ad62011-11-12 22:28:03 +00006160 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00006161 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00006162
Richard Smith3229b742013-05-05 21:17:10 +00006163 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006164 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006165 return false;
Richard Smithe637cbe2019-05-21 23:15:18 +00006166 if (!V->hasValue()) {
6167 // FIXME: Is it possible for V to be indeterminate here? If so, we should
6168 // adjust the diagnostic to say that.
Richard Smith6d4c6582013-11-05 22:18:15 +00006169 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00006170 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006171 return false;
6172 }
Richard Smith3229b742013-05-05 21:17:10 +00006173 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00006174}
6175
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006176bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
6177 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00006178 // Walk through the expression to find the materialized temporary itself.
6179 SmallVector<const Expr *, 2> CommaLHSs;
6180 SmallVector<SubobjectAdjustment, 2> Adjustments;
6181 const Expr *Inner = E->GetTemporaryExpr()->
6182 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00006183
Richard Smith84401042013-06-03 05:03:02 +00006184 // If we passed any comma operators, evaluate their LHSs.
6185 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
6186 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
6187 return false;
6188
Richard Smithe6c01442013-06-05 00:46:14 +00006189 // A materialized temporary with static storage duration can appear within the
6190 // result of a constant expression evaluation, so we need to preserve its
6191 // value for use outside this evaluation.
6192 APValue *Value;
6193 if (E->getStorageDuration() == SD_Static) {
6194 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00006195 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00006196 Result.set(E);
6197 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006198 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
6199 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00006200 }
6201
Richard Smithea4ad5d2013-06-06 08:19:16 +00006202 QualType Type = Inner->getType();
6203
Richard Smith84401042013-06-03 05:03:02 +00006204 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00006205 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
6206 (E->getStorageDuration() == SD_Static &&
6207 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
6208 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00006209 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00006210 }
Richard Smith84401042013-06-03 05:03:02 +00006211
6212 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00006213 for (unsigned I = Adjustments.size(); I != 0; /**/) {
6214 --I;
6215 switch (Adjustments[I].Kind) {
6216 case SubobjectAdjustment::DerivedToBaseAdjustment:
6217 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6218 Type, Result))
6219 return false;
6220 Type = Adjustments[I].DerivedToBase.BasePath->getType();
6221 break;
6222
6223 case SubobjectAdjustment::FieldAdjustment:
6224 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6225 return false;
6226 Type = Adjustments[I].Field->getType();
6227 break;
6228
6229 case SubobjectAdjustment::MemberPointerAdjustment:
6230 if (!HandleMemberPointerAccess(this->Info, Type, Result,
6231 Adjustments[I].Ptr.RHS))
6232 return false;
6233 Type = Adjustments[I].Ptr.MPT->getPointeeType();
6234 break;
6235 }
6236 }
6237
6238 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006239}
6240
Peter Collingbournee9200682011-05-13 03:29:01 +00006241bool
6242LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00006243 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6244 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00006245 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6246 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00006247 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006248}
6249
Richard Smith6e525142011-12-27 12:18:28 +00006250bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smitha9330302019-05-17 19:19:28 +00006251 TypeInfoLValue TypeInfo;
6252
Richard Smithee0ce3022019-05-17 07:06:46 +00006253 if (!E->isPotentiallyEvaluated()) {
Richard Smithee0ce3022019-05-17 07:06:46 +00006254 if (E->isTypeOperand())
6255 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6256 else
6257 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
Richard Smitha9330302019-05-17 19:19:28 +00006258 } else {
6259 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
6260 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
6261 << E->getExprOperand()->getType()
6262 << E->getExprOperand()->getSourceRange();
6263 }
6264
6265 if (!Visit(E->getExprOperand()))
6266 return false;
6267
6268 Optional<DynamicType> DynType =
6269 ComputeDynamicType(Info, E, Result, AK_TypeId);
6270 if (!DynType)
6271 return false;
6272
6273 TypeInfo =
6274 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
Richard Smithee0ce3022019-05-17 07:06:46 +00006275 }
Richard Smith6f3d4352012-10-17 23:52:07 +00006276
Richard Smitha9330302019-05-17 19:19:28 +00006277 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
Richard Smith6e525142011-12-27 12:18:28 +00006278}
6279
Francois Pichet0066db92012-04-16 04:08:35 +00006280bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
6281 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00006282}
Francois Pichet0066db92012-04-16 04:08:35 +00006283
Peter Collingbournee9200682011-05-13 03:29:01 +00006284bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006285 // Handle static data members.
6286 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006287 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00006288 return VisitVarDecl(E, VD);
6289 }
6290
Richard Smith254a73d2011-10-28 22:34:42 +00006291 // Handle static member functions.
6292 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
6293 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00006294 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00006295 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00006296 }
6297 }
6298
Richard Smithd62306a2011-11-10 06:34:14 +00006299 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00006300 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006301}
6302
Peter Collingbournee9200682011-05-13 03:29:01 +00006303bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006304 // FIXME: Deal with vectors as array subscript bases.
6305 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006306 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00006307
Nick Lewyckyad888682017-04-27 07:27:36 +00006308 bool Success = true;
6309 if (!evaluatePointer(E->getBase(), Result)) {
6310 if (!Info.noteFailure())
6311 return false;
6312 Success = false;
6313 }
Mike Stump11289f42009-09-09 15:08:12 +00006314
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006315 APSInt Index;
6316 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00006317 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006318
Nick Lewyckyad888682017-04-27 07:27:36 +00006319 return Success &&
6320 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006321}
Eli Friedman9a156e52008-11-12 09:44:48 +00006322
Peter Collingbournee9200682011-05-13 03:29:01 +00006323bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006324 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00006325}
6326
Richard Smith66c96992012-02-18 22:04:06 +00006327bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6328 if (!Visit(E->getSubExpr()))
6329 return false;
6330 // __real is a no-op on scalar lvalues.
6331 if (E->getSubExpr()->getType()->isAnyComplexType())
6332 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
6333 return true;
6334}
6335
6336bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6337 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
6338 "lvalue __imag__ on scalar?");
6339 if (!Visit(E->getSubExpr()))
6340 return false;
6341 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
6342 return true;
6343}
6344
Richard Smith243ef902013-05-05 23:31:59 +00006345bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006346 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00006347 return Error(UO);
6348
6349 if (!this->Visit(UO->getSubExpr()))
6350 return false;
6351
Richard Smith243ef902013-05-05 23:31:59 +00006352 return handleIncDec(
6353 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00006354 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00006355}
6356
6357bool LValueExprEvaluator::VisitCompoundAssignOperator(
6358 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006359 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00006360 return Error(CAO);
6361
Richard Smith3229b742013-05-05 21:17:10 +00006362 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00006363
6364 // The overall lvalue result is the result of evaluating the LHS.
6365 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00006366 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006367 Evaluate(RHS, this->Info, CAO->getRHS());
6368 return false;
6369 }
6370
Richard Smith3229b742013-05-05 21:17:10 +00006371 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
6372 return false;
6373
Richard Smith43e77732013-05-07 04:50:00 +00006374 return handleCompoundAssignment(
6375 this->Info, CAO,
6376 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
6377 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00006378}
6379
6380bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006381 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006382 return Error(E);
6383
Richard Smith3229b742013-05-05 21:17:10 +00006384 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00006385
6386 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00006387 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006388 Evaluate(NewVal, this->Info, E->getRHS());
6389 return false;
6390 }
6391
Richard Smith3229b742013-05-05 21:17:10 +00006392 if (!Evaluate(NewVal, this->Info, E->getRHS()))
6393 return false;
Richard Smith243ef902013-05-05 23:31:59 +00006394
Richard Smith31c69a32019-05-21 23:15:20 +00006395 if (Info.getLangOpts().CPlusPlus2a &&
6396 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
6397 return false;
6398
Richard Smith243ef902013-05-05 23:31:59 +00006399 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00006400 NewVal);
6401}
6402
Eli Friedman9a156e52008-11-12 09:44:48 +00006403//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006404// Pointer Evaluation
6405//===----------------------------------------------------------------------===//
6406
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006407/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00006408/// returned by a function with the alloc_size attribute. Returns true if we
6409/// were successful. Places an unsigned number into `Result`.
6410///
6411/// This expects the given CallExpr to be a call to a function with an
6412/// alloc_size attribute.
6413static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6414 const CallExpr *Call,
6415 llvm::APInt &Result) {
6416 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
6417
Joel E. Denny81508102018-03-13 14:51:22 +00006418 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
6419 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00006420 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
6421 if (Call->getNumArgs() <= SizeArgNo)
6422 return false;
6423
6424 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00006425 Expr::EvalResult ExprResult;
6426 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00006427 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006428 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00006429 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
6430 return false;
6431 Into = Into.zextOrSelf(BitsInSizeT);
6432 return true;
6433 };
6434
6435 APSInt SizeOfElem;
6436 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
6437 return false;
6438
Joel E. Denny81508102018-03-13 14:51:22 +00006439 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00006440 Result = std::move(SizeOfElem);
6441 return true;
6442 }
6443
6444 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00006445 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00006446 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
6447 return false;
6448
6449 bool Overflow;
6450 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
6451 if (Overflow)
6452 return false;
6453
6454 Result = std::move(BytesAvailable);
6455 return true;
6456}
6457
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006458/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00006459/// function.
6460static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6461 const LValue &LVal,
6462 llvm::APInt &Result) {
6463 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
6464 "Can't get the size of a non alloc_size function");
6465 const auto *Base = LVal.getLValueBase().get<const Expr *>();
6466 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
6467 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
6468}
6469
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006470/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00006471/// a function with the alloc_size attribute. If it was possible to do so, this
6472/// function will return true, make Result's Base point to said function call,
6473/// and mark Result's Base as invalid.
6474static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
6475 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006476 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00006477 return false;
6478
6479 // Because we do no form of static analysis, we only support const variables.
6480 //
6481 // Additionally, we can't support parameters, nor can we support static
6482 // variables (in the latter case, use-before-assign isn't UB; in the former,
6483 // we have no clue what they'll be assigned to).
6484 const auto *VD =
6485 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
6486 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
6487 return false;
6488
6489 const Expr *Init = VD->getAnyInitializer();
6490 if (!Init)
6491 return false;
6492
6493 const Expr *E = Init->IgnoreParens();
6494 if (!tryUnwrapAllocSizeCall(E))
6495 return false;
6496
6497 // Store E instead of E unwrapped so that the type of the LValue's base is
6498 // what the user wanted.
6499 Result.setInvalid(E);
6500
6501 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006502 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00006503 return true;
6504}
6505
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006506namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006507class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006508 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00006509 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006510 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00006511
Peter Collingbournee9200682011-05-13 03:29:01 +00006512 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00006513 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00006514 return true;
6515 }
George Burgess IVe3763372016-12-22 02:50:20 +00006516
George Burgess IVf9013bf2017-02-10 22:52:29 +00006517 bool evaluateLValue(const Expr *E, LValue &Result) {
6518 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
6519 }
6520
6521 bool evaluatePointer(const Expr *E, LValue &Result) {
6522 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
6523 }
6524
George Burgess IVe3763372016-12-22 02:50:20 +00006525 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006526public:
Mike Stump11289f42009-09-09 15:08:12 +00006527
George Burgess IVf9013bf2017-02-10 22:52:29 +00006528 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
6529 : ExprEvaluatorBaseTy(info), Result(Result),
6530 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006531
Richard Smith2e312c82012-03-03 22:46:17 +00006532 bool Success(const APValue &V, const Expr *E) {
6533 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00006534 return true;
6535 }
Richard Smithfddd3842011-12-30 21:15:51 +00006536 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00006537 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
6538 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00006539 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00006540 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006541
John McCall45d55e42010-05-07 21:00:08 +00006542 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006543 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00006544 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006545 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00006546 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00006547 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00006548 if (E->isExpressibleAsConstantInitializer())
6549 return Success(E);
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00006550 if (Info.noteFailure())
6551 EvaluateIgnoredValue(Info, E->getSubExpr());
6552 return Error(E);
6553 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006554 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00006555 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00006556 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006557 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00006558 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00006559 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00006560 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006561 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00006562 }
Richard Smithd62306a2011-11-10 06:34:14 +00006563 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00006564 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00006565 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00006566 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00006567 if (!Info.CurrentCall->This) {
6568 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00006569 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00006570 else
Faisal Valie690b7a2016-07-02 22:34:24 +00006571 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00006572 return false;
6573 }
Richard Smithd62306a2011-11-10 06:34:14 +00006574 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00006575 // If we are inside a lambda's call operator, the 'this' expression refers
6576 // to the enclosing '*this' object (either by value or reference) which is
6577 // either copied into the closure object's field that represents the '*this'
6578 // or refers to '*this'.
6579 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
6580 // Update 'Result' to refer to the data member/field of the closure object
6581 // that represents the '*this' capture.
6582 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00006583 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00006584 return false;
6585 // If we captured '*this' by reference, replace the field with its referent.
6586 if (Info.CurrentCall->LambdaThisCaptureField->getType()
6587 ->isPointerType()) {
6588 APValue RVal;
6589 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
6590 RVal))
6591 return false;
6592
6593 Result.setFrom(Info.Ctx, RVal);
6594 }
6595 }
Richard Smithd62306a2011-11-10 06:34:14 +00006596 return true;
6597 }
John McCallc07a0c72011-02-17 10:25:35 +00006598
Eric Fiselier708afb52019-05-16 21:04:15 +00006599 bool VisitSourceLocExpr(const SourceLocExpr *E) {
6600 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
6601 APValue LValResult = E->EvaluateInContext(
6602 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
6603 Result.setFrom(Info.Ctx, LValResult);
6604 return true;
6605 }
6606
Eli Friedman449fe542009-03-23 04:56:01 +00006607 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006608};
Chris Lattner05706e882008-07-11 18:11:29 +00006609} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006610
George Burgess IVf9013bf2017-02-10 22:52:29 +00006611static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
6612 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00006613 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00006614 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00006615}
6616
John McCall45d55e42010-05-07 21:00:08 +00006617bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00006618 if (E->getOpcode() != BO_Add &&
6619 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00006620 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00006621
Chris Lattner05706e882008-07-11 18:11:29 +00006622 const Expr *PExp = E->getLHS();
6623 const Expr *IExp = E->getRHS();
6624 if (IExp->getType()->isPointerType())
6625 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00006626
George Burgess IVf9013bf2017-02-10 22:52:29 +00006627 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00006628 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00006629 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006630
John McCall45d55e42010-05-07 21:00:08 +00006631 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00006632 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00006633 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00006634
Richard Smith96e0c102011-11-04 02:25:55 +00006635 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00006636 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00006637
Ted Kremenek28831752012-08-23 20:46:57 +00006638 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00006639 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00006640}
Eli Friedman9a156e52008-11-12 09:44:48 +00006641
John McCall45d55e42010-05-07 21:00:08 +00006642bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006643 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006644}
Mike Stump11289f42009-09-09 15:08:12 +00006645
Richard Smith81dfef92018-07-11 00:29:05 +00006646bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6647 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00006648
Eli Friedman847a2bc2009-12-27 05:43:15 +00006649 switch (E->getCastKind()) {
6650 default:
6651 break;
6652
John McCalle3027922010-08-25 11:45:40 +00006653 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00006654 case CK_CPointerToObjCPointerCast:
6655 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00006656 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00006657 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00006658 if (!Visit(SubExpr))
6659 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00006660 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
6661 // permitted in constant expressions in C++11. Bitcasts from cv void* are
6662 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00006663 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00006664 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00006665 if (SubExpr->getType()->isVoidPointerType())
6666 CCEDiag(E, diag::note_constexpr_invalid_cast)
6667 << 3 << SubExpr->getType();
6668 else
6669 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6670 }
Yaxun Liu402804b2016-12-15 08:09:08 +00006671 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
6672 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00006673 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00006674
Anders Carlsson18275092010-10-31 20:41:46 +00006675 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00006676 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006677 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00006678 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006679 if (!Result.Base && Result.Offset.isZero())
6680 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00006681
Richard Smithd62306a2011-11-10 06:34:14 +00006682 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00006683 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00006684 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
6685 castAs<PointerType>()->getPointeeType(),
6686 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00006687
Richard Smith027bf112011-11-17 22:56:20 +00006688 case CK_BaseToDerived:
6689 if (!Visit(E->getSubExpr()))
6690 return false;
6691 if (!Result.Base && Result.Offset.isZero())
6692 return true;
6693 return HandleBaseToDerivedCast(Info, E, Result);
6694
Richard Smith7bd54ab2019-05-15 20:22:21 +00006695 case CK_Dynamic:
6696 if (!Visit(E->getSubExpr()))
6697 return false;
6698 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
6699
Richard Smith0b0a0b62011-10-29 20:57:55 +00006700 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006701 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006702 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00006703
John McCalle3027922010-08-25 11:45:40 +00006704 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006705 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6706
Richard Smith2e312c82012-03-03 22:46:17 +00006707 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00006708 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00006709 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00006710
John McCall45d55e42010-05-07 21:00:08 +00006711 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00006712 unsigned Size = Info.Ctx.getTypeSize(E->getType());
6713 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006714 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006715 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00006716 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00006717 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00006718 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00006719 return true;
6720 } else {
6721 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00006722 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00006723 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00006724 }
6725 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00006726
6727 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00006728 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006729 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00006730 return false;
6731 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006732 APValue &Value = createTemporary(SubExpr, false, Result,
6733 *Info.CurrentCall);
6734 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00006735 return false;
6736 }
Richard Smith96e0c102011-11-04 02:25:55 +00006737 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00006738 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
6739 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00006740 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00006741 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00006742 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00006743 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00006744 }
Richard Smithdd785442011-10-31 20:57:44 +00006745
John McCalle3027922010-08-25 11:45:40 +00006746 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006747 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00006748
6749 case CK_LValueToRValue: {
6750 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006751 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00006752 return false;
6753
6754 APValue RVal;
6755 // Note, we use the subexpression's type in order to retain cv-qualifiers.
6756 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6757 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00006758 return InvalidBaseOK &&
6759 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00006760 return Success(RVal, E);
6761 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006762 }
6763
Richard Smith11562c52011-10-28 17:51:58 +00006764 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00006765}
Chris Lattner05706e882008-07-11 18:11:29 +00006766
Richard Smith6822bd72018-10-26 19:26:45 +00006767static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
6768 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006769 // C++ [expr.alignof]p3:
6770 // When alignof is applied to a reference type, the result is the
6771 // alignment of the referenced type.
6772 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6773 T = Ref->getPointeeType();
6774
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00006775 if (T.getQualifiers().hasUnaligned())
6776 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00006777
6778 const bool AlignOfReturnsPreferred =
6779 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
6780
6781 // __alignof is defined to return the preferred alignment.
6782 // Before 8, clang returned the preferred alignment for alignof and _Alignof
6783 // as well.
6784 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
6785 return Info.Ctx.toCharUnitsFromBits(
6786 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6787 // alignof and _Alignof are defined to return the ABI alignment.
6788 else if (ExprKind == UETT_AlignOf)
6789 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
6790 else
6791 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00006792}
6793
Richard Smith6822bd72018-10-26 19:26:45 +00006794static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
6795 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006796 E = E->IgnoreParens();
6797
6798 // The kinds of expressions that we have special-case logic here for
6799 // should be kept up to date with the special checks for those
6800 // expressions in Sema.
6801
6802 // alignof decl is always accepted, even if it doesn't make sense: we default
6803 // to 1 in those cases.
6804 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6805 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6806 /*RefAsPointee*/true);
6807
6808 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6809 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6810 /*RefAsPointee*/true);
6811
Richard Smith6822bd72018-10-26 19:26:45 +00006812 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006813}
6814
George Burgess IVe3763372016-12-22 02:50:20 +00006815// To be clear: this happily visits unsupported builtins. Better name welcomed.
6816bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6817 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6818 return true;
6819
George Burgess IVf9013bf2017-02-10 22:52:29 +00006820 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00006821 return false;
6822
6823 Result.setInvalid(E);
6824 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006825 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00006826 return true;
6827}
6828
Peter Collingbournee9200682011-05-13 03:29:01 +00006829bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006830 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00006831 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00006832
Richard Smith6328cbd2016-11-16 00:57:23 +00006833 if (unsigned BuiltinOp = E->getBuiltinCallee())
6834 return VisitBuiltinCallExpr(E, BuiltinOp);
6835
George Burgess IVe3763372016-12-22 02:50:20 +00006836 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006837}
6838
6839bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6840 unsigned BuiltinOp) {
6841 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00006842 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006843 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006844 case Builtin::BI__builtin_assume_aligned: {
6845 // We need to be very careful here because: if the pointer does not have the
6846 // asserted alignment, then the behavior is undefined, and undefined
6847 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00006848 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00006849 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00006850
Hal Finkel0dd05d42014-10-03 17:18:37 +00006851 LValue OffsetResult(Result);
6852 APSInt Alignment;
6853 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6854 return false;
Richard Smith642a2362017-01-30 23:30:26 +00006855 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00006856
6857 if (E->getNumArgs() > 2) {
6858 APSInt Offset;
6859 if (!EvaluateInteger(E->getArg(2), Offset, Info))
6860 return false;
6861
Richard Smith642a2362017-01-30 23:30:26 +00006862 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006863 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6864 }
6865
6866 // If there is a base object, then it must have the correct alignment.
6867 if (OffsetResult.Base) {
6868 CharUnits BaseAlignment;
6869 if (const ValueDecl *VD =
6870 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6871 BaseAlignment = Info.Ctx.getDeclAlign(VD);
Richard Smithee0ce3022019-05-17 07:06:46 +00006872 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
6873 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006874 } else {
Richard Smithee0ce3022019-05-17 07:06:46 +00006875 BaseAlignment = GetAlignOfType(
6876 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006877 }
6878
6879 if (BaseAlignment < Align) {
6880 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00006881 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00006882 CCEDiag(E->getArg(0),
6883 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00006884 << (unsigned)BaseAlignment.getQuantity()
6885 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006886 return false;
6887 }
6888 }
6889
6890 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006891 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006892 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006893
Richard Smith642a2362017-01-30 23:30:26 +00006894 (OffsetResult.Base
6895 ? CCEDiag(E->getArg(0),
6896 diag::note_constexpr_baa_insufficient_alignment) << 1
6897 : CCEDiag(E->getArg(0),
6898 diag::note_constexpr_baa_value_insufficient_alignment))
6899 << (int)OffsetResult.Offset.getQuantity()
6900 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006901 return false;
6902 }
6903
6904 return true;
6905 }
Eric Fiselier26187502018-12-14 21:11:28 +00006906 case Builtin::BI__builtin_launder:
6907 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00006908 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006909 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00006910 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006911 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00006912 if (Info.getLangOpts().CPlusPlus11)
6913 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6914 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00006915 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00006916 else
6917 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006918 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00006919 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006920 case Builtin::BI__builtin_wcschr:
6921 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006922 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006923 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00006924 if (!Visit(E->getArg(0)))
6925 return false;
6926 APSInt Desired;
6927 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6928 return false;
6929 uint64_t MaxLength = uint64_t(-1);
6930 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00006931 BuiltinOp != Builtin::BIwcschr &&
6932 BuiltinOp != Builtin::BI__builtin_strchr &&
6933 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00006934 APSInt N;
6935 if (!EvaluateInteger(E->getArg(2), N, Info))
6936 return false;
6937 MaxLength = N.getExtValue();
6938 }
Hubert Tong147b7432018-12-12 16:53:43 +00006939 // We cannot find the value if there are no candidates to match against.
6940 if (MaxLength == 0u)
6941 return ZeroInitialization(E);
6942 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
6943 Result.Designator.Invalid)
6944 return false;
6945 QualType CharTy = Result.Designator.getType(Info.Ctx);
6946 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
6947 BuiltinOp == Builtin::BI__builtin_memchr;
6948 assert(IsRawByte ||
6949 Info.Ctx.hasSameUnqualifiedType(
6950 CharTy, E->getArg(0)->getType()->getPointeeType()));
6951 // Pointers to const void may point to objects of incomplete type.
6952 if (IsRawByte && CharTy->isIncompleteType()) {
6953 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
6954 return false;
6955 }
6956 // Give up on byte-oriented matching against multibyte elements.
6957 // FIXME: We can compare the bytes in the correct order.
6958 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
6959 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00006960 // Figure out what value we're actually looking for (after converting to
6961 // the corresponding unsigned type if necessary).
6962 uint64_t DesiredVal;
6963 bool StopAtNull = false;
6964 switch (BuiltinOp) {
6965 case Builtin::BIstrchr:
6966 case Builtin::BI__builtin_strchr:
6967 // strchr compares directly to the passed integer, and therefore
6968 // always fails if given an int that is not a char.
6969 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6970 E->getArg(1)->getType(),
6971 Desired),
6972 Desired))
6973 return ZeroInitialization(E);
6974 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006975 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006976 case Builtin::BImemchr:
6977 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006978 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006979 // memchr compares by converting both sides to unsigned char. That's also
6980 // correct for strchr if we get this far (to cope with plain char being
6981 // unsigned in the strchr case).
6982 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6983 break;
Richard Smithe9507952016-11-12 01:39:56 +00006984
Richard Smith8110c9d2016-11-29 19:45:17 +00006985 case Builtin::BIwcschr:
6986 case Builtin::BI__builtin_wcschr:
6987 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006988 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006989 case Builtin::BIwmemchr:
6990 case Builtin::BI__builtin_wmemchr:
6991 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6992 DesiredVal = Desired.getZExtValue();
6993 break;
6994 }
Richard Smithe9507952016-11-12 01:39:56 +00006995
6996 for (; MaxLength; --MaxLength) {
6997 APValue Char;
6998 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6999 !Char.isInt())
7000 return false;
7001 if (Char.getInt().getZExtValue() == DesiredVal)
7002 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00007003 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00007004 break;
7005 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
7006 return false;
7007 }
7008 // Not found: return nullptr.
7009 return ZeroInitialization(E);
7010 }
7011
Richard Smith06f71b52018-08-04 00:57:17 +00007012 case Builtin::BImemcpy:
7013 case Builtin::BImemmove:
7014 case Builtin::BIwmemcpy:
7015 case Builtin::BIwmemmove:
7016 if (Info.getLangOpts().CPlusPlus11)
7017 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7018 << /*isConstexpr*/0 << /*isConstructor*/0
7019 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7020 else
7021 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7022 LLVM_FALLTHROUGH;
7023 case Builtin::BI__builtin_memcpy:
7024 case Builtin::BI__builtin_memmove:
7025 case Builtin::BI__builtin_wmemcpy:
7026 case Builtin::BI__builtin_wmemmove: {
7027 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
7028 BuiltinOp == Builtin::BIwmemmove ||
7029 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
7030 BuiltinOp == Builtin::BI__builtin_wmemmove;
7031 bool Move = BuiltinOp == Builtin::BImemmove ||
7032 BuiltinOp == Builtin::BIwmemmove ||
7033 BuiltinOp == Builtin::BI__builtin_memmove ||
7034 BuiltinOp == Builtin::BI__builtin_wmemmove;
7035
7036 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00007037 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00007038 return false;
7039 LValue Dest = Result;
7040
7041 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00007042 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00007043 return false;
7044
7045 APSInt N;
7046 if (!EvaluateInteger(E->getArg(2), N, Info))
7047 return false;
7048 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
7049
7050 // If the size is zero, we treat this as always being a valid no-op.
7051 // (Even if one of the src and dest pointers is null.)
7052 if (!N)
7053 return true;
7054
Richard Smith128719c2018-09-13 22:47:33 +00007055 // Otherwise, if either of the operands is null, we can't proceed. Don't
7056 // try to determine the type of the copied objects, because there aren't
7057 // any.
7058 if (!Src.Base || !Dest.Base) {
7059 APValue Val;
7060 (!Src.Base ? Src : Dest).moveInto(Val);
7061 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
7062 << Move << WChar << !!Src.Base
7063 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
7064 return false;
7065 }
7066 if (Src.Designator.Invalid || Dest.Designator.Invalid)
7067 return false;
7068
Richard Smith06f71b52018-08-04 00:57:17 +00007069 // We require that Src and Dest are both pointers to arrays of
7070 // trivially-copyable type. (For the wide version, the designator will be
7071 // invalid if the designated object is not a wchar_t.)
7072 QualType T = Dest.Designator.getType(Info.Ctx);
7073 QualType SrcT = Src.Designator.getType(Info.Ctx);
7074 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
7075 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
7076 return false;
7077 }
Petr Pavlued083f22018-10-04 09:25:44 +00007078 if (T->isIncompleteType()) {
7079 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
7080 return false;
7081 }
Richard Smith06f71b52018-08-04 00:57:17 +00007082 if (!T.isTriviallyCopyableType(Info.Ctx)) {
7083 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
7084 return false;
7085 }
7086
7087 // Figure out how many T's we're copying.
7088 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
7089 if (!WChar) {
7090 uint64_t Remainder;
7091 llvm::APInt OrigN = N;
7092 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
7093 if (Remainder) {
7094 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7095 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
7096 << (unsigned)TSize;
7097 return false;
7098 }
7099 }
7100
7101 // Check that the copying will remain within the arrays, just so that we
7102 // can give a more meaningful diagnostic. This implicitly also checks that
7103 // N fits into 64 bits.
7104 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
7105 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
7106 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
7107 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7108 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
7109 << N.toString(10, /*Signed*/false);
7110 return false;
7111 }
7112 uint64_t NElems = N.getZExtValue();
7113 uint64_t NBytes = NElems * TSize;
7114
7115 // Check for overlap.
7116 int Direction = 1;
7117 if (HasSameBase(Src, Dest)) {
7118 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
7119 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
7120 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
7121 // Dest is inside the source region.
7122 if (!Move) {
7123 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7124 return false;
7125 }
7126 // For memmove and friends, copy backwards.
7127 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
7128 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
7129 return false;
7130 Direction = -1;
7131 } else if (!Move && SrcOffset >= DestOffset &&
7132 SrcOffset - DestOffset < NBytes) {
7133 // Src is inside the destination region for memcpy: invalid.
7134 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7135 return false;
7136 }
7137 }
7138
7139 while (true) {
7140 APValue Val;
7141 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
7142 !handleAssignment(Info, E, Dest, T, Val))
7143 return false;
7144 // Do not iterate past the last element; if we're copying backwards, that
7145 // might take us off the start of the array.
7146 if (--NElems == 0)
7147 return true;
7148 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
7149 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
7150 return false;
7151 }
7152 }
7153
Richard Smith6cbd65d2013-07-11 02:27:57 +00007154 default:
George Burgess IVe3763372016-12-22 02:50:20 +00007155 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00007156 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007157}
Chris Lattner05706e882008-07-11 18:11:29 +00007158
7159//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00007160// Member Pointer Evaluation
7161//===----------------------------------------------------------------------===//
7162
7163namespace {
7164class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007165 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00007166 MemberPtr &Result;
7167
7168 bool Success(const ValueDecl *D) {
7169 Result = MemberPtr(D);
7170 return true;
7171 }
7172public:
7173
7174 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
7175 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7176
Richard Smith2e312c82012-03-03 22:46:17 +00007177 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007178 Result.setFrom(V);
7179 return true;
7180 }
Richard Smithfddd3842011-12-30 21:15:51 +00007181 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00007182 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00007183 }
7184
7185 bool VisitCastExpr(const CastExpr *E);
7186 bool VisitUnaryAddrOf(const UnaryOperator *E);
7187};
7188} // end anonymous namespace
7189
7190static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
7191 EvalInfo &Info) {
7192 assert(E->isRValue() && E->getType()->isMemberPointerType());
7193 return MemberPointerExprEvaluator(Info, Result).Visit(E);
7194}
7195
7196bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7197 switch (E->getCastKind()) {
7198 default:
7199 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7200
7201 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007202 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007203 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00007204
7205 case CK_BaseToDerivedMemberPointer: {
7206 if (!Visit(E->getSubExpr()))
7207 return false;
7208 if (E->path_empty())
7209 return true;
7210 // Base-to-derived member pointer casts store the path in derived-to-base
7211 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
7212 // the wrong end of the derived->base arc, so stagger the path by one class.
7213 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
7214 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
7215 PathI != PathE; ++PathI) {
7216 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7217 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7218 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007219 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007220 }
7221 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7222 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007223 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007224 return true;
7225 }
7226
7227 case CK_DerivedToBaseMemberPointer:
7228 if (!Visit(E->getSubExpr()))
7229 return false;
7230 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7231 PathE = E->path_end(); PathI != PathE; ++PathI) {
7232 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7233 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7234 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007235 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007236 }
7237 return true;
7238 }
7239}
7240
7241bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7242 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7243 // member can be formed.
7244 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7245}
7246
7247//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00007248// Record Evaluation
7249//===----------------------------------------------------------------------===//
7250
7251namespace {
7252 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007253 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007254 const LValue &This;
7255 APValue &Result;
7256 public:
7257
7258 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
7259 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
7260
Richard Smith2e312c82012-03-03 22:46:17 +00007261 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00007262 Result = V;
7263 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00007264 }
Richard Smithb8348f52016-05-12 22:16:28 +00007265 bool ZeroInitialization(const Expr *E) {
7266 return ZeroInitialization(E, E->getType());
7267 }
7268 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00007269
Richard Smith52a980a2015-08-28 02:43:42 +00007270 bool VisitCallExpr(const CallExpr *E) {
7271 return handleCallExpr(E, Result, &This);
7272 }
Richard Smithe97cbd72011-11-11 04:05:33 +00007273 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00007274 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00007275 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7276 return VisitCXXConstructExpr(E, E->getType());
7277 }
Faisal Valic72a08c2017-01-09 03:02:53 +00007278 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00007279 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00007280 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007281 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007282
7283 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00007284 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007285}
Richard Smithd62306a2011-11-10 06:34:14 +00007286
Richard Smithfddd3842011-12-30 21:15:51 +00007287/// Perform zero-initialization on an object of non-union class type.
7288/// C++11 [dcl.init]p5:
7289/// To zero-initialize an object or reference of type T means:
7290/// [...]
7291/// -- if T is a (possibly cv-qualified) non-union class type,
7292/// each non-static data member and each base-class subobject is
7293/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00007294static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
7295 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00007296 const LValue &This, APValue &Result) {
7297 assert(!RD->isUnion() && "Expected non-union class type");
7298 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
7299 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00007300 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00007301
John McCalld7bca762012-05-01 00:38:49 +00007302 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007303 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7304
7305 if (CD) {
7306 unsigned Index = 0;
7307 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00007308 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00007309 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
7310 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00007311 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
7312 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00007313 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00007314 Result.getStructBase(Index)))
7315 return false;
7316 }
7317 }
7318
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007319 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00007320 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00007321 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00007322 continue;
7323
7324 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007325 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00007326 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007327
David Blaikie2d7c57e2012-04-30 02:36:29 +00007328 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007329 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00007330 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00007331 return false;
7332 }
7333
7334 return true;
7335}
7336
Richard Smithb8348f52016-05-12 22:16:28 +00007337bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
7338 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00007339 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007340 if (RD->isUnion()) {
7341 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
7342 // object's first non-static named data member is zero-initialized
7343 RecordDecl::field_iterator I = RD->field_begin();
7344 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00007345 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00007346 return true;
7347 }
7348
7349 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00007350 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00007351 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00007352 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00007353 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007354 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00007355 }
7356
Richard Smith5d108602012-02-17 00:44:16 +00007357 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00007358 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00007359 return false;
7360 }
7361
Richard Smitha8105bc2012-01-06 16:39:00 +00007362 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00007363}
7364
Richard Smithe97cbd72011-11-11 04:05:33 +00007365bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
7366 switch (E->getCastKind()) {
7367 default:
7368 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7369
7370 case CK_ConstructorConversion:
7371 return Visit(E->getSubExpr());
7372
7373 case CK_DerivedToBase:
7374 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00007375 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007376 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00007377 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007378 if (!DerivedObject.isStruct())
7379 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00007380
7381 // Derived-to-base rvalue conversion: just slice off the derived part.
7382 APValue *Value = &DerivedObject;
7383 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
7384 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7385 PathE = E->path_end(); PathI != PathE; ++PathI) {
7386 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
7387 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7388 Value = &Value->getStructBase(getBaseIndex(RD, Base));
7389 RD = Base;
7390 }
7391 Result = *Value;
7392 return true;
7393 }
7394 }
7395}
7396
Richard Smithd62306a2011-11-10 06:34:14 +00007397bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00007398 if (E->isTransparent())
7399 return Visit(E->getInit(0));
7400
Richard Smithd62306a2011-11-10 06:34:14 +00007401 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00007402 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007403 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007404 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
7405
7406 EvalInfo::EvaluatingConstructorRAII EvalObj(
7407 Info,
7408 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7409 CXXRD && CXXRD->getNumBases());
Richard Smithd62306a2011-11-10 06:34:14 +00007410
7411 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00007412 const FieldDecl *Field = E->getInitializedFieldInUnion();
7413 Result = APValue(Field);
7414 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00007415 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00007416
7417 // If the initializer list for a union does not contain any elements, the
7418 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00007419 // FIXME: The element should be initialized from an initializer list.
7420 // Is this difference ever observable for initializer lists which
7421 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00007422 ImplicitValueInitExpr VIE(Field->getType());
7423 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
7424
Richard Smithd62306a2011-11-10 06:34:14 +00007425 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00007426 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
7427 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00007428
7429 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7430 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7431 isa<CXXDefaultInitExpr>(InitExpr));
7432
Richard Smithb228a862012-02-15 02:18:13 +00007433 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00007434 }
7435
Richard Smithe637cbe2019-05-21 23:15:18 +00007436 if (!Result.hasValue())
Richard Smithc0d04a22016-05-25 22:06:25 +00007437 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
7438 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00007439 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00007440 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00007441
7442 // Initialize base classes.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007443 if (CXXRD && CXXRD->getNumBases()) {
Richard Smith872307e2016-03-08 22:17:41 +00007444 for (const auto &Base : CXXRD->bases()) {
7445 assert(ElementNo < E->getNumInits() && "missing init for base class");
7446 const Expr *Init = E->getInit(ElementNo);
7447
7448 LValue Subobject = This;
7449 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
7450 return false;
7451
7452 APValue &FieldVal = Result.getStructBase(ElementNo);
7453 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007454 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00007455 return false;
7456 Success = false;
7457 }
7458 ++ElementNo;
7459 }
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007460
7461 EvalObj.finishedConstructingBases();
Richard Smith872307e2016-03-08 22:17:41 +00007462 }
7463
7464 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007465 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007466 // Anonymous bit-fields are not considered members of the class for
7467 // purposes of aggregate initialization.
7468 if (Field->isUnnamedBitfield())
7469 continue;
7470
7471 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00007472
Richard Smith253c2a32012-01-27 01:14:48 +00007473 bool HaveInit = ElementNo < E->getNumInits();
7474
7475 // FIXME: Diagnostics here should point to the end of the initializer
7476 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00007477 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007478 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00007479 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00007480
7481 // Perform an implicit value-initialization for members beyond the end of
7482 // the initializer list.
7483 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00007484 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00007485
Richard Smith852c9db2013-04-20 22:23:05 +00007486 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7487 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7488 isa<CXXDefaultInitExpr>(Init));
7489
Richard Smith49ca8aa2013-08-06 07:09:20 +00007490 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7491 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
7492 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007493 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00007494 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00007495 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00007496 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00007497 }
7498 }
7499
Richard Smith253c2a32012-01-27 01:14:48 +00007500 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00007501}
7502
Richard Smithb8348f52016-05-12 22:16:28 +00007503bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7504 QualType T) {
7505 // Note that E's type is not necessarily the type of our class here; we might
7506 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00007507 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00007508 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
7509
Richard Smithfddd3842011-12-30 21:15:51 +00007510 bool ZeroInit = E->requiresZeroInitialization();
7511 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00007512 // If we've already performed zero-initialization, we're already done.
Richard Smithe637cbe2019-05-21 23:15:18 +00007513 if (Result.hasValue())
Richard Smith9eae7232012-01-12 18:54:33 +00007514 return true;
7515
Richard Smithda3f4fd2014-03-05 23:32:50 +00007516 // We can get here in two different ways:
7517 // 1) We're performing value-initialization, and should zero-initialize
7518 // the object, or
7519 // 2) We're performing default-initialization of an object with a trivial
7520 // constexpr default constructor, in which case we should start the
7521 // lifetimes of all the base subobjects (there can be no data member
7522 // subobjects in this case) per [basic.life]p1.
7523 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00007524 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00007525 }
7526
Craig Topper36250ad2014-05-12 05:36:57 +00007527 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00007528 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00007529
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00007530 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00007531 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007532
Richard Smith1bc5c2c2012-01-10 04:32:03 +00007533 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00007534 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00007535 if (const MaterializeTemporaryExpr *ME
7536 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
7537 return Visit(ME->GetTemporaryExpr());
7538
Richard Smithb8348f52016-05-12 22:16:28 +00007539 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00007540 return false;
7541
Craig Topper5fc8fc22014-08-27 06:28:36 +00007542 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00007543 return HandleConstructorCall(E, This, Args,
7544 cast<CXXConstructorDecl>(Definition), Info,
7545 Result);
7546}
7547
7548bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
7549 const CXXInheritedCtorInitExpr *E) {
7550 if (!Info.CurrentCall) {
7551 assert(Info.checkingPotentialConstantExpression());
7552 return false;
7553 }
7554
7555 const CXXConstructorDecl *FD = E->getConstructor();
7556 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
7557 return false;
7558
7559 const FunctionDecl *Definition = nullptr;
7560 auto Body = FD->getBody(Definition);
7561
7562 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
7563 return false;
7564
7565 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00007566 cast<CXXConstructorDecl>(Definition), Info,
7567 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00007568}
7569
Richard Smithcc1b96d2013-06-12 22:31:48 +00007570bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
7571 const CXXStdInitializerListExpr *E) {
7572 const ConstantArrayType *ArrayType =
7573 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
7574
7575 LValue Array;
7576 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
7577 return false;
7578
7579 // Get a pointer to the first element of the array.
7580 Array.addArray(Info, E, ArrayType);
7581
7582 // FIXME: Perform the checks on the field types in SemaInit.
7583 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
7584 RecordDecl::field_iterator Field = Record->field_begin();
7585 if (Field == Record->field_end())
7586 return Error(E);
7587
7588 // Start pointer.
7589 if (!Field->getType()->isPointerType() ||
7590 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
7591 ArrayType->getElementType()))
7592 return Error(E);
7593
7594 // FIXME: What if the initializer_list type has base classes, etc?
7595 Result = APValue(APValue::UninitStruct(), 0, 2);
7596 Array.moveInto(Result.getStructField(0));
7597
7598 if (++Field == Record->field_end())
7599 return Error(E);
7600
7601 if (Field->getType()->isPointerType() &&
7602 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
7603 ArrayType->getElementType())) {
7604 // End pointer.
7605 if (!HandleLValueArrayAdjustment(Info, E, Array,
7606 ArrayType->getElementType(),
7607 ArrayType->getSize().getZExtValue()))
7608 return false;
7609 Array.moveInto(Result.getStructField(1));
7610 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
7611 // Length.
7612 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
7613 else
7614 return Error(E);
7615
7616 if (++Field != Record->field_end())
7617 return Error(E);
7618
7619 return true;
7620}
7621
Faisal Valic72a08c2017-01-09 03:02:53 +00007622bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
7623 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
7624 if (ClosureClass->isInvalidDecl()) return false;
7625
7626 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00007627
Faisal Vali051e3a22017-02-16 04:12:21 +00007628 const size_t NumFields =
7629 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00007630
7631 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
7632 E->capture_init_end()) &&
7633 "The number of lambda capture initializers should equal the number of "
7634 "fields within the closure type");
7635
Faisal Vali051e3a22017-02-16 04:12:21 +00007636 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
7637 // Iterate through all the lambda's closure object's fields and initialize
7638 // them.
7639 auto *CaptureInitIt = E->capture_init_begin();
7640 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
7641 bool Success = true;
7642 for (const auto *Field : ClosureClass->fields()) {
7643 assert(CaptureInitIt != E->capture_init_end());
7644 // Get the initializer for this field
7645 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00007646
Faisal Vali051e3a22017-02-16 04:12:21 +00007647 // If there is no initializer, either this is a VLA or an error has
7648 // occurred.
7649 if (!CurFieldInit)
7650 return Error(E);
7651
7652 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7653 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
7654 if (!Info.keepEvaluatingAfterFailure())
7655 return false;
7656 Success = false;
7657 }
7658 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00007659 }
Faisal Vali051e3a22017-02-16 04:12:21 +00007660 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00007661}
7662
Richard Smithd62306a2011-11-10 06:34:14 +00007663static bool EvaluateRecord(const Expr *E, const LValue &This,
7664 APValue &Result, EvalInfo &Info) {
7665 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00007666 "can't evaluate expression as a record rvalue");
7667 return RecordExprEvaluator(Info, This, Result).Visit(E);
7668}
7669
7670//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00007671// Temporary Evaluation
7672//
7673// Temporaries are represented in the AST as rvalues, but generally behave like
7674// lvalues. The full-object of which the temporary is a subobject is implicitly
7675// materialized so that a reference can bind to it.
7676//===----------------------------------------------------------------------===//
7677namespace {
7678class TemporaryExprEvaluator
7679 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
7680public:
7681 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00007682 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00007683
7684 /// Visit an expression which constructs the value of this temporary.
7685 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007686 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
7687 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00007688 }
7689
7690 bool VisitCastExpr(const CastExpr *E) {
7691 switch (E->getCastKind()) {
7692 default:
7693 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7694
7695 case CK_ConstructorConversion:
7696 return VisitConstructExpr(E->getSubExpr());
7697 }
7698 }
7699 bool VisitInitListExpr(const InitListExpr *E) {
7700 return VisitConstructExpr(E);
7701 }
7702 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7703 return VisitConstructExpr(E);
7704 }
7705 bool VisitCallExpr(const CallExpr *E) {
7706 return VisitConstructExpr(E);
7707 }
Richard Smith513955c2014-12-17 19:24:30 +00007708 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
7709 return VisitConstructExpr(E);
7710 }
Faisal Valic72a08c2017-01-09 03:02:53 +00007711 bool VisitLambdaExpr(const LambdaExpr *E) {
7712 return VisitConstructExpr(E);
7713 }
Richard Smith027bf112011-11-17 22:56:20 +00007714};
7715} // end anonymous namespace
7716
7717/// Evaluate an expression of record type as a temporary.
7718static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00007719 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00007720 return TemporaryExprEvaluator(Info, Result).Visit(E);
7721}
7722
7723//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007724// Vector Evaluation
7725//===----------------------------------------------------------------------===//
7726
7727namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007728 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007729 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00007730 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007731 public:
Mike Stump11289f42009-09-09 15:08:12 +00007732
Richard Smith2d406342011-10-22 21:10:00 +00007733 VectorExprEvaluator(EvalInfo &info, APValue &Result)
7734 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00007735
Craig Topper9798b932015-09-29 04:30:05 +00007736 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007737 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
7738 // FIXME: remove this APValue copy.
7739 Result = APValue(V.data(), V.size());
7740 return true;
7741 }
Richard Smith2e312c82012-03-03 22:46:17 +00007742 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00007743 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00007744 Result = V;
7745 return true;
7746 }
Richard Smithfddd3842011-12-30 21:15:51 +00007747 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00007748
Richard Smith2d406342011-10-22 21:10:00 +00007749 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00007750 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00007751 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00007752 bool VisitInitListExpr(const InitListExpr *E);
7753 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007754 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00007755 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00007756 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007757 };
7758} // end anonymous namespace
7759
7760static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007761 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00007762 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007763}
7764
George Burgess IV533ff002015-12-11 00:23:35 +00007765bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007766 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00007767 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007768
Richard Smith161f09a2011-12-06 22:44:34 +00007769 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00007770 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007771
Eli Friedmanc757de22011-03-25 00:43:55 +00007772 switch (E->getCastKind()) {
7773 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00007774 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00007775 if (SETy->isIntegerType()) {
7776 APSInt IntResult;
7777 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00007778 return false;
7779 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00007780 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00007781 APFloat FloatResult(0.0);
7782 if (!EvaluateFloat(SE, FloatResult, Info))
7783 return false;
7784 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00007785 } else {
Richard Smith2d406342011-10-22 21:10:00 +00007786 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007787 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00007788
7789 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00007790 SmallVector<APValue, 4> Elts(NElts, Val);
7791 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00007792 }
Eli Friedman803acb32011-12-22 03:51:45 +00007793 case CK_BitCast: {
7794 // Evaluate the operand into an APInt we can extract from.
7795 llvm::APInt SValInt;
7796 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
7797 return false;
7798 // Extract the elements
7799 QualType EltTy = VTy->getElementType();
7800 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
7801 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7802 SmallVector<APValue, 4> Elts;
7803 if (EltTy->isRealFloatingType()) {
7804 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00007805 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00007806 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00007807 FloatEltSize = 80;
7808 for (unsigned i = 0; i < NElts; i++) {
7809 llvm::APInt Elt;
7810 if (BigEndian)
7811 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
7812 else
7813 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00007814 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00007815 }
7816 } else if (EltTy->isIntegerType()) {
7817 for (unsigned i = 0; i < NElts; i++) {
7818 llvm::APInt Elt;
7819 if (BigEndian)
7820 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
7821 else
7822 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
7823 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
7824 }
7825 } else {
7826 return Error(E);
7827 }
7828 return Success(Elts, E);
7829 }
Eli Friedmanc757de22011-03-25 00:43:55 +00007830 default:
Richard Smith11562c52011-10-28 17:51:58 +00007831 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007832 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007833}
7834
Richard Smith2d406342011-10-22 21:10:00 +00007835bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007836VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007837 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007838 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00007839 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007840
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007841 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007842 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007843
Eli Friedmanb9c71292012-01-03 23:24:20 +00007844 // The number of initializers can be less than the number of
7845 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00007846 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00007847 // should be initialized with zeroes.
7848 unsigned CountInits = 0, CountElts = 0;
7849 while (CountElts < NumElements) {
7850 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00007851 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00007852 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00007853 APValue v;
7854 if (!EvaluateVector(E->getInit(CountInits), v, Info))
7855 return Error(E);
7856 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00007857 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00007858 Elements.push_back(v.getVectorElt(j));
7859 CountElts += vlen;
7860 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007861 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007862 if (CountInits < NumInits) {
7863 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007864 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007865 } else // trailing integer zero.
7866 sInt = Info.Ctx.MakeIntValue(0, EltTy);
7867 Elements.push_back(APValue(sInt));
7868 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007869 } else {
7870 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007871 if (CountInits < NumInits) {
7872 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007873 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007874 } else // trailing float zero.
7875 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7876 Elements.push_back(APValue(f));
7877 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00007878 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00007879 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007880 }
Richard Smith2d406342011-10-22 21:10:00 +00007881 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007882}
7883
Richard Smith2d406342011-10-22 21:10:00 +00007884bool
Richard Smithfddd3842011-12-30 21:15:51 +00007885VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007886 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00007887 QualType EltTy = VT->getElementType();
7888 APValue ZeroElement;
7889 if (EltTy->isIntegerType())
7890 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7891 else
7892 ZeroElement =
7893 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7894
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007895 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00007896 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007897}
7898
Richard Smith2d406342011-10-22 21:10:00 +00007899bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00007900 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007901 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007902}
7903
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007904//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00007905// Array Evaluation
7906//===----------------------------------------------------------------------===//
7907
7908namespace {
7909 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007910 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007911 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00007912 APValue &Result;
7913 public:
7914
Richard Smithd62306a2011-11-10 06:34:14 +00007915 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7916 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00007917
7918 bool Success(const APValue &V, const Expr *E) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00007919 assert(V.isArray() && "expected array");
Richard Smithf3e9e432011-11-07 09:22:26 +00007920 Result = V;
7921 return true;
7922 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007923
Richard Smithfddd3842011-12-30 21:15:51 +00007924 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007925 const ConstantArrayType *CAT =
7926 Info.Ctx.getAsConstantArrayType(E->getType());
7927 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007928 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007929
7930 Result = APValue(APValue::UninitArray(), 0,
7931 CAT->getSize().getZExtValue());
7932 if (!Result.hasArrayFiller()) return true;
7933
Richard Smithfddd3842011-12-30 21:15:51 +00007934 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00007935 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007936 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00007937 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00007938 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00007939 }
7940
Richard Smith52a980a2015-08-28 02:43:42 +00007941 bool VisitCallExpr(const CallExpr *E) {
7942 return handleCallExpr(E, Result, &This);
7943 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007944 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00007945 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00007946 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00007947 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7948 const LValue &Subobject,
7949 APValue *Value, QualType Type);
Eli Friedman3bf72d72019-02-08 21:18:46 +00007950 bool VisitStringLiteral(const StringLiteral *E) {
7951 expandStringLiteral(Info, E, Result);
7952 return true;
7953 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007954 };
7955} // end anonymous namespace
7956
Richard Smithd62306a2011-11-10 06:34:14 +00007957static bool EvaluateArray(const Expr *E, const LValue &This,
7958 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00007959 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00007960 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007961}
7962
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007963// Return true iff the given array filler may depend on the element index.
7964static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7965 // For now, just whitelist non-class value-initialization and initialization
7966 // lists comprised of them.
7967 if (isa<ImplicitValueInitExpr>(FillerExpr))
7968 return false;
7969 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7970 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7971 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7972 return true;
7973 }
7974 return false;
7975 }
7976 return true;
7977}
7978
Richard Smithf3e9e432011-11-07 09:22:26 +00007979bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7980 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7981 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007982 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007983
Richard Smithca2cfbf2011-12-22 01:07:19 +00007984 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7985 // an appropriately-typed string literal enclosed in braces.
Eli Friedman3bf72d72019-02-08 21:18:46 +00007986 if (E->isStringLiteralInit())
7987 return Visit(E->getInit(0));
Richard Smithca2cfbf2011-12-22 01:07:19 +00007988
Richard Smith253c2a32012-01-27 01:14:48 +00007989 bool Success = true;
7990
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007991 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7992 "zero-initialized array shouldn't have any initialized elts");
7993 APValue Filler;
7994 if (Result.isArray() && Result.hasArrayFiller())
7995 Filler = Result.getArrayFiller();
7996
Richard Smith9543c5e2013-04-22 14:44:29 +00007997 unsigned NumEltsToInit = E->getNumInits();
7998 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007999 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00008000
8001 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008002 // array element.
8003 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00008004 NumEltsToInit = NumElts;
8005
Nicola Zaghen3538b392018-05-15 13:30:56 +00008006 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
8007 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008008
Richard Smith9543c5e2013-04-22 14:44:29 +00008009 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008010
8011 // If the array was previously zero-initialized, preserve the
8012 // zero-initialized values.
Richard Smithe637cbe2019-05-21 23:15:18 +00008013 if (Filler.hasValue()) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008014 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
8015 Result.getArrayInitializedElt(I) = Filler;
8016 if (Result.hasArrayFiller())
8017 Result.getArrayFiller() = Filler;
8018 }
8019
Richard Smithd62306a2011-11-10 06:34:14 +00008020 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00008021 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00008022 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
8023 const Expr *Init =
8024 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00008025 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00008026 Info, Subobject, Init) ||
8027 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00008028 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00008029 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00008030 return false;
8031 Success = false;
8032 }
Richard Smithd62306a2011-11-10 06:34:14 +00008033 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008034
Richard Smith9543c5e2013-04-22 14:44:29 +00008035 if (!Result.hasArrayFiller())
8036 return Success;
8037
8038 // If we get here, we have a trivial filler, which we can just evaluate
8039 // once and splat over the rest of the array elements.
8040 assert(FillerExpr && "no array filler for incomplete init list");
8041 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
8042 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00008043}
8044
Richard Smith410306b2016-12-12 02:53:20 +00008045bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
8046 if (E->getCommonExpr() &&
8047 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
8048 Info, E->getCommonExpr()->getSourceExpr()))
8049 return false;
8050
8051 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
8052
8053 uint64_t Elements = CAT->getSize().getZExtValue();
8054 Result = APValue(APValue::UninitArray(), Elements, Elements);
8055
8056 LValue Subobject = This;
8057 Subobject.addArray(Info, E, CAT);
8058
8059 bool Success = true;
8060 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
8061 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8062 Info, Subobject, E->getSubExpr()) ||
8063 !HandleLValueArrayAdjustment(Info, E, Subobject,
8064 CAT->getElementType(), 1)) {
8065 if (!Info.noteFailure())
8066 return false;
8067 Success = false;
8068 }
8069 }
8070
8071 return Success;
8072}
8073
Richard Smith027bf112011-11-17 22:56:20 +00008074bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00008075 return VisitCXXConstructExpr(E, This, &Result, E->getType());
8076}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008077
Richard Smith9543c5e2013-04-22 14:44:29 +00008078bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8079 const LValue &Subobject,
8080 APValue *Value,
8081 QualType Type) {
Richard Smithe637cbe2019-05-21 23:15:18 +00008082 bool HadZeroInit = Value->hasValue();
Richard Smith9543c5e2013-04-22 14:44:29 +00008083
8084 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
8085 unsigned N = CAT->getSize().getZExtValue();
8086
8087 // Preserve the array filler if we had prior zero-initialization.
8088 APValue Filler =
8089 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
8090 : APValue();
8091
8092 *Value = APValue(APValue::UninitArray(), N, N);
8093
8094 if (HadZeroInit)
8095 for (unsigned I = 0; I != N; ++I)
8096 Value->getArrayInitializedElt(I) = Filler;
8097
8098 // Initialize the elements.
8099 LValue ArrayElt = Subobject;
8100 ArrayElt.addArray(Info, E, CAT);
8101 for (unsigned I = 0; I != N; ++I)
8102 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
8103 CAT->getElementType()) ||
8104 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
8105 CAT->getElementType(), 1))
8106 return false;
8107
8108 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008109 }
Richard Smith027bf112011-11-17 22:56:20 +00008110
Richard Smith9543c5e2013-04-22 14:44:29 +00008111 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00008112 return Error(E);
8113
Richard Smithb8348f52016-05-12 22:16:28 +00008114 return RecordExprEvaluator(Info, Subobject, *Value)
8115 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00008116}
8117
Richard Smithf3e9e432011-11-07 09:22:26 +00008118//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00008119// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00008120//
8121// As a GNU extension, we support casting pointers to sufficiently-wide integer
8122// types and back in constant folding. Integer values are thus represented
8123// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00008124//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00008125
8126namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008127class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008128 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00008129 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00008130public:
Richard Smith2e312c82012-03-03 22:46:17 +00008131 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008132 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00008133
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008134 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008135 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008136 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008137 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008138 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008139 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008140 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008141 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008142 return true;
8143 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008144 bool Success(const llvm::APSInt &SI, const Expr *E) {
8145 return Success(SI, E, Result);
8146 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008147
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008148 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008149 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008150 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008151 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008152 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008153 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008154 Result.getInt().setIsUnsigned(
8155 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008156 return true;
8157 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008158 bool Success(const llvm::APInt &I, const Expr *E) {
8159 return Success(I, E, Result);
8160 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008161
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008162 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008163 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008164 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008165 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008166 return true;
8167 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008168 bool Success(uint64_t Value, const Expr *E) {
8169 return Success(Value, E, Result);
8170 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008171
Ken Dyckdbc01912011-03-11 02:13:43 +00008172 bool Success(CharUnits Size, const Expr *E) {
8173 return Success(Size.getQuantity(), E);
8174 }
8175
Richard Smith2e312c82012-03-03 22:46:17 +00008176 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008177 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00008178 Result = V;
8179 return true;
8180 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008181 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00008182 }
Mike Stump11289f42009-09-09 15:08:12 +00008183
Richard Smithfddd3842011-12-30 21:15:51 +00008184 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00008185
Peter Collingbournee9200682011-05-13 03:29:01 +00008186 //===--------------------------------------------------------------------===//
8187 // Visitor Methods
8188 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00008189
Fangrui Song407659a2018-11-30 23:41:18 +00008190 bool VisitConstantExpr(const ConstantExpr *E);
8191
Chris Lattner7174bf32008-07-12 00:38:25 +00008192 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008193 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00008194 }
8195 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008196 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00008197 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008198
8199 bool CheckReferencedDecl(const Expr *E, const Decl *D);
8200 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008201 if (CheckReferencedDecl(E, E->getDecl()))
8202 return true;
8203
8204 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008205 }
8206 bool VisitMemberExpr(const MemberExpr *E) {
8207 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00008208 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008209 return true;
8210 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008211
8212 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008213 }
8214
Peter Collingbournee9200682011-05-13 03:29:01 +00008215 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00008216 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00008217 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00008218 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00008219 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00008220
Peter Collingbournee9200682011-05-13 03:29:01 +00008221 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008222 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00008223
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008224 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008225 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008226 }
Mike Stump11289f42009-09-09 15:08:12 +00008227
Ted Kremeneke65b0862012-03-06 20:05:56 +00008228 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8229 return Success(E->getValue(), E);
8230 }
Richard Smith410306b2016-12-12 02:53:20 +00008231
8232 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8233 if (Info.ArrayInitIndex == uint64_t(-1)) {
8234 // We were asked to evaluate this subexpression independent of the
8235 // enclosing ArrayInitLoopExpr. We can't do that.
8236 Info.FFDiag(E);
8237 return false;
8238 }
8239 return Success(Info.ArrayInitIndex, E);
8240 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008241
Richard Smith4ce706a2011-10-11 21:43:33 +00008242 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00008243 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00008244 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008245 }
8246
Douglas Gregor29c42f22012-02-24 07:38:34 +00008247 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8248 return Success(E->getValue(), E);
8249 }
8250
John Wiegley6242b6a2011-04-28 00:16:57 +00008251 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
8252 return Success(E->getValue(), E);
8253 }
8254
John Wiegleyf9f65842011-04-25 06:54:41 +00008255 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
8256 return Success(E->getValue(), E);
8257 }
8258
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008259 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008260 bool VisitUnaryImag(const UnaryOperator *E);
8261
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008262 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008263 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Eric Fiselier708afb52019-05-16 21:04:15 +00008264 bool VisitSourceLocExpr(const SourceLocExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008265 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00008266};
Leonard Chandb01c3a2018-06-20 17:19:40 +00008267
8268class FixedPointExprEvaluator
8269 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
8270 APValue &Result;
8271
8272 public:
8273 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
8274 : ExprEvaluatorBaseTy(info), Result(result) {}
8275
Leonard Chandb01c3a2018-06-20 17:19:40 +00008276 bool Success(const llvm::APInt &I, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008277 return Success(
8278 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008279 }
8280
Leonard Chandb01c3a2018-06-20 17:19:40 +00008281 bool Success(uint64_t Value, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008282 return Success(
8283 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008284 }
8285
8286 bool Success(const APValue &V, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008287 return Success(V.getFixedPoint(), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008288 }
8289
Leonard Chand3f3e162019-01-18 21:04:25 +00008290 bool Success(const APFixedPoint &V, const Expr *E) {
8291 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
8292 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8293 "Invalid evaluation result.");
8294 Result = APValue(V);
8295 return true;
8296 }
Leonard Chandb01c3a2018-06-20 17:19:40 +00008297
8298 //===--------------------------------------------------------------------===//
8299 // Visitor Methods
8300 //===--------------------------------------------------------------------===//
8301
8302 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
8303 return Success(E->getValue(), E);
8304 }
8305
Leonard Chand3f3e162019-01-18 21:04:25 +00008306 bool VisitCastExpr(const CastExpr *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008307 bool VisitUnaryOperator(const UnaryOperator *E);
Leonard Chand3f3e162019-01-18 21:04:25 +00008308 bool VisitBinaryOperator(const BinaryOperator *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008309};
Chris Lattner05706e882008-07-11 18:11:29 +00008310} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008311
Richard Smith11562c52011-10-28 17:51:58 +00008312/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
8313/// produce either the integer value or a pointer.
8314///
8315/// GCC has a heinous extension which folds casts between pointer types and
8316/// pointer-sized integral types. We support this by allowing the evaluation of
8317/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
8318/// Some simple arithmetic on such values is supported (they are treated much
8319/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00008320static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00008321 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008322 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008323 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00008324}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008325
Richard Smithf57d8cb2011-12-09 22:58:01 +00008326static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00008327 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008328 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00008329 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008330 if (!Val.isInt()) {
8331 // FIXME: It would be better to produce the diagnostic for casting
8332 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00008333 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008334 return false;
8335 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008336 Result = Val.getInt();
8337 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008338}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008339
Eric Fiselier708afb52019-05-16 21:04:15 +00008340bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
8341 APValue Evaluated = E->EvaluateInContext(
8342 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8343 return Success(Evaluated, E);
8344}
8345
Leonard Chand3f3e162019-01-18 21:04:25 +00008346static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
8347 EvalInfo &Info) {
8348 if (E->getType()->isFixedPointType()) {
8349 APValue Val;
8350 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
8351 return false;
8352 if (!Val.isFixedPoint())
8353 return false;
8354
8355 Result = Val.getFixedPoint();
8356 return true;
8357 }
8358 return false;
8359}
8360
8361static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
8362 EvalInfo &Info) {
8363 if (E->getType()->isIntegerType()) {
8364 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
8365 APSInt Val;
8366 if (!EvaluateInteger(E, Val, Info))
8367 return false;
8368 Result = APFixedPoint(Val, FXSema);
8369 return true;
8370 } else if (E->getType()->isFixedPointType()) {
8371 return EvaluateFixedPoint(E, Result, Info);
8372 }
8373 return false;
8374}
8375
Richard Smithf57d8cb2011-12-09 22:58:01 +00008376/// Check whether the given declaration can be directly converted to an integral
8377/// rvalue. If not, no diagnostic is produced; there are other things we can
8378/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008379bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00008380 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00008381 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008382 // Check for signedness/width mismatches between E type and ECD value.
8383 bool SameSign = (ECD->getInitVal().isSigned()
8384 == E->getType()->isSignedIntegerOrEnumerationType());
8385 bool SameWidth = (ECD->getInitVal().getBitWidth()
8386 == Info.Ctx.getIntWidth(E->getType()));
8387 if (SameSign && SameWidth)
8388 return Success(ECD->getInitVal(), E);
8389 else {
8390 // Get rid of mismatch (otherwise Success assertions will fail)
8391 // by computing a new value matching the type of E.
8392 llvm::APSInt Val = ECD->getInitVal();
8393 if (!SameSign)
8394 Val.setIsSigned(!ECD->getInitVal().isSigned());
8395 if (!SameWidth)
8396 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
8397 return Success(Val, E);
8398 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00008399 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008400 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00008401}
8402
Richard Smith08b682b2018-05-23 21:18:00 +00008403/// Values returned by __builtin_classify_type, chosen to match the values
8404/// produced by GCC's builtin.
8405enum class GCCTypeClass {
8406 None = -1,
8407 Void = 0,
8408 Integer = 1,
8409 // GCC reserves 2 for character types, but instead classifies them as
8410 // integers.
8411 Enum = 3,
8412 Bool = 4,
8413 Pointer = 5,
8414 // GCC reserves 6 for references, but appears to never use it (because
8415 // expressions never have reference type, presumably).
8416 PointerToDataMember = 7,
8417 RealFloat = 8,
8418 Complex = 9,
8419 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
8420 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
8421 // GCC claims to reserve 11 for pointers to member functions, but *actually*
8422 // uses 12 for that purpose, same as for a class or struct. Maybe it
8423 // internally implements a pointer to member as a struct? Who knows.
8424 PointerToMemberFunction = 12, // Not a bug, see above.
8425 ClassOrStruct = 12,
8426 Union = 13,
8427 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
8428 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
8429 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
8430 // literals.
8431};
8432
Chris Lattner86ee2862008-10-06 06:40:35 +00008433/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8434/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00008435static GCCTypeClass
8436EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
8437 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00008438
Richard Smith08b682b2018-05-23 21:18:00 +00008439 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008440 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
8441
8442 switch (CanTy->getTypeClass()) {
8443#define TYPE(ID, BASE)
8444#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
8445#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
8446#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
8447#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00008448 case Type::Auto:
8449 case Type::DeducedTemplateSpecialization:
8450 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008451
8452 case Type::Builtin:
8453 switch (BT->getKind()) {
8454#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00008455#define SIGNED_TYPE(ID, SINGLETON_ID) \
8456 case BuiltinType::ID: return GCCTypeClass::Integer;
8457#define FLOATING_TYPE(ID, SINGLETON_ID) \
8458 case BuiltinType::ID: return GCCTypeClass::RealFloat;
8459#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
8460 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008461#include "clang/AST/BuiltinTypes.def"
8462 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00008463 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008464
8465 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00008466 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008467
Richard Smith08b682b2018-05-23 21:18:00 +00008468 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008469 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00008470 case BuiltinType::WChar_U:
8471 case BuiltinType::Char8:
8472 case BuiltinType::Char16:
8473 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008474 case BuiltinType::UShort:
8475 case BuiltinType::UInt:
8476 case BuiltinType::ULong:
8477 case BuiltinType::ULongLong:
8478 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00008479 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008480
Leonard Chanf921d852018-06-04 16:07:52 +00008481 case BuiltinType::UShortAccum:
8482 case BuiltinType::UAccum:
8483 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00008484 case BuiltinType::UShortFract:
8485 case BuiltinType::UFract:
8486 case BuiltinType::ULongFract:
8487 case BuiltinType::SatUShortAccum:
8488 case BuiltinType::SatUAccum:
8489 case BuiltinType::SatULongAccum:
8490 case BuiltinType::SatUShortFract:
8491 case BuiltinType::SatUFract:
8492 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00008493 return GCCTypeClass::None;
8494
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008495 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008496
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008497 case BuiltinType::ObjCId:
8498 case BuiltinType::ObjCClass:
8499 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00008500#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8501 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00008502#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00008503#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8504 case BuiltinType::Id:
8505#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008506 case BuiltinType::OCLSampler:
8507 case BuiltinType::OCLEvent:
8508 case BuiltinType::OCLClkEvent:
8509 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008510 case BuiltinType::OCLReserveID:
Richard Smith08b682b2018-05-23 21:18:00 +00008511 return GCCTypeClass::None;
8512
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008513 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00008514 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008515 };
Richard Smith08b682b2018-05-23 21:18:00 +00008516 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008517
8518 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00008519 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008520
8521 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008522 case Type::ConstantArray:
8523 case Type::VariableArray:
8524 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00008525 case Type::FunctionNoProto:
8526 case Type::FunctionProto:
8527 return GCCTypeClass::Pointer;
8528
8529 case Type::MemberPointer:
8530 return CanTy->isMemberDataPointerType()
8531 ? GCCTypeClass::PointerToDataMember
8532 : GCCTypeClass::PointerToMemberFunction;
8533
8534 case Type::Complex:
8535 return GCCTypeClass::Complex;
8536
8537 case Type::Record:
8538 return CanTy->isUnionType() ? GCCTypeClass::Union
8539 : GCCTypeClass::ClassOrStruct;
8540
8541 case Type::Atomic:
8542 // GCC classifies _Atomic T the same as T.
8543 return EvaluateBuiltinClassifyType(
8544 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008545
8546 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008547 case Type::Vector:
8548 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008549 case Type::ObjCObject:
8550 case Type::ObjCInterface:
8551 case Type::ObjCObjectPointer:
8552 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00008553 // GCC classifies vectors as None. We follow its lead and classify all
8554 // other types that don't fit into the regular classification the same way.
8555 return GCCTypeClass::None;
8556
8557 case Type::LValueReference:
8558 case Type::RValueReference:
8559 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008560 }
8561
Richard Smith08b682b2018-05-23 21:18:00 +00008562 llvm_unreachable("unexpected type class");
8563}
8564
8565/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8566/// as GCC.
8567static GCCTypeClass
8568EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
8569 // If no argument was supplied, default to None. This isn't
8570 // ideal, however it is what gcc does.
8571 if (E->getNumArgs() == 0)
8572 return GCCTypeClass::None;
8573
8574 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
8575 // being an ICE, but still folds it to a constant using the type of the first
8576 // argument.
8577 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00008578}
8579
Richard Smith5fab0c92011-12-28 19:48:30 +00008580/// EvaluateBuiltinConstantPForLValue - Determine the result of
Richard Smith31cfb312019-04-27 02:58:17 +00008581/// __builtin_constant_p when applied to the given pointer.
Richard Smith5fab0c92011-12-28 19:48:30 +00008582///
Richard Smith31cfb312019-04-27 02:58:17 +00008583/// A pointer is only "constant" if it is null (or a pointer cast to integer)
8584/// or it points to the first character of a string literal.
8585static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
8586 APValue::LValueBase Base = LV.getLValueBase();
8587 if (Base.isNull()) {
8588 // A null base is acceptable.
8589 return true;
8590 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
8591 if (!isa<StringLiteral>(E))
8592 return false;
8593 return LV.getLValueOffset().isZero();
Richard Smithee0ce3022019-05-17 07:06:46 +00008594 } else if (Base.is<TypeInfoLValue>()) {
8595 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
8596 // evaluate to true.
8597 return true;
Richard Smith31cfb312019-04-27 02:58:17 +00008598 } else {
8599 // Any other base is not constant enough for GCC.
8600 return false;
8601 }
Richard Smith5fab0c92011-12-28 19:48:30 +00008602}
8603
8604/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
8605/// GCC as we can manage.
Richard Smith31cfb312019-04-27 02:58:17 +00008606static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
Richard Smith37be3362019-05-04 04:00:45 +00008607 // This evaluation is not permitted to have side-effects, so evaluate it in
8608 // a speculative evaluation context.
8609 SpeculativeEvaluationRAII SpeculativeEval(Info);
8610
Richard Smith31cfb312019-04-27 02:58:17 +00008611 // Constant-folding is always enabled for the operand of __builtin_constant_p
8612 // (even when the enclosing evaluation context otherwise requires a strict
8613 // language-specific constant expression).
8614 FoldConstant Fold(Info, true);
8615
Richard Smith5fab0c92011-12-28 19:48:30 +00008616 QualType ArgType = Arg->getType();
8617
8618 // __builtin_constant_p always has one operand. The rules which gcc follows
8619 // are not precisely documented, but are as follows:
8620 //
8621 // - If the operand is of integral, floating, complex or enumeration type,
8622 // and can be folded to a known value of that type, it returns 1.
Richard Smith31cfb312019-04-27 02:58:17 +00008623 // - If the operand can be folded to a pointer to the first character
8624 // of a string literal (or such a pointer cast to an integral type)
8625 // or to a null pointer or an integer cast to a pointer, it returns 1.
Richard Smith5fab0c92011-12-28 19:48:30 +00008626 //
8627 // Otherwise, it returns 0.
8628 //
8629 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
Richard Smith31cfb312019-04-27 02:58:17 +00008630 // its support for this did not work prior to GCC 9 and is not yet well
8631 // understood.
8632 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
8633 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
8634 ArgType->isNullPtrType()) {
8635 APValue V;
8636 if (!::EvaluateAsRValue(Info, Arg, V)) {
8637 Fold.keepDiagnostics();
Richard Smith5fab0c92011-12-28 19:48:30 +00008638 return false;
Richard Smith31cfb312019-04-27 02:58:17 +00008639 }
Richard Smith5fab0c92011-12-28 19:48:30 +00008640
Richard Smith31cfb312019-04-27 02:58:17 +00008641 // For a pointer (possibly cast to integer), there are special rules.
Richard Smith0c6124b2015-12-03 01:36:22 +00008642 if (V.getKind() == APValue::LValue)
8643 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith31cfb312019-04-27 02:58:17 +00008644
8645 // Otherwise, any constant value is good enough.
Richard Smithe637cbe2019-05-21 23:15:18 +00008646 return V.hasValue();
Richard Smith5fab0c92011-12-28 19:48:30 +00008647 }
8648
8649 // Anything else isn't considered to be sufficiently constant.
8650 return false;
8651}
8652
John McCall95007602010-05-10 23:27:23 +00008653/// Retrieves the "underlying object type" of the given expression,
8654/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00008655static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00008656 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
8657 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00008658 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00008659 } else if (const Expr *E = B.get<const Expr*>()) {
8660 if (isa<CompoundLiteralExpr>(E))
8661 return E->getType();
Richard Smithee0ce3022019-05-17 07:06:46 +00008662 } else if (B.is<TypeInfoLValue>()) {
8663 return B.getTypeInfoType();
John McCall95007602010-05-10 23:27:23 +00008664 }
8665
8666 return QualType();
8667}
8668
George Burgess IV3a03fab2015-09-04 21:28:13 +00008669/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00008670/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00008671/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00008672/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
8673///
8674/// Always returns an RValue with a pointer representation.
8675static const Expr *ignorePointerCastsAndParens(const Expr *E) {
8676 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8677
8678 auto *NoParens = E->IgnoreParens();
8679 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00008680 if (Cast == nullptr)
8681 return NoParens;
8682
8683 // We only conservatively allow a few kinds of casts, because this code is
8684 // inherently a simple solution that seeks to support the common case.
8685 auto CastKind = Cast->getCastKind();
8686 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
8687 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00008688 return NoParens;
8689
8690 auto *SubExpr = Cast->getSubExpr();
8691 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
8692 return NoParens;
8693 return ignorePointerCastsAndParens(SubExpr);
8694}
8695
George Burgess IVa51c4072015-10-16 01:49:01 +00008696/// Checks to see if the given LValue's Designator is at the end of the LValue's
8697/// record layout. e.g.
8698/// struct { struct { int a, b; } fst, snd; } obj;
8699/// obj.fst // no
8700/// obj.snd // yes
8701/// obj.fst.a // no
8702/// obj.fst.b // no
8703/// obj.snd.a // no
8704/// obj.snd.b // yes
8705///
8706/// Please note: this function is specialized for how __builtin_object_size
8707/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00008708///
Richard Smith6f4f0f12017-10-20 22:56:25 +00008709/// If this encounters an invalid RecordDecl or otherwise cannot determine the
8710/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00008711static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
8712 assert(!LVal.Designator.Invalid);
8713
George Burgess IV4168d752016-06-27 19:40:41 +00008714 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
8715 const RecordDecl *Parent = FD->getParent();
8716 Invalid = Parent->isInvalidDecl();
8717 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00008718 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00008719 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00008720 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
8721 };
8722
8723 auto &Base = LVal.getLValueBase();
8724 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
8725 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00008726 bool Invalid;
8727 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
8728 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00008729 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00008730 for (auto *FD : IFD->chain()) {
8731 bool Invalid;
8732 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
8733 return Invalid;
8734 }
George Burgess IVa51c4072015-10-16 01:49:01 +00008735 }
8736 }
8737
George Burgess IVe3763372016-12-22 02:50:20 +00008738 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00008739 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00008740 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00008741 // If we don't know the array bound, conservatively assume we're looking at
8742 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00008743 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00008744 if (BaseType->isIncompleteArrayType())
8745 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
8746 else
8747 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00008748 }
8749
8750 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
8751 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00008752 if (BaseType->isArrayType()) {
8753 // Because __builtin_object_size treats arrays as objects, we can ignore
8754 // the index iff this is the last array in the Designator.
8755 if (I + 1 == E)
8756 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00008757 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
Richard Smith5b5e27a2019-05-10 20:05:31 +00008758 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00008759 if (Index + 1 != CAT->getSize())
8760 return false;
8761 BaseType = CAT->getElementType();
8762 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00008763 const auto *CT = BaseType->castAs<ComplexType>();
Richard Smith5b5e27a2019-05-10 20:05:31 +00008764 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00008765 if (Index != 1)
8766 return false;
8767 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00008768 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00008769 bool Invalid;
8770 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
8771 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00008772 BaseType = FD->getType();
8773 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00008774 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00008775 return false;
8776 }
8777 }
8778 return true;
8779}
8780
George Burgess IVe3763372016-12-22 02:50:20 +00008781/// Tests to see if the LValue has a user-specified designator (that isn't
8782/// necessarily valid). Note that this always returns 'true' if the LValue has
8783/// an unsized array as its first designator entry, because there's currently no
8784/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00008785static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00008786 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00008787 return false;
8788
George Burgess IVe3763372016-12-22 02:50:20 +00008789 if (!LVal.Designator.Entries.empty())
8790 return LVal.Designator.isMostDerivedAnUnsizedArray();
8791
George Burgess IVa51c4072015-10-16 01:49:01 +00008792 if (!LVal.InvalidBase)
8793 return true;
8794
George Burgess IVe3763372016-12-22 02:50:20 +00008795 // If `E` is a MemberExpr, then the first part of the designator is hiding in
8796 // the LValueBase.
8797 const auto *E = LVal.Base.dyn_cast<const Expr *>();
8798 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00008799}
8800
George Burgess IVe3763372016-12-22 02:50:20 +00008801/// Attempts to detect a user writing into a piece of memory that's impossible
8802/// to figure out the size of by just using types.
8803static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
8804 const SubobjectDesignator &Designator = LVal.Designator;
8805 // Notes:
8806 // - Users can only write off of the end when we have an invalid base. Invalid
8807 // bases imply we don't know where the memory came from.
8808 // - We used to be a bit more aggressive here; we'd only be conservative if
8809 // the array at the end was flexible, or if it had 0 or 1 elements. This
8810 // broke some common standard library extensions (PR30346), but was
8811 // otherwise seemingly fine. It may be useful to reintroduce this behavior
8812 // with some sort of whitelist. OTOH, it seems that GCC is always
8813 // conservative with the last element in structs (if it's an array), so our
8814 // current behavior is more compatible than a whitelisting approach would
8815 // be.
8816 return LVal.InvalidBase &&
8817 Designator.Entries.size() == Designator.MostDerivedPathLength &&
8818 Designator.MostDerivedIsArrayElement &&
8819 isDesignatorAtObjectEnd(Ctx, LVal);
8820}
8821
8822/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
8823/// Fails if the conversion would cause loss of precision.
8824static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
8825 CharUnits &Result) {
8826 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
8827 if (Int.ugt(CharUnitsMax))
8828 return false;
8829 Result = CharUnits::fromQuantity(Int.getZExtValue());
8830 return true;
8831}
8832
8833/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
8834/// determine how many bytes exist from the beginning of the object to either
8835/// the end of the current subobject, or the end of the object itself, depending
8836/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00008837///
George Burgess IVe3763372016-12-22 02:50:20 +00008838/// If this returns false, the value of Result is undefined.
8839static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
8840 unsigned Type, const LValue &LVal,
8841 CharUnits &EndOffset) {
8842 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008843
George Burgess IV7fb7e362017-01-03 23:35:19 +00008844 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
8845 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
8846 return false;
8847 return HandleSizeof(Info, ExprLoc, Ty, Result);
8848 };
8849
George Burgess IVe3763372016-12-22 02:50:20 +00008850 // We want to evaluate the size of the entire object. This is a valid fallback
8851 // for when Type=1 and the designator is invalid, because we're asked for an
8852 // upper-bound.
8853 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
8854 // Type=3 wants a lower bound, so we can't fall back to this.
8855 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00008856 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00008857
8858 llvm::APInt APEndOffset;
8859 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8860 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8861 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8862
8863 if (LVal.InvalidBase)
8864 return false;
8865
8866 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00008867 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00008868 }
8869
George Burgess IVe3763372016-12-22 02:50:20 +00008870 // We want to evaluate the size of a subobject.
8871 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008872
8873 // The following is a moderately common idiom in C:
8874 //
8875 // struct Foo { int a; char c[1]; };
8876 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8877 // strcpy(&F->c[0], Bar);
8878 //
George Burgess IVe3763372016-12-22 02:50:20 +00008879 // In order to not break too much legacy code, we need to support it.
8880 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8881 // If we can resolve this to an alloc_size call, we can hand that back,
8882 // because we know for certain how many bytes there are to write to.
8883 llvm::APInt APEndOffset;
8884 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8885 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8886 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8887
8888 // If we cannot determine the size of the initial allocation, then we can't
8889 // given an accurate upper-bound. However, we are still able to give
8890 // conservative lower-bounds for Type=3.
8891 if (Type == 1)
8892 return false;
8893 }
8894
8895 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00008896 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008897 return false;
8898
George Burgess IVe3763372016-12-22 02:50:20 +00008899 // According to the GCC documentation, we want the size of the subobject
8900 // denoted by the pointer. But that's not quite right -- what we actually
8901 // want is the size of the immediately-enclosing array, if there is one.
8902 int64_t ElemsRemaining;
8903 if (Designator.MostDerivedIsArrayElement &&
8904 Designator.Entries.size() == Designator.MostDerivedPathLength) {
8905 uint64_t ArraySize = Designator.getMostDerivedArraySize();
Richard Smith5b5e27a2019-05-10 20:05:31 +00008906 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00008907 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8908 } else {
8909 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8910 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008911
George Burgess IVe3763372016-12-22 02:50:20 +00008912 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8913 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008914}
8915
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008916/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00008917/// returns true and stores the result in @p Size.
8918///
8919/// If @p WasError is non-null, this will report whether the failure to evaluate
8920/// is to be treated as an Error in IntExprEvaluator.
8921static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8922 EvalInfo &Info, uint64_t &Size) {
8923 // Determine the denoted object.
8924 LValue LVal;
8925 {
8926 // The operand of __builtin_object_size is never evaluated for side-effects.
8927 // If there are any, but we can determine the pointed-to object anyway, then
8928 // ignore the side-effects.
8929 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00008930 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00008931
8932 if (E->isGLValue()) {
8933 // It's possible for us to be given GLValues if we're called via
8934 // Expr::tryEvaluateObjectSize.
8935 APValue RVal;
8936 if (!EvaluateAsRValue(Info, E, RVal))
8937 return false;
8938 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00008939 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8940 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00008941 return false;
8942 }
8943
8944 // If we point to before the start of the object, there are no accessible
8945 // bytes.
8946 if (LVal.getLValueOffset().isNegative()) {
8947 Size = 0;
8948 return true;
8949 }
8950
8951 CharUnits EndOffset;
8952 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8953 return false;
8954
8955 // If we've fallen outside of the end offset, just pretend there's nothing to
8956 // write to/read from.
8957 if (EndOffset <= LVal.getLValueOffset())
8958 Size = 0;
8959 else
8960 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8961 return true;
John McCall95007602010-05-10 23:27:23 +00008962}
8963
Fangrui Song407659a2018-11-30 23:41:18 +00008964bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
8965 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
Gauthier Harnischdea9d572019-06-21 08:26:21 +00008966 if (E->getResultAPValueKind() != APValue::None)
8967 return Success(E->getAPValueResult(), E);
Fangrui Song407659a2018-11-30 23:41:18 +00008968 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
8969}
8970
Peter Collingbournee9200682011-05-13 03:29:01 +00008971bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00008972 if (unsigned BuiltinOp = E->getBuiltinCallee())
8973 return VisitBuiltinCallExpr(E, BuiltinOp);
8974
8975 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8976}
8977
8978bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8979 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00008980 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008981 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00008982 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00008983
Erik Pilkington9c3b5882019-01-30 20:34:53 +00008984 case Builtin::BI__builtin_dynamic_object_size:
Mike Stump722cedf2009-10-26 18:35:08 +00008985 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00008986 // The type was checked when we built the expression.
8987 unsigned Type =
8988 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8989 assert(Type <= 3 && "unexpected type");
8990
George Burgess IVe3763372016-12-22 02:50:20 +00008991 uint64_t Size;
8992 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8993 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00008994
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008995 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00008996 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00008997
Richard Smith01ade172012-05-23 04:13:20 +00008998 // Expression had no side effects, but we couldn't statically determine the
8999 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009000 switch (Info.EvalMode) {
9001 case EvalInfo::EM_ConstantExpression:
9002 case EvalInfo::EM_PotentialConstantExpression:
9003 case EvalInfo::EM_ConstantFold:
9004 case EvalInfo::EM_EvaluateForOverflow:
9005 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00009006 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009007 return Error(E);
9008 case EvalInfo::EM_ConstantExpressionUnevaluated:
9009 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00009010 // Reduce it to a constant now.
9011 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009012 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00009013
9014 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00009015 }
9016
Tim Northover314fbfa2018-11-02 13:14:11 +00009017 case Builtin::BI__builtin_os_log_format_buffer_size: {
9018 analyze_os_log::OSLogBufferLayout Layout;
9019 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
9020 return Success(Layout.size().getQuantity(), E);
9021 }
9022
Benjamin Kramera801f4a2012-10-06 14:42:22 +00009023 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00009024 case Builtin::BI__builtin_bswap32:
9025 case Builtin::BI__builtin_bswap64: {
9026 APSInt Val;
9027 if (!EvaluateInteger(E->getArg(0), Val, Info))
9028 return false;
9029
9030 return Success(Val.byteSwap(), E);
9031 }
9032
Richard Smith8889a3d2013-06-13 06:26:32 +00009033 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00009034 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00009035
Craig Topperf95a6d92018-08-08 22:31:12 +00009036 case Builtin::BI__builtin_clrsb:
9037 case Builtin::BI__builtin_clrsbl:
9038 case Builtin::BI__builtin_clrsbll: {
9039 APSInt Val;
9040 if (!EvaluateInteger(E->getArg(0), Val, Info))
9041 return false;
9042
9043 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
9044 }
Richard Smith8889a3d2013-06-13 06:26:32 +00009045
Richard Smith80b3c8e2013-06-13 05:04:16 +00009046 case Builtin::BI__builtin_clz:
9047 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00009048 case Builtin::BI__builtin_clzll:
9049 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00009050 APSInt Val;
9051 if (!EvaluateInteger(E->getArg(0), Val, Info))
9052 return false;
9053 if (!Val)
9054 return Error(E);
9055
9056 return Success(Val.countLeadingZeros(), E);
9057 }
9058
Fangrui Song407659a2018-11-30 23:41:18 +00009059 case Builtin::BI__builtin_constant_p: {
Richard Smith31cfb312019-04-27 02:58:17 +00009060 const Expr *Arg = E->getArg(0);
David Blaikie639b3d12019-05-03 18:11:31 +00009061 if (EvaluateBuiltinConstantP(Info, Arg))
Fangrui Song407659a2018-11-30 23:41:18 +00009062 return Success(true, E);
David Blaikie639b3d12019-05-03 18:11:31 +00009063 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
Richard Smithf7d30482019-05-02 23:21:28 +00009064 // Outside a constant context, eagerly evaluate to false in the presence
9065 // of side-effects in order to avoid -Wunsequenced false-positives in
9066 // a branch on __builtin_constant_p(expr).
Richard Smith31cfb312019-04-27 02:58:17 +00009067 return Success(false, E);
Fangrui Song407659a2018-11-30 23:41:18 +00009068 }
David Blaikie639b3d12019-05-03 18:11:31 +00009069 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9070 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00009071 }
Richard Smith8889a3d2013-06-13 06:26:32 +00009072
Eric Fiselieradd16a82019-04-24 02:23:30 +00009073 case Builtin::BI__builtin_is_constant_evaluated:
9074 return Success(Info.InConstantContext, E);
9075
Richard Smith80b3c8e2013-06-13 05:04:16 +00009076 case Builtin::BI__builtin_ctz:
9077 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00009078 case Builtin::BI__builtin_ctzll:
9079 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00009080 APSInt Val;
9081 if (!EvaluateInteger(E->getArg(0), Val, Info))
9082 return false;
9083 if (!Val)
9084 return Error(E);
9085
9086 return Success(Val.countTrailingZeros(), E);
9087 }
9088
Richard Smith8889a3d2013-06-13 06:26:32 +00009089 case Builtin::BI__builtin_eh_return_data_regno: {
9090 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9091 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
9092 return Success(Operand, E);
9093 }
9094
9095 case Builtin::BI__builtin_expect:
9096 return Visit(E->getArg(0));
9097
9098 case Builtin::BI__builtin_ffs:
9099 case Builtin::BI__builtin_ffsl:
9100 case Builtin::BI__builtin_ffsll: {
9101 APSInt Val;
9102 if (!EvaluateInteger(E->getArg(0), Val, Info))
9103 return false;
9104
9105 unsigned N = Val.countTrailingZeros();
9106 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
9107 }
9108
9109 case Builtin::BI__builtin_fpclassify: {
9110 APFloat Val(0.0);
9111 if (!EvaluateFloat(E->getArg(5), Val, Info))
9112 return false;
9113 unsigned Arg;
9114 switch (Val.getCategory()) {
9115 case APFloat::fcNaN: Arg = 0; break;
9116 case APFloat::fcInfinity: Arg = 1; break;
9117 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
9118 case APFloat::fcZero: Arg = 4; break;
9119 }
9120 return Visit(E->getArg(Arg));
9121 }
9122
9123 case Builtin::BI__builtin_isinf_sign: {
9124 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00009125 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00009126 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
9127 }
9128
Richard Smithea3019d2013-10-15 19:07:14 +00009129 case Builtin::BI__builtin_isinf: {
9130 APFloat Val(0.0);
9131 return EvaluateFloat(E->getArg(0), Val, Info) &&
9132 Success(Val.isInfinity() ? 1 : 0, E);
9133 }
9134
9135 case Builtin::BI__builtin_isfinite: {
9136 APFloat Val(0.0);
9137 return EvaluateFloat(E->getArg(0), Val, Info) &&
9138 Success(Val.isFinite() ? 1 : 0, E);
9139 }
9140
9141 case Builtin::BI__builtin_isnan: {
9142 APFloat Val(0.0);
9143 return EvaluateFloat(E->getArg(0), Val, Info) &&
9144 Success(Val.isNaN() ? 1 : 0, E);
9145 }
9146
9147 case Builtin::BI__builtin_isnormal: {
9148 APFloat Val(0.0);
9149 return EvaluateFloat(E->getArg(0), Val, Info) &&
9150 Success(Val.isNormal() ? 1 : 0, E);
9151 }
9152
Richard Smith8889a3d2013-06-13 06:26:32 +00009153 case Builtin::BI__builtin_parity:
9154 case Builtin::BI__builtin_parityl:
9155 case Builtin::BI__builtin_parityll: {
9156 APSInt Val;
9157 if (!EvaluateInteger(E->getArg(0), Val, Info))
9158 return false;
9159
9160 return Success(Val.countPopulation() % 2, E);
9161 }
9162
Richard Smith80b3c8e2013-06-13 05:04:16 +00009163 case Builtin::BI__builtin_popcount:
9164 case Builtin::BI__builtin_popcountl:
9165 case Builtin::BI__builtin_popcountll: {
9166 APSInt Val;
9167 if (!EvaluateInteger(E->getArg(0), Val, Info))
9168 return false;
9169
9170 return Success(Val.countPopulation(), E);
9171 }
9172
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009173 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00009174 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00009175 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009176 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009177 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00009178 << /*isConstexpr*/0 << /*isConstructor*/0
9179 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00009180 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00009181 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009182 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00009183 case Builtin::BI__builtin_strlen:
9184 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00009185 // As an extension, we support __builtin_strlen() as a constant expression,
9186 // and support folding strlen() to a constant.
9187 LValue String;
9188 if (!EvaluatePointer(E->getArg(0), String, Info))
9189 return false;
9190
Richard Smith8110c9d2016-11-29 19:45:17 +00009191 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
9192
Richard Smithe6c19f22013-11-15 02:10:04 +00009193 // Fast path: if it's a string literal, search the string value.
9194 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
9195 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009196 // The string literal may have embedded null characters. Find the first
9197 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00009198 StringRef Str = S->getBytes();
9199 int64_t Off = String.Offset.getQuantity();
9200 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00009201 S->getCharByteWidth() == 1 &&
9202 // FIXME: Add fast-path for wchar_t too.
9203 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00009204 Str = Str.substr(Off);
9205
9206 StringRef::size_type Pos = Str.find(0);
9207 if (Pos != StringRef::npos)
9208 Str = Str.substr(0, Pos);
9209
9210 return Success(Str.size(), E);
9211 }
9212
9213 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009214 }
Richard Smithe6c19f22013-11-15 02:10:04 +00009215
9216 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00009217 for (uint64_t Strlen = 0; /**/; ++Strlen) {
9218 APValue Char;
9219 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9220 !Char.isInt())
9221 return false;
9222 if (!Char.getInt())
9223 return Success(Strlen, E);
9224 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9225 return false;
9226 }
9227 }
Eli Friedmana4c26022011-10-17 21:44:23 +00009228
Richard Smithe151bab2016-11-11 23:43:35 +00009229 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009230 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009231 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009232 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009233 case Builtin::BImemcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00009234 case Builtin::BIbcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009235 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009236 // A call to strlen is not a constant expression.
9237 if (Info.getLangOpts().CPlusPlus11)
9238 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9239 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00009240 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00009241 else
9242 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009243 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00009244 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009245 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009246 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009247 case Builtin::BI__builtin_wcsncmp:
9248 case Builtin::BI__builtin_memcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00009249 case Builtin::BI__builtin_bcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009250 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00009251 LValue String1, String2;
9252 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9253 !EvaluatePointer(E->getArg(1), String2, Info))
9254 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00009255
Richard Smithe151bab2016-11-11 23:43:35 +00009256 uint64_t MaxLength = uint64_t(-1);
9257 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00009258 BuiltinOp != Builtin::BIwcscmp &&
9259 BuiltinOp != Builtin::BI__builtin_strcmp &&
9260 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00009261 APSInt N;
9262 if (!EvaluateInteger(E->getArg(2), N, Info))
9263 return false;
9264 MaxLength = N.getExtValue();
9265 }
Hubert Tong147b7432018-12-12 16:53:43 +00009266
9267 // Empty substrings compare equal by definition.
9268 if (MaxLength == 0u)
9269 return Success(0, E);
9270
9271 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9272 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9273 String1.Designator.Invalid || String2.Designator.Invalid)
9274 return false;
9275
9276 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9277 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9278
9279 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
Clement Courbet8c3343d2019-02-14 12:00:34 +00009280 BuiltinOp == Builtin::BIbcmp ||
9281 BuiltinOp == Builtin::BI__builtin_memcmp ||
9282 BuiltinOp == Builtin::BI__builtin_bcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00009283
9284 assert(IsRawByte ||
9285 (Info.Ctx.hasSameUnqualifiedType(
9286 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9287 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9288
9289 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9290 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9291 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9292 Char1.isInt() && Char2.isInt();
9293 };
9294 const auto &AdvanceElems = [&] {
9295 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9296 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9297 };
9298
9299 if (IsRawByte) {
9300 uint64_t BytesRemaining = MaxLength;
9301 // Pointers to const void may point to objects of incomplete type.
9302 if (CharTy1->isIncompleteType()) {
9303 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9304 return false;
9305 }
9306 if (CharTy2->isIncompleteType()) {
9307 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9308 return false;
9309 }
9310 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9311 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9312 // Give up on comparing between elements with disparate widths.
9313 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9314 return false;
9315 uint64_t BytesPerElement = CharTy1Size.getQuantity();
9316 assert(BytesRemaining && "BytesRemaining should not be zero: the "
9317 "following loop considers at least one element");
9318 while (true) {
9319 APValue Char1, Char2;
9320 if (!ReadCurElems(Char1, Char2))
9321 return false;
9322 // We have compatible in-memory widths, but a possible type and
9323 // (for `bool`) internal representation mismatch.
9324 // Assuming two's complement representation, including 0 for `false` and
9325 // 1 for `true`, we can check an appropriate number of elements for
9326 // equality even if they are not byte-sized.
9327 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9328 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9329 if (Char1InMem.ne(Char2InMem)) {
9330 // If the elements are byte-sized, then we can produce a three-way
9331 // comparison result in a straightforward manner.
9332 if (BytesPerElement == 1u) {
9333 // memcmp always compares unsigned chars.
9334 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9335 }
9336 // The result is byte-order sensitive, and we have multibyte elements.
9337 // FIXME: We can compare the remaining bytes in the correct order.
9338 return false;
9339 }
9340 if (!AdvanceElems())
9341 return false;
9342 if (BytesRemaining <= BytesPerElement)
9343 break;
9344 BytesRemaining -= BytesPerElement;
9345 }
9346 // Enough elements are equal to account for the memcmp limit.
9347 return Success(0, E);
9348 }
9349
Clement Courbet8c3343d2019-02-14 12:00:34 +00009350 bool StopAtNull =
9351 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9352 BuiltinOp != Builtin::BIwmemcmp &&
9353 BuiltinOp != Builtin::BI__builtin_memcmp &&
9354 BuiltinOp != Builtin::BI__builtin_bcmp &&
9355 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00009356 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9357 BuiltinOp == Builtin::BIwcsncmp ||
9358 BuiltinOp == Builtin::BIwmemcmp ||
9359 BuiltinOp == Builtin::BI__builtin_wcscmp ||
9360 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9361 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00009362
Richard Smithe151bab2016-11-11 23:43:35 +00009363 for (; MaxLength; --MaxLength) {
9364 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +00009365 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +00009366 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00009367 if (Char1.getInt() != Char2.getInt()) {
9368 if (IsWide) // wmemcmp compares with wchar_t signedness.
9369 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9370 // memcmp always compares unsigned chars.
9371 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9372 }
Richard Smithe151bab2016-11-11 23:43:35 +00009373 if (StopAtNull && !Char1.getInt())
9374 return Success(0, E);
9375 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +00009376 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +00009377 return false;
9378 }
9379 // We hit the strncmp / memcmp limit.
9380 return Success(0, E);
9381 }
9382
Richard Smith01ba47d2012-04-13 00:45:38 +00009383 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00009384 case Builtin::BI__atomic_is_lock_free:
9385 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00009386 APSInt SizeVal;
9387 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9388 return false;
9389
9390 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9391 // of two less than the maximum inline atomic width, we know it is
9392 // lock-free. If the size isn't a power of two, or greater than the
9393 // maximum alignment where we promote atomics, we know it is not lock-free
9394 // (at least not in the sense of atomic_is_lock_free). Otherwise,
9395 // the answer can only be determined at runtime; for example, 16-byte
9396 // atomics have lock-free implementations on some, but not all,
9397 // x86-64 processors.
9398
9399 // Check power-of-two.
9400 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00009401 if (Size.isPowerOfTwo()) {
9402 // Check against inlining width.
9403 unsigned InlineWidthBits =
9404 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9405 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9406 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9407 Size == CharUnits::One() ||
9408 E->getArg(1)->isNullPointerConstant(Info.Ctx,
9409 Expr::NPC_NeverValueDependent))
9410 // OK, we will inline appropriately-aligned operations of this size,
9411 // and _Atomic(T) is appropriately-aligned.
9412 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00009413
Richard Smith01ba47d2012-04-13 00:45:38 +00009414 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9415 castAs<PointerType>()->getPointeeType();
9416 if (!PointeeType->isIncompleteType() &&
9417 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9418 // OK, we will inline operations on this object.
9419 return Success(1, E);
9420 }
9421 }
9422 }
Eli Friedmana4c26022011-10-17 21:44:23 +00009423
Richard Smith01ba47d2012-04-13 00:45:38 +00009424 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9425 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00009426 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00009427 case Builtin::BIomp_is_initial_device:
9428 // We can decide statically which value the runtime would return if called.
9429 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00009430 case Builtin::BI__builtin_add_overflow:
9431 case Builtin::BI__builtin_sub_overflow:
9432 case Builtin::BI__builtin_mul_overflow:
9433 case Builtin::BI__builtin_sadd_overflow:
9434 case Builtin::BI__builtin_uadd_overflow:
9435 case Builtin::BI__builtin_uaddl_overflow:
9436 case Builtin::BI__builtin_uaddll_overflow:
9437 case Builtin::BI__builtin_usub_overflow:
9438 case Builtin::BI__builtin_usubl_overflow:
9439 case Builtin::BI__builtin_usubll_overflow:
9440 case Builtin::BI__builtin_umul_overflow:
9441 case Builtin::BI__builtin_umull_overflow:
9442 case Builtin::BI__builtin_umulll_overflow:
9443 case Builtin::BI__builtin_saddl_overflow:
9444 case Builtin::BI__builtin_saddll_overflow:
9445 case Builtin::BI__builtin_ssub_overflow:
9446 case Builtin::BI__builtin_ssubl_overflow:
9447 case Builtin::BI__builtin_ssubll_overflow:
9448 case Builtin::BI__builtin_smul_overflow:
9449 case Builtin::BI__builtin_smull_overflow:
9450 case Builtin::BI__builtin_smulll_overflow: {
9451 LValue ResultLValue;
9452 APSInt LHS, RHS;
9453
9454 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9455 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9456 !EvaluateInteger(E->getArg(1), RHS, Info) ||
9457 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9458 return false;
9459
9460 APSInt Result;
9461 bool DidOverflow = false;
9462
9463 // If the types don't have to match, enlarge all 3 to the largest of them.
9464 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9465 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9466 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9467 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9468 ResultType->isSignedIntegerOrEnumerationType();
9469 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9470 ResultType->isSignedIntegerOrEnumerationType();
9471 uint64_t LHSSize = LHS.getBitWidth();
9472 uint64_t RHSSize = RHS.getBitWidth();
9473 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9474 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9475
9476 // Add an additional bit if the signedness isn't uniformly agreed to. We
9477 // could do this ONLY if there is a signed and an unsigned that both have
9478 // MaxBits, but the code to check that is pretty nasty. The issue will be
9479 // caught in the shrink-to-result later anyway.
9480 if (IsSigned && !AllSigned)
9481 ++MaxBits;
9482
Erich Keanefc3dfd32019-05-30 21:35:32 +00009483 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
9484 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
Erich Keane00958272018-06-13 20:43:27 +00009485 Result = APSInt(MaxBits, !IsSigned);
9486 }
9487
9488 // Find largest int.
9489 switch (BuiltinOp) {
9490 default:
9491 llvm_unreachable("Invalid value for BuiltinOp");
9492 case Builtin::BI__builtin_add_overflow:
9493 case Builtin::BI__builtin_sadd_overflow:
9494 case Builtin::BI__builtin_saddl_overflow:
9495 case Builtin::BI__builtin_saddll_overflow:
9496 case Builtin::BI__builtin_uadd_overflow:
9497 case Builtin::BI__builtin_uaddl_overflow:
9498 case Builtin::BI__builtin_uaddll_overflow:
9499 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
9500 : LHS.uadd_ov(RHS, DidOverflow);
9501 break;
9502 case Builtin::BI__builtin_sub_overflow:
9503 case Builtin::BI__builtin_ssub_overflow:
9504 case Builtin::BI__builtin_ssubl_overflow:
9505 case Builtin::BI__builtin_ssubll_overflow:
9506 case Builtin::BI__builtin_usub_overflow:
9507 case Builtin::BI__builtin_usubl_overflow:
9508 case Builtin::BI__builtin_usubll_overflow:
9509 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
9510 : LHS.usub_ov(RHS, DidOverflow);
9511 break;
9512 case Builtin::BI__builtin_mul_overflow:
9513 case Builtin::BI__builtin_smul_overflow:
9514 case Builtin::BI__builtin_smull_overflow:
9515 case Builtin::BI__builtin_smulll_overflow:
9516 case Builtin::BI__builtin_umul_overflow:
9517 case Builtin::BI__builtin_umull_overflow:
9518 case Builtin::BI__builtin_umulll_overflow:
9519 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
9520 : LHS.umul_ov(RHS, DidOverflow);
9521 break;
9522 }
9523
9524 // In the case where multiple sizes are allowed, truncate and see if
9525 // the values are the same.
9526 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9527 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9528 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9529 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
9530 // since it will give us the behavior of a TruncOrSelf in the case where
9531 // its parameter <= its size. We previously set Result to be at least the
9532 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
9533 // will work exactly like TruncOrSelf.
9534 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
9535 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
9536
9537 if (!APSInt::isSameValue(Temp, Result))
9538 DidOverflow = true;
9539 Result = Temp;
9540 }
9541
9542 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +00009543 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
9544 return false;
Erich Keane00958272018-06-13 20:43:27 +00009545 return Success(DidOverflow, E);
9546 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009547 }
Chris Lattner7174bf32008-07-12 00:38:25 +00009548}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009549
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009550/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +00009551/// object referred to by the lvalue.
9552static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
9553 const LValue &LV) {
9554 // A null pointer can be viewed as being "past the end" but we don't
9555 // choose to look at it that way here.
9556 if (!LV.getLValueBase())
9557 return false;
9558
9559 // If the designator is valid and refers to a subobject, we're not pointing
9560 // past the end.
9561 if (!LV.getLValueDesignator().Invalid &&
9562 !LV.getLValueDesignator().isOnePastTheEnd())
9563 return false;
9564
David Majnemerc378ca52015-08-29 08:32:55 +00009565 // A pointer to an incomplete type might be past-the-end if the type's size is
9566 // zero. We cannot tell because the type is incomplete.
9567 QualType Ty = getType(LV.getLValueBase());
9568 if (Ty->isIncompleteType())
9569 return true;
9570
Richard Smithd20f1e62014-10-21 23:01:04 +00009571 // We're a past-the-end pointer if we point to the byte after the object,
9572 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00009573 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00009574 return LV.getLValueOffset() == Size;
9575}
9576
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009577namespace {
Richard Smith11562c52011-10-28 17:51:58 +00009578
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009579/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009580///
9581/// We use a data recursive algorithm for binary operators so that we are able
9582/// to handle extreme cases of chained binary operators without causing stack
9583/// overflow.
9584class DataRecursiveIntBinOpEvaluator {
9585 struct EvalResult {
9586 APValue Val;
9587 bool Failed;
9588
9589 EvalResult() : Failed(false) { }
9590
9591 void swap(EvalResult &RHS) {
9592 Val.swap(RHS.Val);
9593 Failed = RHS.Failed;
9594 RHS.Failed = false;
9595 }
9596 };
9597
9598 struct Job {
9599 const Expr *E;
9600 EvalResult LHSResult; // meaningful only for binary operator expression.
9601 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00009602
David Blaikie73726062015-08-12 23:09:24 +00009603 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00009604 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00009605
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009606 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00009607 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009608 }
George Burgess IV8c892b52016-05-25 22:31:54 +00009609
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009610 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00009611 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009612 };
9613
9614 SmallVector<Job, 16> Queue;
9615
9616 IntExprEvaluator &IntEval;
9617 EvalInfo &Info;
9618 APValue &FinalResult;
9619
9620public:
9621 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
9622 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
9623
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009624 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009625 /// data recursively.
9626 /// We handle binary operators that are comma, logical, or that have operands
9627 /// with integral or enumeration type.
9628 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009629 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
9630 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +00009631 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009632 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00009633 }
9634
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009635 bool Traverse(const BinaryOperator *E) {
9636 enqueue(E);
9637 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00009638 while (!Queue.empty())
9639 process(PrevResult);
9640
9641 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009642
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009643 FinalResult.swap(PrevResult.Val);
9644 return true;
9645 }
9646
9647private:
9648 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
9649 return IntEval.Success(Value, E, Result);
9650 }
9651 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
9652 return IntEval.Success(Value, E, Result);
9653 }
9654 bool Error(const Expr *E) {
9655 return IntEval.Error(E);
9656 }
9657 bool Error(const Expr *E, diag::kind D) {
9658 return IntEval.Error(E, D);
9659 }
9660
9661 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
9662 return Info.CCEDiag(E, D);
9663 }
9664
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009665 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009666 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009667 bool &SuppressRHSDiags);
9668
9669 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
9670 const BinaryOperator *E, APValue &Result);
9671
9672 void EvaluateExpr(const Expr *E, EvalResult &Result) {
9673 Result.Failed = !Evaluate(Result.Val, Info, E);
9674 if (Result.Failed)
9675 Result.Val = APValue();
9676 }
9677
Richard Trieuba4d0872012-03-21 23:30:30 +00009678 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009679
9680 void enqueue(const Expr *E) {
9681 E = E->IgnoreParens();
9682 Queue.resize(Queue.size()+1);
9683 Queue.back().E = E;
9684 Queue.back().Kind = Job::AnyExprKind;
9685 }
9686};
9687
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009688}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009689
9690bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009691 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009692 bool &SuppressRHSDiags) {
9693 if (E->getOpcode() == BO_Comma) {
9694 // Ignore LHS but note if we could not evaluate it.
9695 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00009696 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009697 return true;
9698 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00009699
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009700 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00009701 bool LHSAsBool;
9702 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009703 // We were able to evaluate the LHS, see if we can get away with not
9704 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00009705 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
9706 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009707 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009708 }
9709 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00009710 LHSResult.Failed = true;
9711
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009712 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00009713 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00009714 if (!Info.noteSideEffect())
9715 return false;
9716
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009717 // We can't evaluate the LHS; however, sometimes the result
9718 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9719 // Don't ignore RHS and suppress diagnostics from this arm.
9720 SuppressRHSDiags = true;
9721 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00009722
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009723 return true;
9724 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00009725
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009726 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9727 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00009728
George Burgess IVa145e252016-05-25 22:38:36 +00009729 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009730 return false; // Ignore RHS;
9731
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009732 return true;
9733}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009734
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00009735static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
9736 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00009737 // Compute the new offset in the appropriate width, wrapping at 64 bits.
9738 // FIXME: When compiling for a 32-bit target, we should use 32-bit
9739 // offsets.
9740 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
9741 CharUnits &Offset = LVal.getLValueOffset();
9742 uint64_t Offset64 = Offset.getQuantity();
9743 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
9744 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
9745 : Offset64 + Index64);
9746}
9747
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009748bool DataRecursiveIntBinOpEvaluator::
9749 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
9750 const BinaryOperator *E, APValue &Result) {
9751 if (E->getOpcode() == BO_Comma) {
9752 if (RHSResult.Failed)
9753 return false;
9754 Result = RHSResult.Val;
9755 return true;
9756 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009757
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009758 if (E->isLogicalOp()) {
9759 bool lhsResult, rhsResult;
9760 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
9761 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +00009762
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009763 if (LHSIsOK) {
9764 if (RHSIsOK) {
9765 if (E->getOpcode() == BO_LOr)
9766 return Success(lhsResult || rhsResult, E, Result);
9767 else
9768 return Success(lhsResult && rhsResult, E, Result);
9769 }
9770 } else {
9771 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009772 // We can't evaluate the LHS; however, sometimes the result
9773 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9774 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009775 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009776 }
9777 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009778
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009779 return false;
9780 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009781
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009782 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9783 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +00009784
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009785 if (LHSResult.Failed || RHSResult.Failed)
9786 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009787
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009788 const APValue &LHSVal = LHSResult.Val;
9789 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +00009790
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009791 // Handle cases like (unsigned long)&a + 4.
9792 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
9793 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00009794 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009795 return true;
9796 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009797
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009798 // Handle cases like 4 + (unsigned long)&a
9799 if (E->getOpcode() == BO_Add &&
9800 RHSVal.isLValue() && LHSVal.isInt()) {
9801 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00009802 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009803 return true;
9804 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009805
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009806 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
9807 // Handle (intptr_t)&&A - (intptr_t)&&B.
9808 if (!LHSVal.getLValueOffset().isZero() ||
9809 !RHSVal.getLValueOffset().isZero())
9810 return false;
9811 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
9812 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
9813 if (!LHSExpr || !RHSExpr)
9814 return false;
9815 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9816 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9817 if (!LHSAddrExpr || !RHSAddrExpr)
9818 return false;
9819 // Make sure both labels come from the same function.
9820 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9821 RHSAddrExpr->getLabel()->getDeclContext())
9822 return false;
9823 Result = APValue(LHSAddrExpr, RHSAddrExpr);
9824 return true;
9825 }
Richard Smith43e77732013-05-07 04:50:00 +00009826
9827 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009828 if (!LHSVal.isInt() || !RHSVal.isInt())
9829 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00009830
9831 // Set up the width and signedness manually, in case it can't be deduced
9832 // from the operation we're performing.
9833 // FIXME: Don't do this in the cases where we can deduce it.
9834 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
9835 E->getType()->isUnsignedIntegerOrEnumerationType());
9836 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
9837 RHSVal.getInt(), Value))
9838 return false;
9839 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009840}
9841
Richard Trieuba4d0872012-03-21 23:30:30 +00009842void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009843 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +00009844
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009845 switch (job.Kind) {
9846 case Job::AnyExprKind: {
9847 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
9848 if (shouldEnqueue(Bop)) {
9849 job.Kind = Job::BinOpKind;
9850 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009851 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009852 }
9853 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009854
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009855 EvaluateExpr(job.E, Result);
9856 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009857 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009858 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009859
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009860 case Job::BinOpKind: {
9861 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009862 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009863 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009864 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009865 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009866 }
9867 if (SuppressRHSDiags)
9868 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009869 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009870 job.Kind = Job::BinOpVisitedLHSKind;
9871 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009872 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009873 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009874
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009875 case Job::BinOpVisitedLHSKind: {
9876 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9877 EvalResult RHS;
9878 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00009879 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009880 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009881 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009882 }
9883 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009884
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009885 llvm_unreachable("Invalid Job::Kind!");
9886}
9887
George Burgess IV8c892b52016-05-25 22:31:54 +00009888namespace {
9889/// Used when we determine that we should fail, but can keep evaluating prior to
9890/// noting that we had a failure.
9891class DelayedNoteFailureRAII {
9892 EvalInfo &Info;
9893 bool NoteFailure;
9894
9895public:
9896 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
9897 : Info(Info), NoteFailure(NoteFailure) {}
9898 ~DelayedNoteFailureRAII() {
9899 if (NoteFailure) {
9900 bool ContinueAfterFailure = Info.noteFailure();
9901 (void)ContinueAfterFailure;
9902 assert(ContinueAfterFailure &&
9903 "Shouldn't have kept evaluating on failure.");
9904 }
9905 }
9906};
9907}
9908
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009909template <class SuccessCB, class AfterCB>
9910static bool
9911EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
9912 SuccessCB &&Success, AfterCB &&DoAfter) {
9913 assert(E->isComparisonOp() && "expected comparison operator");
9914 assert((E->getOpcode() == BO_Cmp ||
9915 E->getType()->isIntegralOrEnumerationType()) &&
9916 "unsupported binary expression evaluation");
9917 auto Error = [&](const Expr *E) {
9918 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9919 return false;
9920 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009921
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009922 using CCR = ComparisonCategoryResult;
9923 bool IsRelational = E->isRelationalOp();
9924 bool IsEquality = E->isEqualityOp();
9925 if (E->getOpcode() == BO_Cmp) {
9926 const ComparisonCategoryInfo &CmpInfo =
9927 Info.Ctx.CompCategories.getInfoForType(E->getType());
9928 IsRelational = CmpInfo.isOrdered();
9929 IsEquality = CmpInfo.isEquality();
9930 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00009931
Anders Carlssonacc79812008-11-16 07:17:21 +00009932 QualType LHSTy = E->getLHS()->getType();
9933 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009934
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009935 if (LHSTy->isIntegralOrEnumerationType() &&
9936 RHSTy->isIntegralOrEnumerationType()) {
9937 APSInt LHS, RHS;
9938 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
9939 if (!LHSOK && !Info.noteFailure())
9940 return false;
9941 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
9942 return false;
9943 if (LHS < RHS)
9944 return Success(CCR::Less, E);
9945 if (LHS > RHS)
9946 return Success(CCR::Greater, E);
9947 return Success(CCR::Equal, E);
9948 }
9949
Leonard Chance1d4f12019-02-21 20:50:09 +00009950 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
9951 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
9952 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
9953
9954 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
9955 if (!LHSOK && !Info.noteFailure())
9956 return false;
9957 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
9958 return false;
9959 if (LHSFX < RHSFX)
9960 return Success(CCR::Less, E);
9961 if (LHSFX > RHSFX)
9962 return Success(CCR::Greater, E);
9963 return Success(CCR::Equal, E);
9964 }
9965
Chandler Carruthb29a7432014-10-11 11:03:30 +00009966 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009967 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00009968 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00009969 if (E->isAssignmentOp()) {
9970 LValue LV;
9971 EvaluateLValue(E->getLHS(), LV, Info);
9972 LHSOK = false;
9973 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00009974 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
9975 if (LHSOK) {
9976 LHS.makeComplexFloat();
9977 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
9978 }
9979 } else {
9980 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
9981 }
George Burgess IVa145e252016-05-25 22:38:36 +00009982 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009983 return false;
9984
Chandler Carruthb29a7432014-10-11 11:03:30 +00009985 if (E->getRHS()->getType()->isRealFloatingType()) {
9986 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
9987 return false;
9988 RHS.makeComplexFloat();
9989 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
9990 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009991 return false;
9992
9993 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00009994 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009995 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00009996 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009997 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009998 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9999 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010000 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010001 assert(IsEquality && "invalid complex comparison");
10002 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
10003 LHS.getComplexIntImag() == RHS.getComplexIntImag();
10004 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010005 }
10006 }
Mike Stump11289f42009-09-09 15:08:12 +000010007
Anders Carlssonacc79812008-11-16 07:17:21 +000010008 if (LHSTy->isRealFloatingType() &&
10009 RHSTy->isRealFloatingType()) {
10010 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +000010011
Richard Smith253c2a32012-01-27 01:14:48 +000010012 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010013 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +000010014 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010015
Richard Smith253c2a32012-01-27 01:14:48 +000010016 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +000010017 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010018
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010019 assert(E->isComparisonOp() && "Invalid binary operator!");
10020 auto GetCmpRes = [&]() {
10021 switch (LHS.compare(RHS)) {
10022 case APFloat::cmpEqual:
10023 return CCR::Equal;
10024 case APFloat::cmpLessThan:
10025 return CCR::Less;
10026 case APFloat::cmpGreaterThan:
10027 return CCR::Greater;
10028 case APFloat::cmpUnordered:
10029 return CCR::Unordered;
10030 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +000010031 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010032 };
10033 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +000010034 }
Mike Stump11289f42009-09-09 15:08:12 +000010035
Eli Friedmana38da572009-04-28 19:17:36 +000010036 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010037 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +000010038
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010039 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10040 if (!LHSOK && !Info.noteFailure())
10041 return false;
Eli Friedman64004332009-03-23 04:38:34 +000010042
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010043 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10044 return false;
Eli Friedman64004332009-03-23 04:38:34 +000010045
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010046 // Reject differing bases from the normal codepath; we special-case
10047 // comparisons to null.
10048 if (!HasSameBase(LHSValue, RHSValue)) {
10049 // Inequalities and subtractions between unrelated pointers have
10050 // unspecified or undefined behavior.
10051 if (!IsEquality)
10052 return Error(E);
10053 // A constant address may compare equal to the address of a symbol.
10054 // The one exception is that address of an object cannot compare equal
10055 // to a null pointer constant.
10056 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
10057 (!RHSValue.Base && !RHSValue.Offset.isZero()))
10058 return Error(E);
10059 // It's implementation-defined whether distinct literals will have
10060 // distinct addresses. In clang, the result of such a comparison is
10061 // unspecified, so it is not a constant expression. However, we do know
10062 // that the address of a literal will be non-null.
10063 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
10064 LHSValue.Base && RHSValue.Base)
10065 return Error(E);
10066 // We can't tell whether weak symbols will end up pointing to the same
10067 // object.
10068 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
10069 return Error(E);
10070 // We can't compare the address of the start of one object with the
10071 // past-the-end address of another object, per C++ DR1652.
10072 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
10073 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
10074 (RHSValue.Base && RHSValue.Offset.isZero() &&
10075 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
10076 return Error(E);
10077 // We can't tell whether an object is at the same address as another
10078 // zero sized object.
10079 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
10080 (LHSValue.Base && isZeroSized(RHSValue)))
10081 return Error(E);
10082 return Success(CCR::Nonequal, E);
10083 }
Eli Friedman64004332009-03-23 04:38:34 +000010084
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010085 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10086 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +000010087
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010088 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10089 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +000010090
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010091 // C++11 [expr.rel]p3:
10092 // Pointers to void (after pointer conversions) can be compared, with a
10093 // result defined as follows: If both pointers represent the same
10094 // address or are both the null pointer value, the result is true if the
10095 // operator is <= or >= and false otherwise; otherwise the result is
10096 // unspecified.
10097 // We interpret this as applying to pointers to *cv* void.
10098 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
10099 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +000010100
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010101 // C++11 [expr.rel]p2:
10102 // - If two pointers point to non-static data members of the same object,
10103 // or to subobjects or array elements fo such members, recursively, the
10104 // pointer to the later declared member compares greater provided the
10105 // two members have the same access control and provided their class is
10106 // not a union.
10107 // [...]
10108 // - Otherwise pointer comparisons are unspecified.
10109 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
10110 bool WasArrayIndex;
10111 unsigned Mismatch = FindDesignatorMismatch(
10112 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
10113 // At the point where the designators diverge, the comparison has a
10114 // specified value if:
10115 // - we are comparing array indices
10116 // - we are comparing fields of a union, or fields with the same access
10117 // Otherwise, the result is unspecified and thus the comparison is not a
10118 // constant expression.
10119 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
10120 Mismatch < RHSDesignator.Entries.size()) {
10121 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
10122 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
10123 if (!LF && !RF)
10124 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
10125 else if (!LF)
10126 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010127 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
10128 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010129 else if (!RF)
10130 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010131 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
10132 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010133 else if (!LF->getParent()->isUnion() &&
10134 LF->getAccess() != RF->getAccess())
10135 Info.CCEDiag(E,
10136 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010137 << LF << LF->getAccess() << RF << RF->getAccess()
10138 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +000010139 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +000010140 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010141
10142 // The comparison here must be unsigned, and performed with the same
10143 // width as the pointer.
10144 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
10145 uint64_t CompareLHS = LHSOffset.getQuantity();
10146 uint64_t CompareRHS = RHSOffset.getQuantity();
10147 assert(PtrSize <= 64 && "Unexpected pointer width");
10148 uint64_t Mask = ~0ULL >> (64 - PtrSize);
10149 CompareLHS &= Mask;
10150 CompareRHS &= Mask;
10151
10152 // If there is a base and this is a relational operator, we can only
10153 // compare pointers within the object in question; otherwise, the result
10154 // depends on where the object is located in memory.
10155 if (!LHSValue.Base.isNull() && IsRelational) {
10156 QualType BaseTy = getType(LHSValue.Base);
10157 if (BaseTy->isIncompleteType())
10158 return Error(E);
10159 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
10160 uint64_t OffsetLimit = Size.getQuantity();
10161 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
10162 return Error(E);
10163 }
10164
10165 if (CompareLHS < CompareRHS)
10166 return Success(CCR::Less, E);
10167 if (CompareLHS > CompareRHS)
10168 return Success(CCR::Greater, E);
10169 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +000010170 }
Richard Smith7bb00672012-02-01 01:42:44 +000010171
10172 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010173 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +000010174 assert(RHSTy->isMemberPointerType() && "invalid comparison");
10175
10176 MemberPtr LHSValue, RHSValue;
10177
10178 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010179 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +000010180 return false;
10181
10182 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10183 return false;
10184
10185 // C++11 [expr.eq]p2:
10186 // If both operands are null, they compare equal. Otherwise if only one is
10187 // null, they compare unequal.
10188 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
10189 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010190 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000010191 }
10192
10193 // Otherwise if either is a pointer to a virtual member function, the
10194 // result is unspecified.
10195 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
10196 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010197 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000010198 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
10199 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010200 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000010201
10202 // Otherwise they compare equal if and only if they would refer to the
10203 // same member of the same most derived object or the same subobject if
10204 // they were dereferenced with a hypothetical object of the associated
10205 // class type.
10206 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010207 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000010208 }
10209
Richard Smithab44d9b2012-02-14 22:35:28 +000010210 if (LHSTy->isNullPtrType()) {
10211 assert(E->isComparisonOp() && "unexpected nullptr operation");
10212 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10213 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10214 // are compared, the result is true of the operator is <=, >= or ==, and
10215 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010216 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +000010217 }
10218
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010219 return DoAfter();
10220}
10221
10222bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10223 if (!CheckLiteralType(Info, E))
10224 return false;
10225
10226 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10227 const BinaryOperator *E) {
10228 // Evaluation succeeded. Lookup the information for the comparison category
10229 // type and fetch the VarDecl for the result.
10230 const ComparisonCategoryInfo &CmpInfo =
10231 Info.Ctx.CompCategories.getInfoForType(E->getType());
10232 const VarDecl *VD =
10233 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10234 // Check and evaluate the result as a constant expression.
10235 LValue LV;
10236 LV.set(VD);
10237 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10238 return false;
10239 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10240 };
10241 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10242 return ExprEvaluatorBaseTy::VisitBinCmp(E);
10243 });
10244}
10245
10246bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10247 // We don't call noteFailure immediately because the assignment happens after
10248 // we evaluate LHS and RHS.
10249 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10250 return Error(E);
10251
10252 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10253 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10254 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10255
10256 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10257 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010258 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010259
10260 if (E->isComparisonOp()) {
10261 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10262 // comparisons and then translating the result.
10263 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10264 const BinaryOperator *E) {
10265 using CCR = ComparisonCategoryResult;
10266 bool IsEqual = ResKind == CCR::Equal,
10267 IsLess = ResKind == CCR::Less,
10268 IsGreater = ResKind == CCR::Greater;
10269 auto Op = E->getOpcode();
10270 switch (Op) {
10271 default:
10272 llvm_unreachable("unsupported binary operator");
10273 case BO_EQ:
10274 case BO_NE:
10275 return Success(IsEqual == (Op == BO_EQ), E);
10276 case BO_LT: return Success(IsLess, E);
10277 case BO_GT: return Success(IsGreater, E);
10278 case BO_LE: return Success(IsEqual || IsLess, E);
10279 case BO_GE: return Success(IsEqual || IsGreater, E);
10280 }
10281 };
10282 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10283 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10284 });
10285 }
10286
10287 QualType LHSTy = E->getLHS()->getType();
10288 QualType RHSTy = E->getRHS()->getType();
10289
10290 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10291 E->getOpcode() == BO_Sub) {
10292 LValue LHSValue, RHSValue;
10293
10294 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10295 if (!LHSOK && !Info.noteFailure())
10296 return false;
10297
10298 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10299 return false;
10300
10301 // Reject differing bases from the normal codepath; we special-case
10302 // comparisons to null.
10303 if (!HasSameBase(LHSValue, RHSValue)) {
10304 // Handle &&A - &&B.
10305 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10306 return Error(E);
10307 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10308 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10309 if (!LHSExpr || !RHSExpr)
10310 return Error(E);
10311 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10312 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10313 if (!LHSAddrExpr || !RHSAddrExpr)
10314 return Error(E);
10315 // Make sure both labels come from the same function.
10316 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10317 RHSAddrExpr->getLabel()->getDeclContext())
10318 return Error(E);
10319 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10320 }
10321 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10322 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10323
10324 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10325 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10326
10327 // C++11 [expr.add]p6:
10328 // Unless both pointers point to elements of the same array object, or
10329 // one past the last element of the array object, the behavior is
10330 // undefined.
10331 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10332 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10333 RHSDesignator))
10334 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10335
10336 QualType Type = E->getLHS()->getType();
10337 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10338
10339 CharUnits ElementSize;
10340 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10341 return false;
10342
10343 // As an extension, a type may have zero size (empty struct or union in
10344 // C, array of zero length). Pointer subtraction in such cases has
10345 // undefined behavior, so is not constant.
10346 if (ElementSize.isZero()) {
10347 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10348 << ElementType;
10349 return false;
10350 }
10351
10352 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10353 // and produce incorrect results when it overflows. Such behavior
10354 // appears to be non-conforming, but is common, so perhaps we should
10355 // assume the standard intended for such cases to be undefined behavior
10356 // and check for them.
10357
10358 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10359 // overflow in the final conversion to ptrdiff_t.
10360 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10361 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10362 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10363 false);
10364 APSInt TrueResult = (LHS - RHS) / ElemSize;
10365 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
10366
10367 if (Result.extend(65) != TrueResult &&
10368 !HandleOverflow(Info, E, TrueResult, E->getType()))
10369 return false;
10370 return Success(Result, E);
10371 }
10372
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010373 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +000010374}
10375
Peter Collingbournee190dee2011-03-11 19:24:49 +000010376/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10377/// a result as the expression's type.
10378bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10379 const UnaryExprOrTypeTraitExpr *E) {
10380 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +000010381 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +000010382 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +000010383 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +000010384 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10385 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000010386 else
Richard Smith6822bd72018-10-26 19:26:45 +000010387 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10388 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000010389 }
Eli Friedman64004332009-03-23 04:38:34 +000010390
Peter Collingbournee190dee2011-03-11 19:24:49 +000010391 case UETT_VecStep: {
10392 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +000010393
Peter Collingbournee190dee2011-03-11 19:24:49 +000010394 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +000010395 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +000010396
Peter Collingbournee190dee2011-03-11 19:24:49 +000010397 // The vec_step built-in functions that take a 3-component
10398 // vector return 4. (OpenCL 1.1 spec 6.11.12)
10399 if (n == 3)
10400 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +000010401
Peter Collingbournee190dee2011-03-11 19:24:49 +000010402 return Success(n, E);
10403 } else
10404 return Success(1, E);
10405 }
10406
10407 case UETT_SizeOf: {
10408 QualType SrcTy = E->getTypeOfArgument();
10409 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10410 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +000010411 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10412 SrcTy = Ref->getPointeeType();
10413
Richard Smithd62306a2011-11-10 06:34:14 +000010414 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +000010415 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +000010416 return false;
Richard Smithd62306a2011-11-10 06:34:14 +000010417 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000010418 }
Alexey Bataev00396512015-07-02 03:40:19 +000010419 case UETT_OpenMPRequiredSimdAlign:
10420 assert(E->isArgumentType());
10421 return Success(
10422 Info.Ctx.toCharUnitsFromBits(
10423 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10424 .getQuantity(),
10425 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000010426 }
10427
10428 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +000010429}
10430
Peter Collingbournee9200682011-05-13 03:29:01 +000010431bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +000010432 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +000010433 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +000010434 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010435 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +000010436 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +000010437 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +000010438 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +000010439 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +000010440 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +000010441 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +000010442 APSInt IdxResult;
10443 if (!EvaluateInteger(Idx, IdxResult, Info))
10444 return false;
10445 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10446 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010447 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010448 CurrentType = AT->getElementType();
10449 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10450 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +000010451 break;
Douglas Gregor882211c2010-04-28 22:16:22 +000010452 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010453
James Y Knight7281c352015-12-29 22:31:18 +000010454 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +000010455 FieldDecl *MemberDecl = ON.getField();
10456 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000010457 if (!RT)
10458 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010459 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000010460 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +000010461 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +000010462 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +000010463 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +000010464 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +000010465 CurrentType = MemberDecl->getType().getNonReferenceType();
10466 break;
10467 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010468
James Y Knight7281c352015-12-29 22:31:18 +000010469 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +000010470 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +000010471
James Y Knight7281c352015-12-29 22:31:18 +000010472 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +000010473 CXXBaseSpecifier *BaseSpec = ON.getBase();
10474 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +000010475 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000010476
10477 // Find the layout of the class whose base we are looking into.
10478 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000010479 if (!RT)
10480 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000010481 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000010482 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +000010483 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10484
10485 // Find the base class itself.
10486 CurrentType = BaseSpec->getType();
10487 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10488 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010489 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +000010490
Douglas Gregord1702062010-04-29 00:18:15 +000010491 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +000010492 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +000010493 break;
10494 }
Douglas Gregor882211c2010-04-28 22:16:22 +000010495 }
10496 }
Peter Collingbournee9200682011-05-13 03:29:01 +000010497 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010498}
10499
Chris Lattnere13042c2008-07-11 19:10:17 +000010500bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010501 switch (E->getOpcode()) {
10502 default:
10503 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
10504 // See C99 6.6p3.
10505 return Error(E);
10506 case UO_Extension:
10507 // FIXME: Should extension allow i-c-e extension expressions in its scope?
10508 // If so, we could clear the diagnostic ID.
10509 return Visit(E->getSubExpr());
10510 case UO_Plus:
10511 // The result is just the value.
10512 return Visit(E->getSubExpr());
10513 case UO_Minus: {
10514 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +000010515 return false;
10516 if (!Result.isInt()) return Error(E);
10517 const APSInt &Value = Result.getInt();
10518 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
10519 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
10520 E->getType()))
10521 return false;
Richard Smithfe800032012-01-31 04:08:20 +000010522 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010523 }
10524 case UO_Not: {
10525 if (!Visit(E->getSubExpr()))
10526 return false;
10527 if (!Result.isInt()) return Error(E);
10528 return Success(~Result.getInt(), E);
10529 }
10530 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +000010531 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +000010532 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +000010533 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +000010534 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +000010535 }
Anders Carlsson9c181652008-07-08 14:35:21 +000010536 }
Anders Carlsson9c181652008-07-08 14:35:21 +000010537}
Mike Stump11289f42009-09-09 15:08:12 +000010538
Chris Lattner477c4be2008-07-12 01:15:53 +000010539/// HandleCast - This is used to evaluate implicit or explicit casts where the
10540/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +000010541bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
10542 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000010543 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +000010544 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000010545
Eli Friedmanc757de22011-03-25 00:43:55 +000010546 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +000010547 case CK_BaseToDerived:
10548 case CK_DerivedToBase:
10549 case CK_UncheckedDerivedToBase:
10550 case CK_Dynamic:
10551 case CK_ToUnion:
10552 case CK_ArrayToPointerDecay:
10553 case CK_FunctionToPointerDecay:
10554 case CK_NullToPointer:
10555 case CK_NullToMemberPointer:
10556 case CK_BaseToDerivedMemberPointer:
10557 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +000010558 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +000010559 case CK_ConstructorConversion:
10560 case CK_IntegralToPointer:
10561 case CK_ToVoid:
10562 case CK_VectorSplat:
10563 case CK_IntegralToFloating:
10564 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000010565 case CK_CPointerToObjCPointerCast:
10566 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000010567 case CK_AnyPointerToBlockPointerCast:
10568 case CK_ObjCObjectLValueCast:
10569 case CK_FloatingRealToComplex:
10570 case CK_FloatingComplexToReal:
10571 case CK_FloatingComplexCast:
10572 case CK_FloatingComplexToIntegralComplex:
10573 case CK_IntegralRealToComplex:
10574 case CK_IntegralComplexCast:
10575 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +000010576 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000010577 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000010578 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000010579 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000010580 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000010581 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +000010582 case CK_IntegralToFixedPoint:
Eli Friedmanc757de22011-03-25 00:43:55 +000010583 llvm_unreachable("invalid cast kind for integral value");
10584
Eli Friedman9faf2f92011-03-25 19:07:11 +000010585 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000010586 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000010587 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +000010588 case CK_ARCProduceObject:
10589 case CK_ARCConsumeObject:
10590 case CK_ARCReclaimReturnedObject:
10591 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000010592 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010593 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000010594
Richard Smith4ef685b2012-01-17 21:17:26 +000010595 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +000010596 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010597 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +000010598 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +000010599 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000010600
10601 case CK_MemberPointerToBoolean:
10602 case CK_PointerToBoolean:
10603 case CK_IntegralToBoolean:
10604 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +000010605 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +000010606 case CK_FloatingComplexToBoolean:
10607 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010608 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +000010609 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +000010610 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +000010611 uint64_t IntResult = BoolResult;
10612 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
10613 IntResult = (uint64_t)-1;
10614 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +000010615 }
10616
Leonard Chan8f7caae2019-03-06 00:28:43 +000010617 case CK_FixedPointToIntegral: {
10618 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
10619 if (!EvaluateFixedPoint(SubExpr, Src, Info))
10620 return false;
10621 bool Overflowed;
10622 llvm::APSInt Result = Src.convertToInt(
10623 Info.Ctx.getIntWidth(DestType),
10624 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
10625 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
10626 return false;
10627 return Success(Result, E);
10628 }
10629
Leonard Chanb4ba4672018-10-23 17:55:35 +000010630 case CK_FixedPointToBoolean: {
10631 // Unsigned padding does not affect this.
10632 APValue Val;
10633 if (!Evaluate(Val, Info, SubExpr))
10634 return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000010635 return Success(Val.getFixedPoint().getBoolValue(), E);
Leonard Chanb4ba4672018-10-23 17:55:35 +000010636 }
10637
Eli Friedmanc757de22011-03-25 00:43:55 +000010638 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +000010639 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +000010640 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +000010641
Eli Friedman742421e2009-02-20 01:15:07 +000010642 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +000010643 // Allow casts of address-of-label differences if they are no-ops
10644 // or narrowing. (The narrowing case isn't actually guaranteed to
10645 // be constant-evaluatable except in some narrow cases which are hard
10646 // to detect here. We let it through on the assumption the user knows
10647 // what they are doing.)
10648 if (Result.isAddrLabelDiff())
10649 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +000010650 // Only allow casts of lvalues if they are lossless.
10651 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
10652 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +000010653
Richard Smith911e1422012-01-30 22:27:01 +000010654 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
10655 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +000010656 }
Mike Stump11289f42009-09-09 15:08:12 +000010657
Eli Friedmanc757de22011-03-25 00:43:55 +000010658 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +000010659 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
10660
John McCall45d55e42010-05-07 21:00:08 +000010661 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +000010662 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +000010663 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +000010664
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000010665 if (LV.getLValueBase()) {
10666 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +000010667 // FIXME: Allow a larger integer size than the pointer size, and allow
10668 // narrowing back down to pointer width in subsequent integral casts.
10669 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000010670 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010671 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +000010672
Richard Smithcf74da72011-11-16 07:18:12 +000010673 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +000010674 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000010675 return true;
10676 }
10677
Hans Wennborgdd1ea8a2019-03-06 10:26:19 +000010678 APSInt AsInt;
10679 APValue V;
10680 LV.moveInto(V);
10681 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
10682 llvm_unreachable("Can't cast this!");
Yaxun Liu402804b2016-12-15 08:09:08 +000010683
Richard Smith911e1422012-01-30 22:27:01 +000010684 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +000010685 }
Eli Friedman9a156e52008-11-12 09:44:48 +000010686
Eli Friedmanc757de22011-03-25 00:43:55 +000010687 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +000010688 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000010689 if (!EvaluateComplex(SubExpr, C, Info))
10690 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +000010691 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000010692 }
Eli Friedmanc2b50172009-02-22 11:46:18 +000010693
Eli Friedmanc757de22011-03-25 00:43:55 +000010694 case CK_FloatingToIntegral: {
10695 APFloat F(0.0);
10696 if (!EvaluateFloat(SubExpr, F, Info))
10697 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +000010698
Richard Smith357362d2011-12-13 06:39:58 +000010699 APSInt Value;
10700 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
10701 return false;
10702 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +000010703 }
10704 }
Mike Stump11289f42009-09-09 15:08:12 +000010705
Eli Friedmanc757de22011-03-25 00:43:55 +000010706 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +000010707}
Anders Carlssonb5ad0212008-07-08 14:30:00 +000010708
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010709bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
10710 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000010711 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010712 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
10713 return false;
10714 if (!LV.isComplexInt())
10715 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010716 return Success(LV.getComplexIntReal(), E);
10717 }
10718
10719 return Visit(E->getSubExpr());
10720}
10721
Eli Friedman4e7a2412009-02-27 04:45:43 +000010722bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010723 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +000010724 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010725 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
10726 return false;
10727 if (!LV.isComplexInt())
10728 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010729 return Success(LV.getComplexIntImag(), E);
10730 }
10731
Richard Smith4a678122011-10-24 18:44:57 +000010732 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +000010733 return Success(0, E);
10734}
10735
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010736bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
10737 return Success(E->getPackLength(), E);
10738}
10739
Sebastian Redl5f0180d2010-09-10 20:55:47 +000010740bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
10741 return Success(E->getValue(), E);
10742}
10743
Leonard Chandb01c3a2018-06-20 17:19:40 +000010744bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10745 switch (E->getOpcode()) {
10746 default:
10747 // Invalid unary operators
10748 return Error(E);
10749 case UO_Plus:
10750 // The result is just the value.
10751 return Visit(E->getSubExpr());
10752 case UO_Minus: {
10753 if (!Visit(E->getSubExpr())) return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000010754 if (!Result.isFixedPoint())
10755 return Error(E);
10756 bool Overflowed;
10757 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
10758 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
10759 return false;
10760 return Success(Negated, E);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010761 }
10762 case UO_LNot: {
10763 bool bres;
10764 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
10765 return false;
10766 return Success(!bres, E);
10767 }
10768 }
10769}
10770
Leonard Chand3f3e162019-01-18 21:04:25 +000010771bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
10772 const Expr *SubExpr = E->getSubExpr();
10773 QualType DestType = E->getType();
10774 assert(DestType->isFixedPointType() &&
10775 "Expected destination type to be a fixed point type");
10776 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
10777
10778 switch (E->getCastKind()) {
10779 case CK_FixedPointCast: {
10780 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
10781 if (!EvaluateFixedPoint(SubExpr, Src, Info))
10782 return false;
10783 bool Overflowed;
10784 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
10785 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
10786 return false;
10787 return Success(Result, E);
10788 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000010789 case CK_IntegralToFixedPoint: {
10790 APSInt Src;
10791 if (!EvaluateInteger(SubExpr, Src, Info))
10792 return false;
10793
10794 bool Overflowed;
10795 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
10796 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
10797
10798 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
10799 return false;
10800
10801 return Success(IntResult, E);
10802 }
Leonard Chand3f3e162019-01-18 21:04:25 +000010803 case CK_NoOp:
10804 case CK_LValueToRValue:
10805 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10806 default:
10807 return Error(E);
10808 }
10809}
10810
10811bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10812 const Expr *LHS = E->getLHS();
10813 const Expr *RHS = E->getRHS();
10814 FixedPointSemantics ResultFXSema =
10815 Info.Ctx.getFixedPointSemantics(E->getType());
10816
10817 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
10818 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
10819 return false;
10820 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
10821 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
10822 return false;
10823
10824 switch (E->getOpcode()) {
10825 case BO_Add: {
10826 bool AddOverflow, ConversionOverflow;
10827 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
10828 .convert(ResultFXSema, &ConversionOverflow);
10829 if ((AddOverflow || ConversionOverflow) &&
10830 !HandleOverflow(Info, E, Result, E->getType()))
10831 return false;
10832 return Success(Result, E);
10833 }
10834 default:
10835 return false;
10836 }
10837 llvm_unreachable("Should've exited before this");
10838}
10839
Chris Lattner05706e882008-07-11 18:11:29 +000010840//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +000010841// Float Evaluation
10842//===----------------------------------------------------------------------===//
10843
10844namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000010845class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010846 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +000010847 APFloat &Result;
10848public:
10849 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +000010850 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +000010851
Richard Smith2e312c82012-03-03 22:46:17 +000010852 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010853 Result = V.getFloat();
10854 return true;
10855 }
Eli Friedman24c01542008-08-22 00:06:13 +000010856
Richard Smithfddd3842011-12-30 21:15:51 +000010857 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +000010858 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
10859 return true;
10860 }
10861
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010862 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +000010863
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010864 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +000010865 bool VisitBinaryOperator(const BinaryOperator *E);
10866 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000010867 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +000010868
John McCallb1fb0d32010-05-07 22:08:54 +000010869 bool VisitUnaryReal(const UnaryOperator *E);
10870 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +000010871
Richard Smithfddd3842011-12-30 21:15:51 +000010872 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +000010873};
10874} // end anonymous namespace
10875
10876static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000010877 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010878 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +000010879}
10880
Jay Foad39c79802011-01-12 09:06:06 +000010881static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +000010882 QualType ResultTy,
10883 const Expr *Arg,
10884 bool SNaN,
10885 llvm::APFloat &Result) {
10886 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
10887 if (!S) return false;
10888
10889 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
10890
10891 llvm::APInt fill;
10892
10893 // Treat empty strings as if they were zero.
10894 if (S->getString().empty())
10895 fill = llvm::APInt(32, 0);
10896 else if (S->getString().getAsInteger(0, fill))
10897 return false;
10898
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +000010899 if (Context.getTargetInfo().isNan2008()) {
10900 if (SNaN)
10901 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10902 else
10903 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10904 } else {
10905 // Prior to IEEE 754-2008, architectures were allowed to choose whether
10906 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
10907 // a different encoding to what became a standard in 2008, and for pre-
10908 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
10909 // sNaN. This is now known as "legacy NaN" encoding.
10910 if (SNaN)
10911 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10912 else
10913 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10914 }
10915
John McCall16291492010-02-28 13:00:19 +000010916 return true;
10917}
10918
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010919bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000010920 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010921 default:
10922 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10923
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010924 case Builtin::BI__builtin_huge_val:
10925 case Builtin::BI__builtin_huge_valf:
10926 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010927 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010928 case Builtin::BI__builtin_inf:
10929 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010930 case Builtin::BI__builtin_infl:
10931 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010932 const llvm::fltSemantics &Sem =
10933 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000010934 Result = llvm::APFloat::getInf(Sem);
10935 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010936 }
Mike Stump11289f42009-09-09 15:08:12 +000010937
John McCall16291492010-02-28 13:00:19 +000010938 case Builtin::BI__builtin_nans:
10939 case Builtin::BI__builtin_nansf:
10940 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010941 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010942 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10943 true, Result))
10944 return Error(E);
10945 return true;
John McCall16291492010-02-28 13:00:19 +000010946
Chris Lattner0b7282e2008-10-06 06:31:58 +000010947 case Builtin::BI__builtin_nan:
10948 case Builtin::BI__builtin_nanf:
10949 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010950 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000010951 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000010952 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000010953 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10954 false, Result))
10955 return Error(E);
10956 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010957
10958 case Builtin::BI__builtin_fabs:
10959 case Builtin::BI__builtin_fabsf:
10960 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010961 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010962 if (!EvaluateFloat(E->getArg(0), Result, Info))
10963 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010964
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010965 if (Result.isNegative())
10966 Result.changeSign();
10967 return true;
10968
Richard Smith8889a3d2013-06-13 06:26:32 +000010969 // FIXME: Builtin::BI__builtin_powi
10970 // FIXME: Builtin::BI__builtin_powif
10971 // FIXME: Builtin::BI__builtin_powil
10972
Mike Stump11289f42009-09-09 15:08:12 +000010973 case Builtin::BI__builtin_copysign:
10974 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010975 case Builtin::BI__builtin_copysignl:
10976 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010977 APFloat RHS(0.);
10978 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
10979 !EvaluateFloat(E->getArg(1), RHS, Info))
10980 return false;
10981 Result.copySign(RHS);
10982 return true;
10983 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010984 }
10985}
10986
John McCallb1fb0d32010-05-07 22:08:54 +000010987bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000010988 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10989 ComplexValue CV;
10990 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10991 return false;
10992 Result = CV.FloatReal;
10993 return true;
10994 }
10995
10996 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000010997}
10998
10999bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000011000 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11001 ComplexValue CV;
11002 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11003 return false;
11004 Result = CV.FloatImag;
11005 return true;
11006 }
11007
Richard Smith4a678122011-10-24 18:44:57 +000011008 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000011009 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
11010 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000011011 return true;
11012}
11013
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011014bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011015 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011016 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000011017 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000011018 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000011019 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000011020 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
11021 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011022 Result.changeSign();
11023 return true;
11024 }
11025}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011026
Eli Friedman24c01542008-08-22 00:06:13 +000011027bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000011028 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11029 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000011030
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011031 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000011032 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000011033 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000011034 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000011035 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
11036 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000011037}
11038
11039bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
11040 Result = E->getValue();
11041 return true;
11042}
11043
Peter Collingbournee9200682011-05-13 03:29:01 +000011044bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
11045 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000011046
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011047 switch (E->getCastKind()) {
11048 default:
Richard Smith11562c52011-10-28 17:51:58 +000011049 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011050
11051 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011052 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000011053 return EvaluateInteger(SubExpr, IntResult, Info) &&
11054 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
11055 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000011056 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011057
11058 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011059 if (!Visit(SubExpr))
11060 return false;
Richard Smith357362d2011-12-13 06:39:58 +000011061 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
11062 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000011063 }
John McCalld7646252010-11-14 08:17:51 +000011064
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011065 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000011066 ComplexValue V;
11067 if (!EvaluateComplex(SubExpr, V, Info))
11068 return false;
11069 Result = V.getComplexFloatReal();
11070 return true;
11071 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011072 }
Eli Friedman9a156e52008-11-12 09:44:48 +000011073}
11074
Eli Friedman24c01542008-08-22 00:06:13 +000011075//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011076// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000011077//===----------------------------------------------------------------------===//
11078
11079namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000011080class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000011081 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000011082 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000011083
Anders Carlsson537969c2008-11-16 20:27:53 +000011084public:
John McCall93d91dc2010-05-07 17:22:02 +000011085 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000011086 : ExprEvaluatorBaseTy(info), Result(Result) {}
11087
Richard Smith2e312c82012-03-03 22:46:17 +000011088 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011089 Result.setFrom(V);
11090 return true;
11091 }
Mike Stump11289f42009-09-09 15:08:12 +000011092
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011093 bool ZeroInitialization(const Expr *E);
11094
Anders Carlsson537969c2008-11-16 20:27:53 +000011095 //===--------------------------------------------------------------------===//
11096 // Visitor Methods
11097 //===--------------------------------------------------------------------===//
11098
Peter Collingbournee9200682011-05-13 03:29:01 +000011099 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000011100 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000011101 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011102 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011103 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000011104};
11105} // end anonymous namespace
11106
John McCall93d91dc2010-05-07 17:22:02 +000011107static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
11108 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000011109 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000011110 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000011111}
11112
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011113bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000011114 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011115 if (ElemTy->isRealFloatingType()) {
11116 Result.makeComplexFloat();
11117 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
11118 Result.FloatReal = Zero;
11119 Result.FloatImag = Zero;
11120 } else {
11121 Result.makeComplexInt();
11122 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
11123 Result.IntReal = Zero;
11124 Result.IntImag = Zero;
11125 }
11126 return true;
11127}
11128
Peter Collingbournee9200682011-05-13 03:29:01 +000011129bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
11130 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011131
11132 if (SubExpr->getType()->isRealFloatingType()) {
11133 Result.makeComplexFloat();
11134 APFloat &Imag = Result.FloatImag;
11135 if (!EvaluateFloat(SubExpr, Imag, Info))
11136 return false;
11137
11138 Result.FloatReal = APFloat(Imag.getSemantics());
11139 return true;
11140 } else {
11141 assert(SubExpr->getType()->isIntegerType() &&
11142 "Unexpected imaginary literal.");
11143
11144 Result.makeComplexInt();
11145 APSInt &Imag = Result.IntImag;
11146 if (!EvaluateInteger(SubExpr, Imag, Info))
11147 return false;
11148
11149 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
11150 return true;
11151 }
11152}
11153
Peter Collingbournee9200682011-05-13 03:29:01 +000011154bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011155
John McCallfcef3cf2010-12-14 17:51:41 +000011156 switch (E->getCastKind()) {
11157 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011158 case CK_BaseToDerived:
11159 case CK_DerivedToBase:
11160 case CK_UncheckedDerivedToBase:
11161 case CK_Dynamic:
11162 case CK_ToUnion:
11163 case CK_ArrayToPointerDecay:
11164 case CK_FunctionToPointerDecay:
11165 case CK_NullToPointer:
11166 case CK_NullToMemberPointer:
11167 case CK_BaseToDerivedMemberPointer:
11168 case CK_DerivedToBaseMemberPointer:
11169 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000011170 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000011171 case CK_ConstructorConversion:
11172 case CK_IntegralToPointer:
11173 case CK_PointerToIntegral:
11174 case CK_PointerToBoolean:
11175 case CK_ToVoid:
11176 case CK_VectorSplat:
11177 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000011178 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000011179 case CK_IntegralToBoolean:
11180 case CK_IntegralToFloating:
11181 case CK_FloatingToIntegral:
11182 case CK_FloatingToBoolean:
11183 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000011184 case CK_CPointerToObjCPointerCast:
11185 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011186 case CK_AnyPointerToBlockPointerCast:
11187 case CK_ObjCObjectLValueCast:
11188 case CK_FloatingComplexToReal:
11189 case CK_FloatingComplexToBoolean:
11190 case CK_IntegralComplexToReal:
11191 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000011192 case CK_ARCProduceObject:
11193 case CK_ARCConsumeObject:
11194 case CK_ARCReclaimReturnedObject:
11195 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000011196 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000011197 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000011198 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000011199 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000011200 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000011201 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000011202 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000011203 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +000011204 case CK_FixedPointToIntegral:
11205 case CK_IntegralToFixedPoint:
John McCallfcef3cf2010-12-14 17:51:41 +000011206 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000011207
John McCallfcef3cf2010-12-14 17:51:41 +000011208 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011209 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000011210 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +000011211 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000011212
11213 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000011214 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011215 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011216 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000011217
11218 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011219 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000011220 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011221 return false;
11222
John McCallfcef3cf2010-12-14 17:51:41 +000011223 Result.makeComplexFloat();
11224 Result.FloatImag = APFloat(Real.getSemantics());
11225 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011226 }
11227
John McCallfcef3cf2010-12-14 17:51:41 +000011228 case CK_FloatingComplexCast: {
11229 if (!Visit(E->getSubExpr()))
11230 return false;
11231
11232 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11233 QualType From
11234 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11235
Richard Smith357362d2011-12-13 06:39:58 +000011236 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11237 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011238 }
11239
11240 case CK_FloatingComplexToIntegralComplex: {
11241 if (!Visit(E->getSubExpr()))
11242 return false;
11243
11244 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11245 QualType From
11246 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11247 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000011248 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11249 To, Result.IntReal) &&
11250 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11251 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011252 }
11253
11254 case CK_IntegralRealToComplex: {
11255 APSInt &Real = Result.IntReal;
11256 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11257 return false;
11258
11259 Result.makeComplexInt();
11260 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11261 return true;
11262 }
11263
11264 case CK_IntegralComplexCast: {
11265 if (!Visit(E->getSubExpr()))
11266 return false;
11267
11268 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11269 QualType From
11270 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11271
Richard Smith911e1422012-01-30 22:27:01 +000011272 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11273 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011274 return true;
11275 }
11276
11277 case CK_IntegralComplexToFloatingComplex: {
11278 if (!Visit(E->getSubExpr()))
11279 return false;
11280
Ted Kremenek28831752012-08-23 20:46:57 +000011281 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000011282 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000011283 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000011284 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000011285 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11286 To, Result.FloatReal) &&
11287 HandleIntToFloatCast(Info, E, From, Result.IntImag,
11288 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011289 }
11290 }
11291
11292 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011293}
11294
John McCall93d91dc2010-05-07 17:22:02 +000011295bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000011296 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000011297 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11298
Chandler Carrutha216cad2014-10-11 00:57:18 +000011299 // Track whether the LHS or RHS is real at the type system level. When this is
11300 // the case we can simplify our evaluation strategy.
11301 bool LHSReal = false, RHSReal = false;
11302
11303 bool LHSOK;
11304 if (E->getLHS()->getType()->isRealFloatingType()) {
11305 LHSReal = true;
11306 APFloat &Real = Result.FloatReal;
11307 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11308 if (LHSOK) {
11309 Result.makeComplexFloat();
11310 Result.FloatImag = APFloat(Real.getSemantics());
11311 }
11312 } else {
11313 LHSOK = Visit(E->getLHS());
11314 }
George Burgess IVa145e252016-05-25 22:38:36 +000011315 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000011316 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011317
John McCall93d91dc2010-05-07 17:22:02 +000011318 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011319 if (E->getRHS()->getType()->isRealFloatingType()) {
11320 RHSReal = true;
11321 APFloat &Real = RHS.FloatReal;
11322 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11323 return false;
11324 RHS.makeComplexFloat();
11325 RHS.FloatImag = APFloat(Real.getSemantics());
11326 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000011327 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011328
Chandler Carrutha216cad2014-10-11 00:57:18 +000011329 assert(!(LHSReal && RHSReal) &&
11330 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011331 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011332 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000011333 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011334 if (Result.isComplexFloat()) {
11335 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11336 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011337 if (LHSReal)
11338 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11339 else if (!RHSReal)
11340 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11341 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011342 } else {
11343 Result.getComplexIntReal() += RHS.getComplexIntReal();
11344 Result.getComplexIntImag() += RHS.getComplexIntImag();
11345 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011346 break;
John McCalle3027922010-08-25 11:45:40 +000011347 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011348 if (Result.isComplexFloat()) {
11349 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11350 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011351 if (LHSReal) {
11352 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11353 Result.getComplexFloatImag().changeSign();
11354 } else if (!RHSReal) {
11355 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11356 APFloat::rmNearestTiesToEven);
11357 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011358 } else {
11359 Result.getComplexIntReal() -= RHS.getComplexIntReal();
11360 Result.getComplexIntImag() -= RHS.getComplexIntImag();
11361 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011362 break;
John McCalle3027922010-08-25 11:45:40 +000011363 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011364 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000011365 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000011366 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000011367 // following naming scheme:
11368 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000011369 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011370 APFloat &A = LHS.getComplexFloatReal();
11371 APFloat &B = LHS.getComplexFloatImag();
11372 APFloat &C = RHS.getComplexFloatReal();
11373 APFloat &D = RHS.getComplexFloatImag();
11374 APFloat &ResR = Result.getComplexFloatReal();
11375 APFloat &ResI = Result.getComplexFloatImag();
11376 if (LHSReal) {
11377 assert(!RHSReal && "Cannot have two real operands for a complex op!");
11378 ResR = A * C;
11379 ResI = A * D;
11380 } else if (RHSReal) {
11381 ResR = C * A;
11382 ResI = C * B;
11383 } else {
11384 // In the fully general case, we need to handle NaNs and infinities
11385 // robustly.
11386 APFloat AC = A * C;
11387 APFloat BD = B * D;
11388 APFloat AD = A * D;
11389 APFloat BC = B * C;
11390 ResR = AC - BD;
11391 ResI = AD + BC;
11392 if (ResR.isNaN() && ResI.isNaN()) {
11393 bool Recalc = false;
11394 if (A.isInfinity() || B.isInfinity()) {
11395 A = APFloat::copySign(
11396 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11397 B = APFloat::copySign(
11398 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11399 if (C.isNaN())
11400 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11401 if (D.isNaN())
11402 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11403 Recalc = true;
11404 }
11405 if (C.isInfinity() || D.isInfinity()) {
11406 C = APFloat::copySign(
11407 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11408 D = APFloat::copySign(
11409 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11410 if (A.isNaN())
11411 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11412 if (B.isNaN())
11413 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11414 Recalc = true;
11415 }
11416 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11417 AD.isInfinity() || BC.isInfinity())) {
11418 if (A.isNaN())
11419 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11420 if (B.isNaN())
11421 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11422 if (C.isNaN())
11423 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11424 if (D.isNaN())
11425 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11426 Recalc = true;
11427 }
11428 if (Recalc) {
11429 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11430 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11431 }
11432 }
11433 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011434 } else {
John McCall93d91dc2010-05-07 17:22:02 +000011435 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000011436 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011437 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11438 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000011439 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011440 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11441 LHS.getComplexIntImag() * RHS.getComplexIntReal());
11442 }
11443 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011444 case BO_Div:
11445 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000011446 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000011447 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000011448 // following naming scheme:
11449 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011450 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011451 APFloat &A = LHS.getComplexFloatReal();
11452 APFloat &B = LHS.getComplexFloatImag();
11453 APFloat &C = RHS.getComplexFloatReal();
11454 APFloat &D = RHS.getComplexFloatImag();
11455 APFloat &ResR = Result.getComplexFloatReal();
11456 APFloat &ResI = Result.getComplexFloatImag();
11457 if (RHSReal) {
11458 ResR = A / C;
11459 ResI = B / C;
11460 } else {
11461 if (LHSReal) {
11462 // No real optimizations we can do here, stub out with zero.
11463 B = APFloat::getZero(A.getSemantics());
11464 }
11465 int DenomLogB = 0;
11466 APFloat MaxCD = maxnum(abs(C), abs(D));
11467 if (MaxCD.isFinite()) {
11468 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000011469 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11470 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011471 }
11472 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000011473 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11474 APFloat::rmNearestTiesToEven);
11475 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11476 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011477 if (ResR.isNaN() && ResI.isNaN()) {
11478 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11479 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11480 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11481 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11482 D.isFinite()) {
11483 A = APFloat::copySign(
11484 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11485 B = APFloat::copySign(
11486 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11487 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11488 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11489 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11490 C = APFloat::copySign(
11491 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11492 D = APFloat::copySign(
11493 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11494 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
11495 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
11496 }
11497 }
11498 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011499 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011500 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
11501 return Error(E, diag::note_expr_divide_by_zero);
11502
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011503 ComplexValue LHS = Result;
11504 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
11505 RHS.getComplexIntImag() * RHS.getComplexIntImag();
11506 Result.getComplexIntReal() =
11507 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
11508 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
11509 Result.getComplexIntImag() =
11510 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
11511 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
11512 }
11513 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011514 }
11515
John McCall93d91dc2010-05-07 17:22:02 +000011516 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011517}
11518
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011519bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11520 // Get the operand value into 'Result'.
11521 if (!Visit(E->getSubExpr()))
11522 return false;
11523
11524 switch (E->getOpcode()) {
11525 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011526 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011527 case UO_Extension:
11528 return true;
11529 case UO_Plus:
11530 // The result is always just the subexpr.
11531 return true;
11532 case UO_Minus:
11533 if (Result.isComplexFloat()) {
11534 Result.getComplexFloatReal().changeSign();
11535 Result.getComplexFloatImag().changeSign();
11536 }
11537 else {
11538 Result.getComplexIntReal() = -Result.getComplexIntReal();
11539 Result.getComplexIntImag() = -Result.getComplexIntImag();
11540 }
11541 return true;
11542 case UO_Not:
11543 if (Result.isComplexFloat())
11544 Result.getComplexFloatImag().changeSign();
11545 else
11546 Result.getComplexIntImag() = -Result.getComplexIntImag();
11547 return true;
11548 }
11549}
11550
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011551bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11552 if (E->getNumInits() == 2) {
11553 if (E->getType()->isComplexType()) {
11554 Result.makeComplexFloat();
11555 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
11556 return false;
11557 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
11558 return false;
11559 } else {
11560 Result.makeComplexInt();
11561 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
11562 return false;
11563 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
11564 return false;
11565 }
11566 return true;
11567 }
11568 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
11569}
11570
Anders Carlsson537969c2008-11-16 20:27:53 +000011571//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000011572// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
11573// implicit conversion.
11574//===----------------------------------------------------------------------===//
11575
11576namespace {
11577class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000011578 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000011579 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000011580 APValue &Result;
11581public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000011582 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
11583 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000011584
11585 bool Success(const APValue &V, const Expr *E) {
11586 Result = V;
11587 return true;
11588 }
11589
11590 bool ZeroInitialization(const Expr *E) {
11591 ImplicitValueInitExpr VIE(
11592 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000011593 // For atomic-qualified class (and array) types in C++, initialize the
11594 // _Atomic-wrapped subobject directly, in-place.
11595 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
11596 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000011597 }
11598
11599 bool VisitCastExpr(const CastExpr *E) {
11600 switch (E->getCastKind()) {
11601 default:
11602 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11603 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000011604 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
11605 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000011606 }
11607 }
11608};
11609} // end anonymous namespace
11610
Richard Smith64cb9ca2017-02-22 22:09:50 +000011611static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
11612 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000011613 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000011614 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000011615}
11616
11617//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000011618// Void expression evaluation, primarily for a cast to void on the LHS of a
11619// comma operator
11620//===----------------------------------------------------------------------===//
11621
11622namespace {
11623class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000011624 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000011625public:
11626 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
11627
Richard Smith2e312c82012-03-03 22:46:17 +000011628 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000011629
Richard Smith7cd577b2017-08-17 19:35:50 +000011630 bool ZeroInitialization(const Expr *E) { return true; }
11631
Richard Smith42d3af92011-12-07 00:43:50 +000011632 bool VisitCastExpr(const CastExpr *E) {
11633 switch (E->getCastKind()) {
11634 default:
11635 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11636 case CK_ToVoid:
11637 VisitIgnoredValue(E->getSubExpr());
11638 return true;
11639 }
11640 }
Hal Finkela8443c32014-07-17 14:49:58 +000011641
11642 bool VisitCallExpr(const CallExpr *E) {
11643 switch (E->getBuiltinCallee()) {
11644 default:
11645 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11646 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000011647 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000011648 // The argument is not evaluated!
11649 return true;
11650 }
11651 }
Richard Smith42d3af92011-12-07 00:43:50 +000011652};
11653} // end anonymous namespace
11654
11655static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
11656 assert(E->isRValue() && E->getType()->isVoidType());
11657 return VoidExprEvaluator(Info).Visit(E);
11658}
11659
11660//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000011661// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000011662//===----------------------------------------------------------------------===//
11663
Richard Smith2e312c82012-03-03 22:46:17 +000011664static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000011665 // In C, function designators are not lvalues, but we evaluate them as if they
11666 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000011667 QualType T = E->getType();
11668 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000011669 LValue LV;
11670 if (!EvaluateLValue(E, LV, Info))
11671 return false;
11672 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000011673 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000011674 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000011675 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011676 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000011677 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011678 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011679 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000011680 LValue LV;
11681 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011682 return false;
Richard Smith725810a2011-10-16 21:26:27 +000011683 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000011684 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000011685 llvm::APFloat F(0.0);
11686 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011687 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000011688 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000011689 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000011690 ComplexValue C;
11691 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011692 return false;
Richard Smith725810a2011-10-16 21:26:27 +000011693 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000011694 } else if (T->isFixedPointType()) {
11695 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011696 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000011697 MemberPtr P;
11698 if (!EvaluateMemberPointer(E, P, Info))
11699 return false;
11700 P.moveInto(Result);
11701 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000011702 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000011703 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011704 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000011705 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000011706 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000011707 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000011708 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000011709 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011710 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000011711 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000011712 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000011713 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000011714 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011715 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000011716 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000011717 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000011718 if (!EvaluateVoid(E, Info))
11719 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011720 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000011721 QualType Unqual = T.getAtomicUnqualifiedType();
11722 if (Unqual->isArrayType() || Unqual->isRecordType()) {
11723 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011724 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000011725 if (!EvaluateAtomic(E, &LV, Value, Info))
11726 return false;
11727 } else {
11728 if (!EvaluateAtomic(E, nullptr, Result, Info))
11729 return false;
11730 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011731 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000011732 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000011733 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011734 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000011735 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000011736 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011737 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011738
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000011739 return true;
11740}
11741
Richard Smithb228a862012-02-15 02:18:13 +000011742/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
11743/// cases, the in-place evaluation is essential, since later initializers for
11744/// an object can indirectly refer to subobjects which were initialized earlier.
11745static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000011746 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000011747 assert(!E->isValueDependent());
11748
Richard Smith7525ff62013-05-09 07:14:00 +000011749 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000011750 return false;
11751
11752 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000011753 // Evaluate arrays and record types in-place, so that later initializers can
11754 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000011755 QualType T = E->getType();
11756 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000011757 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000011758 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000011759 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000011760 else if (T->isAtomicType()) {
11761 QualType Unqual = T.getAtomicUnqualifiedType();
11762 if (Unqual->isArrayType() || Unqual->isRecordType())
11763 return EvaluateAtomic(E, &This, Result, Info);
11764 }
Richard Smithed5165f2011-11-04 05:33:44 +000011765 }
11766
11767 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000011768 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000011769}
11770
Richard Smithf57d8cb2011-12-09 22:58:01 +000011771/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
11772/// lvalue-to-rvalue cast if it is an lvalue.
11773static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000011774 if (E->getType().isNull())
11775 return false;
11776
Nick Lewyckyc190f962017-05-02 01:06:16 +000011777 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000011778 return false;
11779
Richard Smith2e312c82012-03-03 22:46:17 +000011780 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011781 return false;
11782
11783 if (E->isGLValue()) {
11784 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000011785 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000011786 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011787 return false;
11788 }
11789
Richard Smith2e312c82012-03-03 22:46:17 +000011790 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000011791 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011792}
Richard Smith11562c52011-10-28 17:51:58 +000011793
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011794static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000011795 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011796 // Fast-path evaluations of integer literals, since we sometimes see files
11797 // containing vast quantities of these.
11798 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
11799 Result.Val = APValue(APSInt(L->getValue(),
11800 L->getType()->isUnsignedIntegerType()));
11801 IsConst = true;
11802 return true;
11803 }
James Dennett0492ef02014-03-14 17:44:10 +000011804
11805 // This case should be rare, but we need to check it before we check on
11806 // the type below.
11807 if (Exp->getType().isNull()) {
11808 IsConst = false;
11809 return true;
11810 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011811
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011812 // FIXME: Evaluating values of large array and record types can cause
11813 // performance problems. Only do so in C++11 for now.
11814 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
11815 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000011816 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011817 IsConst = false;
11818 return true;
11819 }
11820 return false;
11821}
11822
Fangrui Song407659a2018-11-30 23:41:18 +000011823static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
11824 Expr::SideEffectsKind SEK) {
11825 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
11826 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
11827}
11828
11829static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
11830 const ASTContext &Ctx, EvalInfo &Info) {
11831 bool IsConst;
11832 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
11833 return IsConst;
11834
11835 return EvaluateAsRValue(Info, E, Result.Val);
11836}
11837
11838static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
11839 const ASTContext &Ctx,
11840 Expr::SideEffectsKind AllowSideEffects,
11841 EvalInfo &Info) {
11842 if (!E->getType()->isIntegralOrEnumerationType())
11843 return false;
11844
11845 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
11846 !ExprResult.Val.isInt() ||
11847 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11848 return false;
11849
11850 return true;
11851}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011852
Leonard Chand3f3e162019-01-18 21:04:25 +000011853static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
11854 const ASTContext &Ctx,
11855 Expr::SideEffectsKind AllowSideEffects,
11856 EvalInfo &Info) {
11857 if (!E->getType()->isFixedPointType())
11858 return false;
11859
11860 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
11861 return false;
11862
11863 if (!ExprResult.Val.isFixedPoint() ||
11864 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11865 return false;
11866
11867 return true;
11868}
11869
Richard Smith7b553f12011-10-29 00:50:52 +000011870/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000011871/// any crazy technique (that has nothing to do with language standards) that
11872/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000011873/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
11874/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000011875bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
11876 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011877 assert(!isValueDependent() &&
11878 "Expression evaluator can't be called on a dependent expression.");
Richard Smith6d4c6582013-11-05 22:18:15 +000011879 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000011880 Info.InConstantContext = InConstantContext;
11881 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000011882}
11883
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011884bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
11885 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011886 assert(!isValueDependent() &&
11887 "Expression evaluator can't be called on a dependent expression.");
Richard Smith11562c52011-10-28 17:51:58 +000011888 EvalResult Scratch;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011889 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
Richard Smith2e312c82012-03-03 22:46:17 +000011890 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000011891}
11892
Fangrui Song407659a2018-11-30 23:41:18 +000011893bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011894 SideEffectsKind AllowSideEffects,
11895 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011896 assert(!isValueDependent() &&
11897 "Expression evaluator can't be called on a dependent expression.");
Fangrui Song407659a2018-11-30 23:41:18 +000011898 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011899 Info.InConstantContext = InConstantContext;
Fangrui Song407659a2018-11-30 23:41:18 +000011900 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000011901}
11902
Leonard Chand3f3e162019-01-18 21:04:25 +000011903bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011904 SideEffectsKind AllowSideEffects,
11905 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011906 assert(!isValueDependent() &&
11907 "Expression evaluator can't be called on a dependent expression.");
Leonard Chand3f3e162019-01-18 21:04:25 +000011908 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011909 Info.InConstantContext = InConstantContext;
Leonard Chand3f3e162019-01-18 21:04:25 +000011910 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
11911}
11912
Richard Trieube234c32016-04-21 21:04:55 +000011913bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011914 SideEffectsKind AllowSideEffects,
11915 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011916 assert(!isValueDependent() &&
11917 "Expression evaluator can't be called on a dependent expression.");
11918
Richard Trieube234c32016-04-21 21:04:55 +000011919 if (!getType()->isRealFloatingType())
11920 return false;
11921
11922 EvalResult ExprResult;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011923 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
11924 !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000011925 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000011926 return false;
11927
11928 Result = ExprResult.Val.getFloat();
11929 return true;
11930}
11931
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011932bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
11933 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011934 assert(!isValueDependent() &&
11935 "Expression evaluator can't be called on a dependent expression.");
11936
Richard Smith6d4c6582013-11-05 22:18:15 +000011937 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000011938 Info.InConstantContext = InConstantContext;
John McCall45d55e42010-05-07 21:00:08 +000011939 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000011940 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
11941 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000011942 Ctx.getLValueReferenceType(getType()), LV,
11943 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000011944 return false;
11945
Richard Smith2e312c82012-03-03 22:46:17 +000011946 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000011947 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000011948}
11949
Reid Kleckner1a840d22018-05-10 18:57:35 +000011950bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
11951 const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011952 assert(!isValueDependent() &&
11953 "Expression evaluator can't be called on a dependent expression.");
11954
Reid Kleckner1a840d22018-05-10 18:57:35 +000011955 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
11956 EvalInfo Info(Ctx, Result, EM);
Eric Fiselier680e8652019-03-08 22:06:48 +000011957 Info.InConstantContext = true;
Eric Fiselieradd16a82019-04-24 02:23:30 +000011958
Reid Kleckner1a840d22018-05-10 18:57:35 +000011959 if (!::Evaluate(Result.Val, Info, this))
11960 return false;
11961
11962 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
11963 Usage);
11964}
11965
Richard Smithd0b4dd62011-12-19 06:19:21 +000011966bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
11967 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011968 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011969 assert(!isValueDependent() &&
11970 "Expression evaluator can't be called on a dependent expression.");
11971
Richard Smithdafff942012-01-14 04:30:29 +000011972 // FIXME: Evaluating initializers for large array and record types can cause
11973 // performance problems. Only do so in C++11 for now.
11974 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011975 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000011976 return false;
11977
Richard Smithd0b4dd62011-12-19 06:19:21 +000011978 Expr::EvalStatus EStatus;
11979 EStatus.Diag = &Notes;
11980
Richard Smith0c6124b2015-12-03 01:36:22 +000011981 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
11982 ? EvalInfo::EM_ConstantExpression
11983 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000011984 InitInfo.setEvaluatingDecl(VD, Value);
Fangrui Song407659a2018-11-30 23:41:18 +000011985 InitInfo.InConstantContext = true;
Richard Smithd0b4dd62011-12-19 06:19:21 +000011986
11987 LValue LVal;
11988 LVal.set(VD);
11989
Richard Smithfddd3842011-12-30 21:15:51 +000011990 // C++11 [basic.start.init]p2:
11991 // Variables with static storage duration or thread storage duration shall be
11992 // zero-initialized before any other initialization takes place.
11993 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011994 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000011995 !VD->getType()->isReferenceType()) {
11996 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000011997 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000011998 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000011999 return false;
12000 }
12001
Richard Smith7525ff62013-05-09 07:14:00 +000012002 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
12003 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000012004 EStatus.HasSideEffects)
12005 return false;
12006
12007 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
12008 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000012009}
12010
Richard Smith7b553f12011-10-29 00:50:52 +000012011/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
12012/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000012013bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012014 assert(!isValueDependent() &&
12015 "Expression evaluator can't be called on a dependent expression.");
12016
Anders Carlsson5b3638b2008-12-01 06:44:05 +000012017 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000012018 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000012019 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000012020}
Anders Carlsson59689ed2008-11-22 21:04:56 +000012021
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000012022APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012023 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012024 assert(!isValueDependent() &&
12025 "Expression evaluator can't be called on a dependent expression.");
12026
Fangrui Song407659a2018-11-30 23:41:18 +000012027 EvalResult EVResult;
12028 EVResult.Diag = Diag;
12029 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12030 Info.InConstantContext = true;
12031
12032 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000012033 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000012034 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000012035 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000012036
Fangrui Song407659a2018-11-30 23:41:18 +000012037 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000012038}
John McCall864e3962010-05-07 05:32:02 +000012039
David Bolvansky3b6ae572018-10-18 20:49:06 +000012040APSInt Expr::EvaluateKnownConstIntCheckOverflow(
12041 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012042 assert(!isValueDependent() &&
12043 "Expression evaluator can't be called on a dependent expression.");
12044
Fangrui Song407659a2018-11-30 23:41:18 +000012045 EvalResult EVResult;
12046 EVResult.Diag = Diag;
12047 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12048 Info.InConstantContext = true;
12049
12050 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000012051 (void)Result;
12052 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000012053 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000012054
Fangrui Song407659a2018-11-30 23:41:18 +000012055 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000012056}
12057
Richard Smithe9ff7702013-11-05 22:23:30 +000012058void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012059 assert(!isValueDependent() &&
12060 "Expression evaluator can't be called on a dependent expression.");
12061
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012062 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000012063 EvalResult EVResult;
12064 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
12065 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12066 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012067 }
12068}
12069
Richard Smithe6c01442013-06-05 00:46:14 +000012070bool Expr::EvalResult::isGlobalLValue() const {
12071 assert(Val.isLValue());
12072 return IsGlobalLValue(Val.getLValueBase());
12073}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000012074
12075
John McCall864e3962010-05-07 05:32:02 +000012076/// isIntegerConstantExpr - this recursive routine will test if an expression is
12077/// an integer constant expression.
12078
12079/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
12080/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000012081
12082// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000012083// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
12084// and a (possibly null) SourceLocation indicating the location of the problem.
12085//
John McCall864e3962010-05-07 05:32:02 +000012086// Note that to reduce code duplication, this helper does no evaluation
12087// itself; the caller checks whether the expression is evaluatable, and
12088// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000012089// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000012090
Dan Gohman28ade552010-07-26 21:25:24 +000012091namespace {
12092
Richard Smith9e575da2012-12-28 13:25:52 +000012093enum ICEKind {
12094 /// This expression is an ICE.
12095 IK_ICE,
12096 /// This expression is not an ICE, but if it isn't evaluated, it's
12097 /// a legal subexpression for an ICE. This return value is used to handle
12098 /// the comma operator in C99 mode, and non-constant subexpressions.
12099 IK_ICEIfUnevaluated,
12100 /// This expression is not an ICE, and is not a legal subexpression for one.
12101 IK_NotICE
12102};
12103
John McCall864e3962010-05-07 05:32:02 +000012104struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000012105 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000012106 SourceLocation Loc;
12107
Richard Smith9e575da2012-12-28 13:25:52 +000012108 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000012109};
12110
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012111}
Dan Gohman28ade552010-07-26 21:25:24 +000012112
Richard Smith9e575da2012-12-28 13:25:52 +000012113static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
12114
12115static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000012116
Craig Toppera31a8822013-08-22 07:09:37 +000012117static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000012118 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000012119 Expr::EvalStatus Status;
12120 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12121
12122 Info.InConstantContext = true;
12123 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000012124 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012125 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000012126
John McCall864e3962010-05-07 05:32:02 +000012127 return NoDiag();
12128}
12129
Craig Toppera31a8822013-08-22 07:09:37 +000012130static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000012131 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000012132 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012133 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012134
12135 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000012136#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000012137#define STMT(Node, Base) case Expr::Node##Class:
12138#define EXPR(Node, Base)
12139#include "clang/AST/StmtNodes.inc"
12140 case Expr::PredefinedExprClass:
12141 case Expr::FloatingLiteralClass:
12142 case Expr::ImaginaryLiteralClass:
12143 case Expr::StringLiteralClass:
12144 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000012145 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000012146 case Expr::MemberExprClass:
12147 case Expr::CompoundAssignOperatorClass:
12148 case Expr::CompoundLiteralExprClass:
12149 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000012150 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000012151 case Expr::ArrayInitLoopExprClass:
12152 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000012153 case Expr::NoInitExprClass:
12154 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000012155 case Expr::ImplicitValueInitExprClass:
12156 case Expr::ParenListExprClass:
12157 case Expr::VAArgExprClass:
12158 case Expr::AddrLabelExprClass:
12159 case Expr::StmtExprClass:
12160 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000012161 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000012162 case Expr::CXXDynamicCastExprClass:
12163 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000012164 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000012165 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000012166 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000012167 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000012168 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012169 case Expr::CXXThisExprClass:
12170 case Expr::CXXThrowExprClass:
12171 case Expr::CXXNewExprClass:
12172 case Expr::CXXDeleteExprClass:
12173 case Expr::CXXPseudoDestructorExprClass:
12174 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000012175 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000012176 case Expr::DependentScopeDeclRefExprClass:
12177 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000012178 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000012179 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000012180 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000012181 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000012182 case Expr::CXXTemporaryObjectExprClass:
12183 case Expr::CXXUnresolvedConstructExprClass:
12184 case Expr::CXXDependentScopeMemberExprClass:
12185 case Expr::UnresolvedMemberExprClass:
12186 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000012187 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012188 case Expr::ObjCArrayLiteralClass:
12189 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012190 case Expr::ObjCEncodeExprClass:
12191 case Expr::ObjCMessageExprClass:
12192 case Expr::ObjCSelectorExprClass:
12193 case Expr::ObjCProtocolExprClass:
12194 case Expr::ObjCIvarRefExprClass:
12195 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012196 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000012197 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000012198 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000012199 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000012200 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000012201 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000012202 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000012203 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000012204 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000012205 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000012206 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000012207 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000012208 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000012209 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000012210 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000012211 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000012212 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000012213 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000012214 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000012215 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000012216 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012217 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000012218
Richard Smithf137f932014-01-25 20:50:08 +000012219 case Expr::InitListExprClass: {
12220 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
12221 // form "T x = { a };" is equivalent to "T x = a;".
12222 // Unless we're initializing a reference, T is a scalar as it is known to be
12223 // of integral or enumeration type.
12224 if (E->isRValue())
12225 if (cast<InitListExpr>(E)->getNumInits() == 1)
12226 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012227 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000012228 }
12229
Douglas Gregor820ba7b2011-01-04 17:33:58 +000012230 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000012231 case Expr::GNUNullExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +000012232 case Expr::SourceLocExprClass:
John McCall864e3962010-05-07 05:32:02 +000012233 return NoDiag();
12234
John McCall7c454bb2011-07-15 05:09:51 +000012235 case Expr::SubstNonTypeTemplateParmExprClass:
12236 return
12237 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12238
Bill Wendling7c44da22018-10-31 03:48:47 +000012239 case Expr::ConstantExprClass:
12240 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12241
John McCall864e3962010-05-07 05:32:02 +000012242 case Expr::ParenExprClass:
12243 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000012244 case Expr::GenericSelectionExprClass:
12245 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012246 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000012247 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012248 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012249 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000012250 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000012251 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000012252 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000012253 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000012254 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000012255 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000012256 return NoDiag();
12257 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000012258 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000012259 // C99 6.6/3 allows function calls within unevaluated subexpressions of
12260 // constant expressions, but they can never be ICEs because an ICE cannot
12261 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000012262 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000012263 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000012264 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012265 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012266 }
Richard Smith6365c912012-02-24 22:12:32 +000012267 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000012268 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12269 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000012270 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012271 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000012272 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000012273 // Parameter variables are never constants. Without this check,
12274 // getAnyInitializer() can find a default argument, which leads
12275 // to chaos.
12276 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000012277 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000012278
12279 // C++ 7.1.5.1p2
12280 // A variable of non-volatile const-qualified integral or enumeration
12281 // type initialized by an ICE can be used in ICEs.
12282 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000012283 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000012284 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000012285
Richard Smithd0b4dd62011-12-19 06:19:21 +000012286 const VarDecl *VD;
12287 // Look for a declaration of this variable that has an initializer, and
12288 // check whether it is an ICE.
12289 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12290 return NoDiag();
12291 else
Richard Smith9e575da2012-12-28 13:25:52 +000012292 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000012293 }
12294 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012295 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000012296 }
John McCall864e3962010-05-07 05:32:02 +000012297 case Expr::UnaryOperatorClass: {
12298 const UnaryOperator *Exp = cast<UnaryOperator>(E);
12299 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000012300 case UO_PostInc:
12301 case UO_PostDec:
12302 case UO_PreInc:
12303 case UO_PreDec:
12304 case UO_AddrOf:
12305 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000012306 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000012307 // C99 6.6/3 allows increment and decrement within unevaluated
12308 // subexpressions of constant expressions, but they can never be ICEs
12309 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012310 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000012311 case UO_Extension:
12312 case UO_LNot:
12313 case UO_Plus:
12314 case UO_Minus:
12315 case UO_Not:
12316 case UO_Real:
12317 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000012318 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012319 }
Reid Klecknere540d972018-11-01 17:51:48 +000012320 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000012321 }
12322 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000012323 // Note that per C99, offsetof must be an ICE. And AFAIK, using
12324 // EvaluateAsRValue matches the proposed gcc behavior for cases like
12325 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
12326 // compliance: we should warn earlier for offsetof expressions with
12327 // array subscripts that aren't ICEs, and if the array subscripts
12328 // are ICEs, the value of the offsetof must be an integer constant.
12329 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000012330 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000012331 case Expr::UnaryExprOrTypeTraitExprClass: {
12332 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12333 if ((Exp->getKind() == UETT_SizeOf) &&
12334 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012335 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012336 return NoDiag();
12337 }
12338 case Expr::BinaryOperatorClass: {
12339 const BinaryOperator *Exp = cast<BinaryOperator>(E);
12340 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000012341 case BO_PtrMemD:
12342 case BO_PtrMemI:
12343 case BO_Assign:
12344 case BO_MulAssign:
12345 case BO_DivAssign:
12346 case BO_RemAssign:
12347 case BO_AddAssign:
12348 case BO_SubAssign:
12349 case BO_ShlAssign:
12350 case BO_ShrAssign:
12351 case BO_AndAssign:
12352 case BO_XorAssign:
12353 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000012354 // C99 6.6/3 allows assignments within unevaluated subexpressions of
12355 // constant expressions, but they can never be ICEs because an ICE cannot
12356 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012357 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012358
John McCalle3027922010-08-25 11:45:40 +000012359 case BO_Mul:
12360 case BO_Div:
12361 case BO_Rem:
12362 case BO_Add:
12363 case BO_Sub:
12364 case BO_Shl:
12365 case BO_Shr:
12366 case BO_LT:
12367 case BO_GT:
12368 case BO_LE:
12369 case BO_GE:
12370 case BO_EQ:
12371 case BO_NE:
12372 case BO_And:
12373 case BO_Xor:
12374 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000012375 case BO_Comma:
12376 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000012377 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12378 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000012379 if (Exp->getOpcode() == BO_Div ||
12380 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000012381 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000012382 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000012383 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000012384 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000012385 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012386 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012387 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000012388 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000012389 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012390 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012391 }
12392 }
12393 }
John McCalle3027922010-08-25 11:45:40 +000012394 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012395 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000012396 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12397 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000012398 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012399 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012400 } else {
12401 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012402 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012403 }
12404 }
Richard Smith9e575da2012-12-28 13:25:52 +000012405 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000012406 }
John McCalle3027922010-08-25 11:45:40 +000012407 case BO_LAnd:
12408 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000012409 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12410 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012411 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000012412 // Rare case where the RHS has a comma "side-effect"; we need
12413 // to actually check the condition to see whether the side
12414 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000012415 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000012416 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000012417 return RHSResult;
12418 return NoDiag();
12419 }
12420
Richard Smith9e575da2012-12-28 13:25:52 +000012421 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000012422 }
12423 }
Reid Klecknere540d972018-11-01 17:51:48 +000012424 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000012425 }
12426 case Expr::ImplicitCastExprClass:
12427 case Expr::CStyleCastExprClass:
12428 case Expr::CXXFunctionalCastExprClass:
12429 case Expr::CXXStaticCastExprClass:
12430 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000012431 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000012432 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000012433 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000012434 if (isa<ExplicitCastExpr>(E)) {
12435 if (const FloatingLiteral *FL
12436 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12437 unsigned DestWidth = Ctx.getIntWidth(E->getType());
12438 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12439 APSInt IgnoredVal(DestWidth, !DestSigned);
12440 bool Ignored;
12441 // If the value does not fit in the destination type, the behavior is
12442 // undefined, so we are not required to treat it as a constant
12443 // expression.
12444 if (FL->getValue().convertToInteger(IgnoredVal,
12445 llvm::APFloat::rmTowardZero,
12446 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012447 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000012448 return NoDiag();
12449 }
12450 }
Eli Friedman76d4e432011-09-29 21:49:34 +000012451 switch (cast<CastExpr>(E)->getCastKind()) {
12452 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000012453 case CK_AtomicToNonAtomic:
12454 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000012455 case CK_NoOp:
12456 case CK_IntegralToBoolean:
12457 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000012458 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000012459 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012460 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000012461 }
John McCall864e3962010-05-07 05:32:02 +000012462 }
John McCallc07a0c72011-02-17 10:25:35 +000012463 case Expr::BinaryConditionalOperatorClass: {
12464 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12465 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012466 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000012467 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012468 if (FalseResult.Kind == IK_NotICE) return FalseResult;
12469 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12470 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000012471 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000012472 return FalseResult;
12473 }
John McCall864e3962010-05-07 05:32:02 +000012474 case Expr::ConditionalOperatorClass: {
12475 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12476 // If the condition (ignoring parens) is a __builtin_constant_p call,
12477 // then only the true side is actually considered in an integer constant
12478 // expression, and it is fully evaluated. This is an important GNU
12479 // extension. See GCC PR38377 for discussion.
12480 if (const CallExpr *CallCE
12481 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000012482 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000012483 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000012484 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012485 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012486 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000012487
Richard Smithf57d8cb2011-12-09 22:58:01 +000012488 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12489 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000012490
Richard Smith9e575da2012-12-28 13:25:52 +000012491 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012492 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012493 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012494 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012495 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000012496 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012497 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000012498 return NoDiag();
12499 // Rare case where the diagnostics depend on which side is evaluated
12500 // Note that if we get here, CondResult is 0, and at least one of
12501 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000012502 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000012503 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000012504 return TrueResult;
12505 }
12506 case Expr::CXXDefaultArgExprClass:
12507 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000012508 case Expr::CXXDefaultInitExprClass:
12509 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012510 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000012511 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012512 }
12513 }
12514
David Blaikiee4d798f2012-01-20 21:50:17 +000012515 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000012516}
12517
Richard Smithf57d8cb2011-12-09 22:58:01 +000012518/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000012519static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000012520 const Expr *E,
12521 llvm::APSInt *Value,
12522 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000012523 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012524 if (Loc) *Loc = E->getExprLoc();
12525 return false;
12526 }
12527
Richard Smith66e05fe2012-01-18 05:21:49 +000012528 APValue Result;
12529 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000012530 return false;
12531
Richard Smith98710fc2014-11-13 23:03:19 +000012532 if (!Result.isInt()) {
12533 if (Loc) *Loc = E->getExprLoc();
12534 return false;
12535 }
12536
Richard Smith66e05fe2012-01-18 05:21:49 +000012537 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000012538 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012539}
12540
Craig Toppera31a8822013-08-22 07:09:37 +000012541bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
12542 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012543 assert(!isValueDependent() &&
12544 "Expression evaluator can't be called on a dependent expression.");
12545
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012546 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000012547 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000012548
Richard Smith9e575da2012-12-28 13:25:52 +000012549 ICEDiag D = CheckICE(this, Ctx);
12550 if (D.Kind != IK_ICE) {
12551 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000012552 return false;
12553 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000012554 return true;
12555}
12556
Craig Toppera31a8822013-08-22 07:09:37 +000012557bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000012558 SourceLocation *Loc, bool isEvaluated) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012559 assert(!isValueDependent() &&
12560 "Expression evaluator can't be called on a dependent expression.");
12561
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012562 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000012563 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
12564
12565 if (!isIntegerConstantExpr(Ctx, Loc))
12566 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000012567
Richard Smith5c40f092015-12-04 03:00:44 +000012568 // The only possible side-effects here are due to UB discovered in the
12569 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
12570 // required to treat the expression as an ICE, so we produce the folded
12571 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000012572 EvalResult ExprResult;
12573 Expr::EvalStatus Status;
12574 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
12575 Info.InConstantContext = true;
12576
12577 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000012578 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000012579
12580 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000012581 return true;
12582}
Richard Smith66e05fe2012-01-18 05:21:49 +000012583
Craig Toppera31a8822013-08-22 07:09:37 +000012584bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012585 assert(!isValueDependent() &&
12586 "Expression evaluator can't be called on a dependent expression.");
12587
Richard Smith9e575da2012-12-28 13:25:52 +000012588 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000012589}
12590
Craig Toppera31a8822013-08-22 07:09:37 +000012591bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000012592 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012593 assert(!isValueDependent() &&
12594 "Expression evaluator can't be called on a dependent expression.");
12595
Richard Smith66e05fe2012-01-18 05:21:49 +000012596 // We support this checking in C++98 mode in order to diagnose compatibility
12597 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012598 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000012599
Richard Smith98a0a492012-02-14 21:38:30 +000012600 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000012601 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012602 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000012603 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000012604 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000012605
12606 APValue Scratch;
12607 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
12608
12609 if (!Diags.empty()) {
12610 IsConstExpr = false;
12611 if (Loc) *Loc = Diags[0].first;
12612 } else if (!IsConstExpr) {
12613 // FIXME: This shouldn't happen.
12614 if (Loc) *Loc = getExprLoc();
12615 }
12616
12617 return IsConstExpr;
12618}
Richard Smith253c2a32012-01-27 01:14:48 +000012619
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012620bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
12621 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000012622 ArrayRef<const Expr*> Args,
12623 const Expr *This) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012624 assert(!isValueDependent() &&
12625 "Expression evaluator can't be called on a dependent expression.");
12626
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012627 Expr::EvalStatus Status;
12628 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000012629 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012630
George Burgess IV177399e2017-01-09 04:12:14 +000012631 LValue ThisVal;
12632 const LValue *ThisPtr = nullptr;
12633 if (This) {
12634#ifndef NDEBUG
12635 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
12636 assert(MD && "Don't provide `this` for non-methods.");
12637 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
12638#endif
12639 if (EvaluateObjectArgument(Info, This, ThisVal))
12640 ThisPtr = &ThisVal;
12641 if (Info.EvalStatus.HasSideEffects)
12642 return false;
12643 }
12644
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012645 ArgVector ArgValues(Args.size());
12646 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
12647 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000012648 if ((*I)->isValueDependent() ||
12649 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012650 // If evaluation fails, throw away the argument entirely.
12651 ArgValues[I - Args.begin()] = APValue();
12652 if (Info.EvalStatus.HasSideEffects)
12653 return false;
12654 }
12655
12656 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000012657 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012658 ArgValues.data());
12659 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
12660}
12661
Richard Smith253c2a32012-01-27 01:14:48 +000012662bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012663 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000012664 PartialDiagnosticAt> &Diags) {
12665 // FIXME: It would be useful to check constexpr function templates, but at the
12666 // moment the constant expression evaluator cannot cope with the non-rigorous
12667 // ASTs which we build for dependent expressions.
12668 if (FD->isDependentContext())
12669 return true;
12670
12671 Expr::EvalStatus Status;
12672 Status.Diag = &Diags;
12673
Richard Smith6d4c6582013-11-05 22:18:15 +000012674 EvalInfo Info(FD->getASTContext(), Status,
12675 EvalInfo::EM_PotentialConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000012676 Info.InConstantContext = true;
Richard Smith253c2a32012-01-27 01:14:48 +000012677
12678 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000012679 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000012680
Richard Smith7525ff62013-05-09 07:14:00 +000012681 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000012682 // is a temporary being used as the 'this' pointer.
12683 LValue This;
12684 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000012685 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000012686
Richard Smith253c2a32012-01-27 01:14:48 +000012687 ArrayRef<const Expr*> Args;
12688
Richard Smith2e312c82012-03-03 22:46:17 +000012689 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000012690 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
12691 // Evaluate the call as a constant initializer, to allow the construction
12692 // of objects of non-literal types.
12693 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000012694 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
12695 } else {
12696 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000012697 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000012698 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000012699 }
Richard Smith253c2a32012-01-27 01:14:48 +000012700
12701 return Diags.empty();
12702}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012703
12704bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
12705 const FunctionDecl *FD,
12706 SmallVectorImpl<
12707 PartialDiagnosticAt> &Diags) {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012708 assert(!E->isValueDependent() &&
12709 "Expression evaluator can't be called on a dependent expression.");
12710
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012711 Expr::EvalStatus Status;
12712 Status.Diag = &Diags;
12713
12714 EvalInfo Info(FD->getASTContext(), Status,
12715 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000012716 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012717
12718 // Fabricate a call stack frame to give the arguments a plausible cover story.
12719 ArrayRef<const Expr*> Args;
12720 ArgVector ArgValues(0);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012721 bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012722 (void)Success;
12723 assert(Success &&
12724 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000012725 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012726
12727 APValue ResultScratch;
12728 Evaluate(ResultScratch, Info, E);
12729 return Diags.empty();
12730}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012731
12732bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
12733 unsigned Type) const {
12734 if (!getType()->isPointerType())
12735 return false;
12736
12737 Expr::EvalStatus Status;
12738 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000012739 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012740}