blob: 508456422b6b978f3b675b5d7cf5c949a6ba255a [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"
Fangrui Song407659a2018-11-30 23:41:18 +000050#include "llvm/Support/SaveAndRestore.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000051#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000052#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000053#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000054
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000055#define DEBUG_TYPE "exprconstant"
56
Anders Carlsson7a241ba2008-07-03 04:20:39 +000057using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000058using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000059using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000060
Richard Smithb228a862012-02-15 02:18:13 +000061static bool IsGlobalLValue(APValue::LValueBase B);
62
John McCall93d91dc2010-05-07 17:22:02 +000063namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000064 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000065 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000066 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000067
Eric Fiselier708afb52019-05-16 21:04:15 +000068 using SourceLocExprScopeGuard =
69 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
70
Richard Smithb228a862012-02-15 02:18:13 +000071 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000072 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000073 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000074 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000075 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000076 //
77 // extern int arr[]; void f() { extern int arr[3]; };
78 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000079 //
80 // For now, we take the array bound from the most recent declaration.
81 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
82 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
83 QualType T = Redecl->getType();
84 if (!T->isIncompleteArrayType())
85 return T;
86 }
87 return D->getType();
88 }
Richard Smith84401042013-06-03 05:03:02 +000089
Mikael Holmen3b6b2e32019-05-20 11:38:33 +000090 if (B.is<TypeInfoLValue>())
Richard Smithee0ce3022019-05-17 07:06:46 +000091 return B.getTypeInfoType();
92
Richard Smith84401042013-06-03 05:03:02 +000093 const Expr *Base = B.get<const Expr*>();
94
95 // For a materialized temporary, the type of the temporary we materialized
96 // may not be the type of the expression.
97 if (const MaterializeTemporaryExpr *MTE =
98 dyn_cast<MaterializeTemporaryExpr>(Base)) {
99 SmallVector<const Expr *, 2> CommaLHSs;
100 SmallVector<SubobjectAdjustment, 2> Adjustments;
101 const Expr *Temp = MTE->GetTemporaryExpr();
102 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
103 Adjustments);
104 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +0000105 // for it directly. Otherwise use the type after adjustment.
106 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +0000107 return Inner->getType();
108 }
109
110 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000111 }
112
Richard Smithd62306a2011-11-10 06:34:14 +0000113 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000114 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000115 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000116 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000117 }
118 /// Get an LValue path entry, which is known to not be an array index, as a
119 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000120 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000121 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000122 }
123 /// Determine whether this LValue path entry for a base class names a virtual
124 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000125 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000126 return E.getAsBaseOrMember().getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000127 }
128
George Burgess IVe3763372016-12-22 02:50:20 +0000129 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
130 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
131 const FunctionDecl *Callee = CE->getDirectCallee();
132 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
133 }
134
135 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
136 /// This will look through a single cast.
137 ///
138 /// Returns null if we couldn't unwrap a function with alloc_size.
139 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
140 if (!E->getType()->isPointerType())
141 return nullptr;
142
143 E = E->IgnoreParens();
144 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000145 // probably be a cast of some kind. In exotic cases, we might also see a
146 // top-level ExprWithCleanups. Ignore them either way.
Bill Wendling7c44da22018-10-31 03:48:47 +0000147 if (const auto *FE = dyn_cast<FullExpr>(E))
148 E = FE->getSubExpr()->IgnoreParens();
George Burgess IV47638762018-03-07 04:52:34 +0000149
George Burgess IVe3763372016-12-22 02:50:20 +0000150 if (const auto *Cast = dyn_cast<CastExpr>(E))
151 E = Cast->getSubExpr()->IgnoreParens();
152
153 if (const auto *CE = dyn_cast<CallExpr>(E))
154 return getAllocSizeAttr(CE) ? CE : nullptr;
155 return nullptr;
156 }
157
158 /// Determines whether or not the given Base contains a call to a function
159 /// with the alloc_size attribute.
160 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
161 const auto *E = Base.dyn_cast<const Expr *>();
162 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
163 }
164
Richard Smith6f4f0f12017-10-20 22:56:25 +0000165 /// The bound to claim that an array of unknown bound has.
166 /// The value in MostDerivedArraySize is undefined in this case. So, set it
167 /// to an arbitrary value that's likely to loudly break things if it's used.
168 static const uint64_t AssumedSizeForUnsizedArray =
169 std::numeric_limits<uint64_t>::max() / 2;
170
George Burgess IVe3763372016-12-22 02:50:20 +0000171 /// Determines if an LValue with the given LValueBase will have an unsized
172 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000173 /// Find the path length and type of the most-derived subobject in the given
174 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000175 static unsigned
176 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
177 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000178 uint64_t &ArraySize, QualType &Type, bool &IsArray,
179 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000180 // This only accepts LValueBases from APValues, and APValues don't support
181 // arrays that lack size info.
182 assert(!isBaseAnAllocSizeCall(Base) &&
183 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000184 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000185 Type = getType(Base);
186
Richard Smith80815602011-11-07 05:07:52 +0000187 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000188 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000189 const ArrayType *AT = Ctx.getAsArrayType(Type);
190 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000191 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000192 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000193
194 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
195 ArraySize = CAT->getSize().getZExtValue();
196 } else {
197 assert(I == 0 && "unexpected unsized array designator");
198 FirstEntryIsUnsizedArray = true;
199 ArraySize = AssumedSizeForUnsizedArray;
200 }
Richard Smith66c96992012-02-18 22:04:06 +0000201 } else if (Type->isAnyComplexType()) {
202 const ComplexType *CT = Type->castAs<ComplexType>();
203 Type = CT->getElementType();
204 ArraySize = 2;
205 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000206 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000207 } else if (const FieldDecl *FD = getAsField(Path[I])) {
208 Type = FD->getType();
209 ArraySize = 0;
210 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000211 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000212 } else {
Richard Smith80815602011-11-07 05:07:52 +0000213 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000214 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000215 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000216 }
Richard Smith80815602011-11-07 05:07:52 +0000217 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000218 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000219 }
220
Richard Smitha8105bc2012-01-06 16:39:00 +0000221 // The order of this enum is important for diagnostics.
222 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000223 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smithdebad642019-05-12 09:39:08 +0000224 CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000225 };
226
Richard Smith96e0c102011-11-04 02:25:55 +0000227 /// A path from a glvalue to a subobject of that glvalue.
228 struct SubobjectDesignator {
229 /// True if the subobject was named in a manner not supported by C++11. Such
230 /// lvalues can still be folded, but they are not core constant expressions
231 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000232 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000233
Richard Smitha8105bc2012-01-06 16:39:00 +0000234 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000235 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000236
Daniel Jasperffdee092017-05-02 19:21:42 +0000237 /// Indicator of whether the first entry is an unsized array.
238 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000239
George Burgess IVa51c4072015-10-16 01:49:01 +0000240 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000241 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000242
Richard Smitha8105bc2012-01-06 16:39:00 +0000243 /// The length of the path to the most-derived object of which this is a
244 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000245 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000246
George Burgess IVa51c4072015-10-16 01:49:01 +0000247 /// The size of the array of which the most-derived object is an element.
248 /// This will always be 0 if the most-derived object is not an array
249 /// element. 0 is not an indicator of whether or not the most-derived object
250 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000251 ///
252 /// If the current array is an unsized array, the value of this is
253 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000254 uint64_t MostDerivedArraySize;
255
256 /// The type of the most derived object referred to by this address.
257 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000258
Richard Smith80815602011-11-07 05:07:52 +0000259 typedef APValue::LValuePathEntry PathEntry;
260
Richard Smith96e0c102011-11-04 02:25:55 +0000261 /// The entries on the path from the glvalue to the designated subobject.
262 SmallVector<PathEntry, 8> Entries;
263
Richard Smitha8105bc2012-01-06 16:39:00 +0000264 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000265
Richard Smitha8105bc2012-01-06 16:39:00 +0000266 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000267 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000268 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000269 MostDerivedPathLength(0), MostDerivedArraySize(0),
270 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000271
272 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000273 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000274 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000275 MostDerivedPathLength(0), MostDerivedArraySize(0) {
276 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000277 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000278 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000279 ArrayRef<PathEntry> VEntries = V.getLValuePath();
280 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000281 if (V.getLValueBase()) {
282 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000283 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000284 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000285 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000286 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000287 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000288 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000289 }
Richard Smith80815602011-11-07 05:07:52 +0000290 }
291 }
292
Richard Smith96e0c102011-11-04 02:25:55 +0000293 void setInvalid() {
294 Invalid = true;
295 Entries.clear();
296 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000297
George Burgess IVe3763372016-12-22 02:50:20 +0000298 /// Determine whether the most derived subobject is an array without a
299 /// known bound.
300 bool isMostDerivedAnUnsizedArray() const {
301 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000302 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000303 }
304
305 /// Determine what the most derived array's size is. Results in an assertion
306 /// failure if the most derived array lacks a size.
307 uint64_t getMostDerivedArraySize() const {
308 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
309 return MostDerivedArraySize;
310 }
311
Richard Smitha8105bc2012-01-06 16:39:00 +0000312 /// Determine whether this is a one-past-the-end pointer.
313 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000314 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000315 if (IsOnePastTheEnd)
316 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000317 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smith5b5e27a2019-05-10 20:05:31 +0000318 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
319 MostDerivedArraySize)
Richard Smitha8105bc2012-01-06 16:39:00 +0000320 return true;
321 return false;
322 }
323
Richard Smith06f71b52018-08-04 00:57:17 +0000324 /// Get the range of valid index adjustments in the form
325 /// {maximum value that can be subtracted from this pointer,
326 /// maximum value that can be added to this pointer}
327 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
328 if (Invalid || isMostDerivedAnUnsizedArray())
329 return {0, 0};
330
331 // [expr.add]p4: For the purposes of these operators, a pointer to a
332 // nonarray object behaves the same as a pointer to the first element of
333 // an array of length one with the type of the object as its element type.
334 bool IsArray = MostDerivedPathLength == Entries.size() &&
335 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000336 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
337 : (uint64_t)IsOnePastTheEnd;
Richard Smith06f71b52018-08-04 00:57:17 +0000338 uint64_t ArraySize =
339 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
340 return {ArrayIndex, ArraySize - ArrayIndex};
341 }
342
Richard Smitha8105bc2012-01-06 16:39:00 +0000343 /// Check that this refers to a valid subobject.
344 bool isValidSubobject() const {
345 if (Invalid)
346 return false;
347 return !isOnePastTheEnd();
348 }
349 /// Check that this refers to a valid subobject, and if not, produce a
350 /// relevant diagnostic and set the designator as invalid.
351 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
352
Richard Smith06f71b52018-08-04 00:57:17 +0000353 /// Get the type of the designated object.
354 QualType getType(ASTContext &Ctx) const {
355 assert(!Invalid && "invalid designator has no subobject type");
356 return MostDerivedPathLength == Entries.size()
357 ? MostDerivedType
358 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
359 }
360
Richard Smitha8105bc2012-01-06 16:39:00 +0000361 /// Update this designator to refer to the first element within this array.
362 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000363 Entries.push_back(PathEntry::ArrayIndex(0));
Richard Smitha8105bc2012-01-06 16:39:00 +0000364
365 // This is a most-derived object.
366 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000367 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000368 MostDerivedArraySize = CAT->getSize().getZExtValue();
369 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000370 }
George Burgess IVe3763372016-12-22 02:50:20 +0000371 /// Update this designator to refer to the first element within the array of
372 /// elements of type T. This is an array of unknown size.
373 void addUnsizedArrayUnchecked(QualType ElemTy) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000374 Entries.push_back(PathEntry::ArrayIndex(0));
George Burgess IVe3763372016-12-22 02:50:20 +0000375
376 MostDerivedType = ElemTy;
377 MostDerivedIsArrayElement = true;
378 // The value in MostDerivedArraySize is undefined in this case. So, set it
379 // to an arbitrary value that's likely to loudly break things if it's
380 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000381 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000382 MostDerivedPathLength = Entries.size();
383 }
Richard Smith96e0c102011-11-04 02:25:55 +0000384 /// Update this designator to refer to the given base or member of this
385 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000386 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000387 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
Richard Smitha8105bc2012-01-06 16:39:00 +0000388
389 // If this isn't a base class, it's a new most-derived object.
390 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
391 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000392 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000393 MostDerivedArraySize = 0;
394 MostDerivedPathLength = Entries.size();
395 }
Richard Smith96e0c102011-11-04 02:25:55 +0000396 }
Richard Smith66c96992012-02-18 22:04:06 +0000397 /// Update this designator to refer to the given complex component.
398 void addComplexUnchecked(QualType EltTy, bool Imag) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000399 Entries.push_back(PathEntry::ArrayIndex(Imag));
Richard Smith66c96992012-02-18 22:04:06 +0000400
401 // This is technically a most-derived object, though in practice this
402 // is unlikely to matter.
403 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000404 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000405 MostDerivedArraySize = 2;
406 MostDerivedPathLength = Entries.size();
407 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000408 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000409 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
410 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000411 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000412 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
413 if (Invalid || !N) return;
414 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
415 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000416 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000417 // Can't verify -- trust that the user is doing the right thing (or if
418 // not, trust that the caller will catch the bad behavior).
419 // FIXME: Should we reject if this overflows, at least?
Richard Smith5b5e27a2019-05-10 20:05:31 +0000420 Entries.back() = PathEntry::ArrayIndex(
421 Entries.back().getAsArrayIndex() + TruncatedN);
Daniel Jasperffdee092017-05-02 19:21:42 +0000422 return;
423 }
424
425 // [expr.add]p4: For the purposes of these operators, a pointer to a
426 // nonarray object behaves the same as a pointer to the first element of
427 // an array of length one with the type of the object as its element type.
428 bool IsArray = MostDerivedPathLength == Entries.size() &&
429 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000430 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
431 : (uint64_t)IsOnePastTheEnd;
Daniel Jasperffdee092017-05-02 19:21:42 +0000432 uint64_t ArraySize =
433 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
434
435 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
436 // Calculate the actual index in a wide enough type, so we can include
437 // it in the note.
438 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
439 (llvm::APInt&)N += ArrayIndex;
440 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
441 diagnosePointerArithmetic(Info, E, N);
442 setInvalid();
443 return;
444 }
445
446 ArrayIndex += TruncatedN;
447 assert(ArrayIndex <= ArraySize &&
448 "bounds check succeeded for out-of-bounds index");
449
450 if (IsArray)
Richard Smith5b5e27a2019-05-10 20:05:31 +0000451 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
Daniel Jasperffdee092017-05-02 19:21:42 +0000452 else
453 IsOnePastTheEnd = (ArrayIndex != 0);
454 }
Richard Smith96e0c102011-11-04 02:25:55 +0000455 };
456
Richard Smith254a73d2011-10-28 22:34:42 +0000457 /// A stack frame in the constexpr call stack.
458 struct CallStackFrame {
459 EvalInfo &Info;
460
461 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000462 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000463
Richard Smithf6f003a2011-12-16 19:06:07 +0000464 /// Callee - The function which was called.
465 const FunctionDecl *Callee;
466
Richard Smithd62306a2011-11-10 06:34:14 +0000467 /// This - The binding for the this pointer in this call, if any.
468 const LValue *This;
469
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000470 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000471 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000472 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000473
Eric Fiselier708afb52019-05-16 21:04:15 +0000474 /// Source location information about the default argument or default
475 /// initializer expression we're evaluating, if any.
476 CurrentSourceLocExprScope CurSourceLocExprScope;
477
Eli Friedman4830ec82012-06-25 21:21:08 +0000478 // Note that we intentionally use std::map here so that references to
479 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000480 typedef std::pair<const void *, unsigned> MapKeyTy;
481 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000482 /// Temporaries - Temporary lvalues materialized within this stack frame.
483 MapTy Temporaries;
484
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000485 /// CallLoc - The location of the call expression for this call.
486 SourceLocation CallLoc;
487
488 /// Index - The call index of this call.
489 unsigned Index;
490
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000491 /// The stack of integers for tracking version numbers for temporaries.
492 SmallVector<unsigned, 2> TempVersionStack = {1};
493 unsigned CurTempVersion = TempVersionStack.back();
494
495 unsigned getTempVersion() const { return TempVersionStack.back(); }
496
497 void pushTempVersion() {
498 TempVersionStack.push_back(++CurTempVersion);
499 }
500
501 void popTempVersion() {
502 TempVersionStack.pop_back();
503 }
504
Faisal Vali051e3a22017-02-16 04:12:21 +0000505 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000506 // on the overall stack usage of deeply-recursing constexpr evaluations.
Faisal Vali051e3a22017-02-16 04:12:21 +0000507 // (We should cache this map rather than recomputing it repeatedly.)
508 // But let's try this and see how it goes; we can look into caching the map
509 // as a later change.
510
511 /// LambdaCaptureFields - Mapping from captured variables/this to
512 /// corresponding data members in the closure class.
513 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
514 FieldDecl *LambdaThisCaptureField;
515
Richard Smithf6f003a2011-12-16 19:06:07 +0000516 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
517 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000518 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000519 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000520
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000521 // Return the temporary for Key whose version number is Version.
522 APValue *getTemporary(const void *Key, unsigned Version) {
523 MapKeyTy KV(Key, Version);
524 auto LB = Temporaries.lower_bound(KV);
525 if (LB != Temporaries.end() && LB->first == KV)
526 return &LB->second;
527 // Pair (Key,Version) wasn't found in the map. Check that no elements
528 // in the map have 'Key' as their key.
529 assert((LB == Temporaries.end() || LB->first.first != Key) &&
530 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
531 "Element with key 'Key' found in map");
532 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000533 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000534
535 // Return the current temporary for Key in the map.
536 APValue *getCurrentTemporary(const void *Key) {
537 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
538 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
539 return &std::prev(UB)->second;
540 return nullptr;
541 }
542
543 // Return the version number of the current temporary for Key.
544 unsigned getCurrentTemporaryVersion(const void *Key) const {
545 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
546 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
547 return std::prev(UB)->first.second;
548 return 0;
549 }
550
Richard Smith08d6a2c2013-07-24 07:11:57 +0000551 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000552 };
553
Richard Smith852c9db2013-04-20 22:23:05 +0000554 /// Temporarily override 'this'.
555 class ThisOverrideRAII {
556 public:
557 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
558 : Frame(Frame), OldThis(Frame.This) {
559 if (Enable)
560 Frame.This = NewThis;
561 }
562 ~ThisOverrideRAII() {
563 Frame.This = OldThis;
564 }
565 private:
566 CallStackFrame &Frame;
567 const LValue *OldThis;
568 };
569
Richard Smith92b1ce02011-12-12 09:28:41 +0000570 /// A partial diagnostic which we might know in advance that we are not going
571 /// to emit.
572 class OptionalDiagnostic {
573 PartialDiagnostic *Diag;
574
575 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000576 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
577 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000578
579 template<typename T>
580 OptionalDiagnostic &operator<<(const T &v) {
581 if (Diag)
582 *Diag << v;
583 return *this;
584 }
Richard Smithfe800032012-01-31 04:08:20 +0000585
586 OptionalDiagnostic &operator<<(const APSInt &I) {
587 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000588 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000589 I.toString(Buffer);
590 *Diag << StringRef(Buffer.data(), Buffer.size());
591 }
592 return *this;
593 }
594
595 OptionalDiagnostic &operator<<(const APFloat &F) {
596 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000597 // FIXME: Force the precision of the source value down so we don't
598 // print digits which are usually useless (we don't really care here if
599 // we truncate a digit by accident in edge cases). Ideally,
Fangrui Song6907ce22018-07-30 19:24:48 +0000600 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000601 // representation which rounds to the correct value, but it's a bit
602 // tricky to implement.
603 unsigned precision =
604 llvm::APFloat::semanticsPrecision(F.getSemantics());
605 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000606 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000607 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000608 *Diag << StringRef(Buffer.data(), Buffer.size());
609 }
610 return *this;
611 }
Leonard Chand3f3e162019-01-18 21:04:25 +0000612
613 OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
614 if (Diag) {
615 SmallVector<char, 32> Buffer;
616 FX.toString(Buffer);
617 *Diag << StringRef(Buffer.data(), Buffer.size());
618 }
619 return *this;
620 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000621 };
622
Richard Smith08d6a2c2013-07-24 07:11:57 +0000623 /// A cleanup, and a flag indicating whether it is lifetime-extended.
624 class Cleanup {
625 llvm::PointerIntPair<APValue*, 1, bool> Value;
626
627 public:
628 Cleanup(APValue *Val, bool IsLifetimeExtended)
629 : Value(Val, IsLifetimeExtended) {}
630
631 bool isLifetimeExtended() const { return Value.getInt(); }
632 void endLifetime() {
633 *Value.getPointer() = APValue();
634 }
635 };
636
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000637 /// A reference to an object whose construction we are currently evaluating.
638 struct ObjectUnderConstruction {
639 APValue::LValueBase Base;
640 ArrayRef<APValue::LValuePathEntry> Path;
641 friend bool operator==(const ObjectUnderConstruction &LHS,
642 const ObjectUnderConstruction &RHS) {
643 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
644 }
645 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
646 return llvm::hash_combine(Obj.Base, Obj.Path);
647 }
648 };
649 enum class ConstructionPhase { None, Bases, AfterBases };
650}
651
652namespace llvm {
653template<> struct DenseMapInfo<ObjectUnderConstruction> {
654 using Base = DenseMapInfo<APValue::LValueBase>;
655 static ObjectUnderConstruction getEmptyKey() {
656 return {Base::getEmptyKey(), {}}; }
657 static ObjectUnderConstruction getTombstoneKey() {
658 return {Base::getTombstoneKey(), {}};
659 }
660 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
661 return hash_value(Object);
662 }
663 static bool isEqual(const ObjectUnderConstruction &LHS,
664 const ObjectUnderConstruction &RHS) {
665 return LHS == RHS;
666 }
667};
668}
669
670namespace {
Richard Smithb228a862012-02-15 02:18:13 +0000671 /// EvalInfo - This is a private struct used by the evaluator to capture
672 /// information about a subexpression as it is folded. It retains information
673 /// about the AST context, but also maintains information about the folded
674 /// expression.
675 ///
676 /// If an expression could be evaluated, it is still possible it is not a C
677 /// "integer constant expression" or constant expression. If not, this struct
678 /// captures information about how and why not.
679 ///
680 /// One bit of information passed *into* the request for constant folding
681 /// indicates whether the subexpression is "evaluated" or not according to C
682 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
683 /// evaluate the expression regardless of what the RHS is, but C only allows
684 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000685 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000686 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000687
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000688 /// EvalStatus - Contains information about the evaluation.
689 Expr::EvalStatus &EvalStatus;
690
691 /// CurrentCall - The top of the constexpr call stack.
692 CallStackFrame *CurrentCall;
693
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000694 /// CallStackDepth - The number of calls in the call stack right now.
695 unsigned CallStackDepth;
696
Richard Smithb228a862012-02-15 02:18:13 +0000697 /// NextCallIndex - The next call index to assign.
698 unsigned NextCallIndex;
699
Richard Smitha3d3bd22013-05-08 02:12:03 +0000700 /// StepsLeft - The remaining number of evaluation steps we're permitted
701 /// to perform. This is essentially a limit for the number of statements
702 /// we will evaluate.
703 unsigned StepsLeft;
704
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000705 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000706 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000707 CallStackFrame BottomFrame;
708
Richard Smith08d6a2c2013-07-24 07:11:57 +0000709 /// A stack of values whose lifetimes end at the end of some surrounding
710 /// evaluation frame.
711 llvm::SmallVector<Cleanup, 16> CleanupStack;
712
Richard Smithd62306a2011-11-10 06:34:14 +0000713 /// EvaluatingDecl - This is the declaration whose initializer is being
714 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000715 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000716
717 /// EvaluatingDeclValue - This is the value being constructed for the
718 /// declaration whose initializer is being evaluated, if any.
719 APValue *EvaluatingDeclValue;
720
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000721 /// Set of objects that are currently being constructed.
722 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
723 ObjectsUnderConstruction;
Erik Pilkington42925492017-10-04 00:18:55 +0000724
725 struct EvaluatingConstructorRAII {
726 EvalInfo &EI;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000727 ObjectUnderConstruction Object;
Erik Pilkington42925492017-10-04 00:18:55 +0000728 bool DidInsert;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000729 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
730 bool HasBases)
Erik Pilkington42925492017-10-04 00:18:55 +0000731 : EI(EI), Object(Object) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000732 DidInsert =
733 EI.ObjectsUnderConstruction
734 .insert({Object, HasBases ? ConstructionPhase::Bases
735 : ConstructionPhase::AfterBases})
736 .second;
737 }
738 void finishedConstructingBases() {
739 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
Erik Pilkington42925492017-10-04 00:18:55 +0000740 }
741 ~EvaluatingConstructorRAII() {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000742 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
Erik Pilkington42925492017-10-04 00:18:55 +0000743 }
744 };
745
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000746 ConstructionPhase
747 isEvaluatingConstructor(APValue::LValueBase Base,
748 ArrayRef<APValue::LValuePathEntry> Path) {
749 return ObjectsUnderConstruction.lookup({Base, Path});
Erik Pilkington42925492017-10-04 00:18:55 +0000750 }
751
Richard Smith37be3362019-05-04 04:00:45 +0000752 /// If we're currently speculatively evaluating, the outermost call stack
753 /// depth at which we can mutate state, otherwise 0.
754 unsigned SpeculativeEvaluationDepth = 0;
755
Richard Smith410306b2016-12-12 02:53:20 +0000756 /// The current array initialization index, if we're performing array
757 /// initialization.
758 uint64_t ArrayInitIndex = -1;
759
Richard Smith357362d2011-12-13 06:39:58 +0000760 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
761 /// notes attached to it will also be stored, otherwise they will not be.
762 bool HasActiveDiagnostic;
763
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000764 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000765 /// fold (not just why it's not strictly a constant expression)?
766 bool HasFoldFailureDiagnostic;
767
Fangrui Song407659a2018-11-30 23:41:18 +0000768 /// Whether or not we're in a context where the front end requires a
769 /// constant value.
770 bool InConstantContext;
771
Richard Smith6d4c6582013-11-05 22:18:15 +0000772 enum EvaluationMode {
773 /// Evaluate as a constant expression. Stop if we find that the expression
774 /// is not a constant expression.
775 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000776
Richard Smith6d4c6582013-11-05 22:18:15 +0000777 /// Evaluate as a potential constant expression. Keep going if we hit a
778 /// construct that we can't evaluate yet (because we don't yet know the
779 /// value of something) but stop if we hit something that could never be
780 /// a constant expression.
781 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000782
Richard Smith6d4c6582013-11-05 22:18:15 +0000783 /// Fold the expression to a constant. Stop if we hit a side-effect that
784 /// we can't model.
785 EM_ConstantFold,
786
787 /// Evaluate the expression looking for integer overflow and similar
788 /// issues. Don't worry about side-effects, and try to visit all
789 /// subexpressions.
790 EM_EvaluateForOverflow,
791
792 /// Evaluate in any way we know how. Don't worry about side-effects that
793 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000794 EM_IgnoreSideEffects,
795
796 /// Evaluate as a constant expression. Stop if we find that the expression
797 /// is not a constant expression. Some expressions can be retried in the
798 /// optimizer if we don't constant fold them here, but in an unevaluated
799 /// context we try to fold them immediately since the optimizer never
800 /// gets a chance to look at it.
801 EM_ConstantExpressionUnevaluated,
802
803 /// Evaluate as a potential constant expression. Keep going if we hit a
804 /// construct that we can't evaluate yet (because we don't yet know the
805 /// value of something) but stop if we hit something that could never be
806 /// a constant expression. Some expressions can be retried in the
807 /// optimizer if we don't constant fold them here, but in an unevaluated
808 /// context we try to fold them immediately since the optimizer never
809 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000810 EM_PotentialConstantExpressionUnevaluated,
Richard Smith6d4c6582013-11-05 22:18:15 +0000811 } EvalMode;
812
813 /// Are we checking whether the expression is a potential constant
814 /// expression?
815 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000816 return EvalMode == EM_PotentialConstantExpression ||
817 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000818 }
819
820 /// Are we checking an expression for overflow?
821 // FIXME: We should check for any kind of undefined or suspicious behavior
822 // in such constructs, not just overflow.
823 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
824
825 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000826 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000827 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000828 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000829 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
830 EvaluatingDecl((const ValueDecl *)nullptr),
831 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
Richard Smith37be3362019-05-04 04:00:45 +0000832 HasFoldFailureDiagnostic(false),
Fangrui Song407659a2018-11-30 23:41:18 +0000833 InConstantContext(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000834
Richard Smith7525ff62013-05-09 07:14:00 +0000835 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
836 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000837 EvaluatingDeclValue = &Value;
838 }
839
David Blaikiebbafb8a2012-03-11 07:00:24 +0000840 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000841
Richard Smith357362d2011-12-13 06:39:58 +0000842 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000843 // Don't perform any constexpr calls (other than the call we're checking)
844 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000845 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000846 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000847 if (NextCallIndex == 0) {
848 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000849 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000850 return false;
851 }
Richard Smith357362d2011-12-13 06:39:58 +0000852 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
853 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000854 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000855 << getLangOpts().ConstexprCallDepth;
856 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000857 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000858
Richard Smith37be3362019-05-04 04:00:45 +0000859 std::pair<CallStackFrame *, unsigned>
860 getCallFrameAndDepth(unsigned CallIndex) {
861 assert(CallIndex && "no call index in getCallFrameAndDepth");
Richard Smithb228a862012-02-15 02:18:13 +0000862 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
863 // be null in this loop.
Richard Smith37be3362019-05-04 04:00:45 +0000864 unsigned Depth = CallStackDepth;
Richard Smithb228a862012-02-15 02:18:13 +0000865 CallStackFrame *Frame = CurrentCall;
Richard Smith37be3362019-05-04 04:00:45 +0000866 while (Frame->Index > CallIndex) {
Richard Smithb228a862012-02-15 02:18:13 +0000867 Frame = Frame->Caller;
Richard Smith37be3362019-05-04 04:00:45 +0000868 --Depth;
869 }
870 if (Frame->Index == CallIndex)
871 return {Frame, Depth};
872 return {nullptr, 0};
Richard Smithb228a862012-02-15 02:18:13 +0000873 }
874
Richard Smitha3d3bd22013-05-08 02:12:03 +0000875 bool nextStep(const Stmt *S) {
876 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000877 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000878 return false;
879 }
880 --StepsLeft;
881 return true;
882 }
883
Richard Smith357362d2011-12-13 06:39:58 +0000884 private:
885 /// Add a diagnostic to the diagnostics list.
886 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
887 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
888 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
889 return EvalStatus.Diag->back().second;
890 }
891
Richard Smithf6f003a2011-12-16 19:06:07 +0000892 /// Add notes containing a call stack to the current point of evaluation.
893 void addCallStack(unsigned Limit);
894
Faisal Valie690b7a2016-07-02 22:34:24 +0000895 private:
896 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
897 unsigned ExtraNotes, bool IsCCEDiag) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000898
Richard Smith92b1ce02011-12-12 09:28:41 +0000899 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000900 // If we have a prior diagnostic, it will be noting that the expression
901 // isn't a constant expression. This diagnostic is more important,
902 // unless we require this evaluation to produce a constant expression.
903 //
904 // FIXME: We might want to show both diagnostics to the user in
905 // EM_ConstantFold mode.
906 if (!EvalStatus.Diag->empty()) {
907 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000908 case EM_ConstantFold:
909 case EM_IgnoreSideEffects:
910 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000911 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000912 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000913 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000914 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000915 case EM_ConstantExpression:
916 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000917 case EM_ConstantExpressionUnevaluated:
918 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000919 HasActiveDiagnostic = false;
920 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000921 }
922 }
923
Richard Smithf6f003a2011-12-16 19:06:07 +0000924 unsigned CallStackNotes = CallStackDepth - 1;
925 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
926 if (Limit)
927 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000928 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000929 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000930
Richard Smith357362d2011-12-13 06:39:58 +0000931 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000932 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000933 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000934 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
935 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000936 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000937 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000938 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000939 }
Richard Smith357362d2011-12-13 06:39:58 +0000940 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000941 return OptionalDiagnostic();
942 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000943 public:
944 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
945 OptionalDiagnostic
946 FFDiag(SourceLocation Loc,
947 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
948 unsigned ExtraNotes = 0) {
949 return Diag(Loc, DiagId, ExtraNotes, false);
950 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000951
Faisal Valie690b7a2016-07-02 22:34:24 +0000952 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000953 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000954 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000955 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000956 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000957 HasActiveDiagnostic = false;
958 return OptionalDiagnostic();
959 }
960
Richard Smith92b1ce02011-12-12 09:28:41 +0000961 /// Diagnose that the evaluation does not produce a C++11 core constant
962 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000963 ///
964 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
965 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000966 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000967 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000968 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000969 // Don't override a previous diagnostic. Don't bother collecting
970 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000971 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000972 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000973 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000974 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000975 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000976 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000977 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
978 = diag::note_invalid_subexpr_in_const_expr,
979 unsigned ExtraNotes = 0) {
980 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
981 }
Richard Smith357362d2011-12-13 06:39:58 +0000982 /// Add a note to a prior diagnostic.
983 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
984 if (!HasActiveDiagnostic)
985 return OptionalDiagnostic();
986 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000987 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000988
989 /// Add a stack of notes to a prior diagnostic.
990 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
991 if (HasActiveDiagnostic) {
992 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
993 Diags.begin(), Diags.end());
994 }
995 }
Richard Smith253c2a32012-01-27 01:14:48 +0000996
Richard Smith6d4c6582013-11-05 22:18:15 +0000997 /// Should we continue evaluation after encountering a side-effect that we
998 /// couldn't model?
999 bool keepEvaluatingAfterSideEffect() {
1000 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00001001 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001002 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001003 case EM_EvaluateForOverflow:
1004 case EM_IgnoreSideEffects:
1005 return true;
1006
Richard Smith6d4c6582013-11-05 22:18:15 +00001007 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001008 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001009 case EM_ConstantFold:
1010 return false;
1011 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001012 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +00001013 }
1014
1015 /// Note that we have had a side-effect, and determine whether we should
1016 /// keep evaluating.
1017 bool noteSideEffect() {
1018 EvalStatus.HasSideEffects = true;
1019 return keepEvaluatingAfterSideEffect();
1020 }
1021
Richard Smithce8eca52015-12-08 03:21:47 +00001022 /// Should we continue evaluation after encountering undefined behavior?
1023 bool keepEvaluatingAfterUndefinedBehavior() {
1024 switch (EvalMode) {
1025 case EM_EvaluateForOverflow:
1026 case EM_IgnoreSideEffects:
1027 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +00001028 return true;
1029
1030 case EM_PotentialConstantExpression:
1031 case EM_PotentialConstantExpressionUnevaluated:
1032 case EM_ConstantExpression:
1033 case EM_ConstantExpressionUnevaluated:
1034 return false;
1035 }
1036 llvm_unreachable("Missed EvalMode case");
1037 }
1038
1039 /// Note that we hit something that was technically undefined behavior, but
1040 /// that we can evaluate past it (such as signed overflow or floating-point
1041 /// division by zero.)
1042 bool noteUndefinedBehavior() {
1043 EvalStatus.HasUndefinedBehavior = true;
1044 return keepEvaluatingAfterUndefinedBehavior();
1045 }
1046
Richard Smith253c2a32012-01-27 01:14:48 +00001047 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001048 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +00001049 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +00001050 if (!StepsLeft)
1051 return false;
1052
1053 switch (EvalMode) {
1054 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001055 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001056 case EM_EvaluateForOverflow:
1057 return true;
1058
1059 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001060 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001061 case EM_ConstantFold:
1062 case EM_IgnoreSideEffects:
1063 return false;
1064 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001065 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001066 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001067
George Burgess IV8c892b52016-05-25 22:31:54 +00001068 /// Notes that we failed to evaluate an expression that other expressions
1069 /// directly depend on, and determine if we should keep evaluating. This
1070 /// should only be called if we actually intend to keep evaluating.
1071 ///
1072 /// Call noteSideEffect() instead if we may be able to ignore the value that
1073 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1074 ///
1075 /// (Foo(), 1) // use noteSideEffect
1076 /// (Foo() || true) // use noteSideEffect
1077 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001078 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001079 // Failure when evaluating some expression often means there is some
1080 // subexpression whose evaluation was skipped. Therefore, (because we
1081 // don't track whether we skipped an expression when unwinding after an
1082 // evaluation failure) every evaluation failure that bubbles up from a
1083 // subexpression implies that a side-effect has potentially happened. We
1084 // skip setting the HasSideEffects flag to true until we decide to
1085 // continue evaluating after that point, which happens here.
1086 bool KeepGoing = keepEvaluatingAfterFailure();
1087 EvalStatus.HasSideEffects |= KeepGoing;
1088 return KeepGoing;
1089 }
1090
Richard Smith410306b2016-12-12 02:53:20 +00001091 class ArrayInitLoopIndex {
1092 EvalInfo &Info;
1093 uint64_t OuterIndex;
1094
1095 public:
1096 ArrayInitLoopIndex(EvalInfo &Info)
1097 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1098 Info.ArrayInitIndex = 0;
1099 }
1100 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1101
1102 operator uint64_t&() { return Info.ArrayInitIndex; }
1103 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001104 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001105
1106 /// Object used to treat all foldable expressions as constant expressions.
1107 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001108 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001109 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001110 bool HadNoPriorDiags;
1111 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001112
Richard Smith6d4c6582013-11-05 22:18:15 +00001113 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1114 : Info(Info),
1115 Enabled(Enabled),
1116 HadNoPriorDiags(Info.EvalStatus.Diag &&
1117 Info.EvalStatus.Diag->empty() &&
1118 !Info.EvalStatus.HasSideEffects),
1119 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001120 if (Enabled &&
1121 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1122 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001123 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001124 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001125 void keepDiagnostics() { Enabled = false; }
1126 ~FoldConstant() {
1127 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001128 !Info.EvalStatus.HasSideEffects)
1129 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001130 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001131 }
1132 };
Richard Smith17100ba2012-02-16 02:46:34 +00001133
James Y Knight892b09b2018-10-10 02:53:43 +00001134 /// RAII object used to set the current evaluation mode to ignore
1135 /// side-effects.
1136 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001137 EvalInfo &Info;
1138 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001139 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001140 : Info(Info), OldMode(Info.EvalMode) {
1141 if (!Info.checkingPotentialConstantExpression())
James Y Knight892b09b2018-10-10 02:53:43 +00001142 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001143 }
1144
James Y Knight892b09b2018-10-10 02:53:43 +00001145 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001146 };
1147
George Burgess IV8c892b52016-05-25 22:31:54 +00001148 /// RAII object used to optionally suppress diagnostics and side-effects from
1149 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001150 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001151 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001152 Expr::EvalStatus OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001153 unsigned OldSpeculativeEvaluationDepth;
Richard Smith17100ba2012-02-16 02:46:34 +00001154
George Burgess IV8c892b52016-05-25 22:31:54 +00001155 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001156 Info = Other.Info;
1157 OldStatus = Other.OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001158 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001159 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001160 }
1161
1162 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001163 if (!Info)
1164 return;
1165
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001166 Info->EvalStatus = OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001167 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
George Burgess IV8c892b52016-05-25 22:31:54 +00001168 }
1169
Richard Smith17100ba2012-02-16 02:46:34 +00001170 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001171 SpeculativeEvaluationRAII() = default;
1172
1173 SpeculativeEvaluationRAII(
1174 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001175 : Info(&Info), OldStatus(Info.EvalStatus),
Richard Smith37be3362019-05-04 04:00:45 +00001176 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
Richard Smith17100ba2012-02-16 02:46:34 +00001177 Info.EvalStatus.Diag = NewDiag;
Richard Smith37be3362019-05-04 04:00:45 +00001178 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
Richard Smith17100ba2012-02-16 02:46:34 +00001179 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001180
1181 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1182 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1183 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001184 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001185
1186 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1187 maybeRestoreState();
1188 moveFromAndCancel(std::move(Other));
1189 return *this;
1190 }
1191
1192 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001193 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001194
1195 /// RAII object wrapping a full-expression or block scope, and handling
1196 /// the ending of the lifetime of temporaries created within it.
1197 template<bool IsFullExpression>
1198 class ScopeRAII {
1199 EvalInfo &Info;
1200 unsigned OldStackSize;
1201 public:
1202 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001203 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1204 // Push a new temporary version. This is needed to distinguish between
1205 // temporaries created in different iterations of a loop.
1206 Info.CurrentCall->pushTempVersion();
1207 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001208 ~ScopeRAII() {
1209 // Body moved to a static method to encourage the compiler to inline away
1210 // instances of this class.
1211 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001212 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001213 }
1214 private:
1215 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1216 unsigned NewEnd = OldStackSize;
1217 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1218 I != N; ++I) {
1219 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1220 // Full-expression cleanup of a lifetime-extended temporary: nothing
1221 // to do, just move this cleanup to the right place in the stack.
1222 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1223 ++NewEnd;
1224 } else {
1225 // End the lifetime of the object.
1226 Info.CleanupStack[I].endLifetime();
1227 }
1228 }
1229 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1230 Info.CleanupStack.end());
1231 }
1232 };
1233 typedef ScopeRAII<false> BlockScopeRAII;
1234 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001235}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001236
Richard Smitha8105bc2012-01-06 16:39:00 +00001237bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1238 CheckSubobjectKind CSK) {
1239 if (Invalid)
1240 return false;
1241 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001242 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001243 << CSK;
1244 setInvalid();
1245 return false;
1246 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001247 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1248 // must actually be at least one array element; even a VLA cannot have a
1249 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001250 return true;
1251}
1252
Richard Smith6f4f0f12017-10-20 22:56:25 +00001253void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1254 const Expr *E) {
1255 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1256 // Do not set the designator as invalid: we can represent this situation,
1257 // and correct handling of __builtin_object_size requires us to do so.
1258}
1259
Richard Smitha8105bc2012-01-06 16:39:00 +00001260void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001261 const Expr *E,
1262 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001263 // If we're complaining, we must be able to statically determine the size of
1264 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001265 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001266 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001267 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001268 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001269 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001270 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001271 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001272 setInvalid();
1273}
1274
Richard Smithf6f003a2011-12-16 19:06:07 +00001275CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1276 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001277 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001278 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1279 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001280 Info.CurrentCall = this;
1281 ++Info.CallStackDepth;
1282}
1283
1284CallStackFrame::~CallStackFrame() {
1285 assert(Info.CurrentCall == this && "calls retired out of order");
1286 --Info.CallStackDepth;
1287 Info.CurrentCall = Caller;
1288}
1289
Richard Smith08d6a2c2013-07-24 07:11:57 +00001290APValue &CallStackFrame::createTemporary(const void *Key,
1291 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001292 unsigned Version = Info.CurrentCall->getTempVersion();
1293 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smithe637cbe2019-05-21 23:15:18 +00001294 assert(Result.isAbsent() && "temporary created multiple times");
Richard Smith08d6a2c2013-07-24 07:11:57 +00001295 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1296 return Result;
1297}
1298
Richard Smith84401042013-06-03 05:03:02 +00001299static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001300
1301void EvalInfo::addCallStack(unsigned Limit) {
1302 // Determine which calls to skip, if any.
1303 unsigned ActiveCalls = CallStackDepth - 1;
1304 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1305 if (Limit && Limit < ActiveCalls) {
1306 SkipStart = Limit / 2 + Limit % 2;
1307 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001308 }
1309
Richard Smithf6f003a2011-12-16 19:06:07 +00001310 // Walk the call stack and add the diagnostics.
1311 unsigned CallIdx = 0;
1312 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1313 Frame = Frame->Caller, ++CallIdx) {
1314 // Skip this call?
1315 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1316 if (CallIdx == SkipStart) {
1317 // Note that we're skipping calls.
1318 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1319 << unsigned(ActiveCalls - Limit);
1320 }
1321 continue;
1322 }
1323
Richard Smith5179eb72016-06-28 19:03:57 +00001324 // Use a different note for an inheriting constructor, because from the
1325 // user's perspective it's not really a function at all.
1326 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1327 if (CD->isInheritingConstructor()) {
1328 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1329 << CD->getParent();
1330 continue;
1331 }
1332 }
1333
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001334 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001335 llvm::raw_svector_ostream Out(Buffer);
1336 describeCall(Frame, Out);
1337 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1338 }
1339}
1340
Richard Smithdebad642019-05-12 09:39:08 +00001341/// Kinds of access we can perform on an object, for diagnostics. Note that
1342/// we consider a member function call to be a kind of access, even though
1343/// it is not formally an access of the object, because it has (largely) the
1344/// same set of semantic restrictions.
Hubert Tong147b7432018-12-12 16:53:43 +00001345enum AccessKinds {
1346 AK_Read,
1347 AK_Assign,
1348 AK_Increment,
Richard Smithdebad642019-05-12 09:39:08 +00001349 AK_Decrement,
1350 AK_MemberCall,
Richard Smith7bd54ab2019-05-15 20:22:21 +00001351 AK_DynamicCast,
Richard Smitha9330302019-05-17 19:19:28 +00001352 AK_TypeId,
Hubert Tong147b7432018-12-12 16:53:43 +00001353};
1354
Richard Smithdebad642019-05-12 09:39:08 +00001355static bool isModification(AccessKinds AK) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00001356 switch (AK) {
1357 case AK_Read:
1358 case AK_MemberCall:
1359 case AK_DynamicCast:
Richard Smitha9330302019-05-17 19:19:28 +00001360 case AK_TypeId:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001361 return false;
1362 case AK_Assign:
1363 case AK_Increment:
1364 case AK_Decrement:
1365 return true;
1366 }
1367 llvm_unreachable("unknown access kind");
1368}
1369
1370/// Is this an access per the C++ definition?
1371static bool isFormalAccess(AccessKinds AK) {
1372 return AK == AK_Read || isModification(AK);
Richard Smithdebad642019-05-12 09:39:08 +00001373}
1374
Richard Smithf6f003a2011-12-16 19:06:07 +00001375namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001376 struct ComplexValue {
1377 private:
1378 bool IsInt;
1379
1380 public:
1381 APSInt IntReal, IntImag;
1382 APFloat FloatReal, FloatImag;
1383
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001384 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001385
1386 void makeComplexFloat() { IsInt = false; }
1387 bool isComplexFloat() const { return !IsInt; }
1388 APFloat &getComplexFloatReal() { return FloatReal; }
1389 APFloat &getComplexFloatImag() { return FloatImag; }
1390
1391 void makeComplexInt() { IsInt = true; }
1392 bool isComplexInt() const { return IsInt; }
1393 APSInt &getComplexIntReal() { return IntReal; }
1394 APSInt &getComplexIntImag() { return IntImag; }
1395
Richard Smith2e312c82012-03-03 22:46:17 +00001396 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001397 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001398 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001399 else
Richard Smith2e312c82012-03-03 22:46:17 +00001400 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001401 }
Richard Smith2e312c82012-03-03 22:46:17 +00001402 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001403 assert(v.isComplexFloat() || v.isComplexInt());
1404 if (v.isComplexFloat()) {
1405 makeComplexFloat();
1406 FloatReal = v.getComplexFloatReal();
1407 FloatImag = v.getComplexFloatImag();
1408 } else {
1409 makeComplexInt();
1410 IntReal = v.getComplexIntReal();
1411 IntImag = v.getComplexIntImag();
1412 }
1413 }
John McCall93d91dc2010-05-07 17:22:02 +00001414 };
John McCall45d55e42010-05-07 21:00:08 +00001415
1416 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001417 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001418 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001419 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001420 bool IsNullPtr : 1;
1421 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001422
Richard Smithce40ad62011-11-12 22:28:03 +00001423 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001424 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001425 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001426 SubobjectDesignator &getLValueDesignator() { return Designator; }
1427 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001428 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001429
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001430 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1431 unsigned getLValueVersion() const { return Base.getVersion(); }
1432
Richard Smith2e312c82012-03-03 22:46:17 +00001433 void moveInto(APValue &V) const {
1434 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001435 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001436 else {
1437 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001438 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001439 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001440 }
John McCall45d55e42010-05-07 21:00:08 +00001441 }
Richard Smith2e312c82012-03-03 22:46:17 +00001442 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001443 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001444 Base = V.getLValueBase();
1445 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001446 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001447 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001448 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001449 }
1450
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001451 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001452#ifndef NDEBUG
1453 // We only allow a few types of invalid bases. Enforce that here.
1454 if (BInvalid) {
1455 const auto *E = B.get<const Expr *>();
1456 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1457 "Unexpected type of invalid base");
1458 }
1459#endif
1460
Richard Smithce40ad62011-11-12 22:28:03 +00001461 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001462 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001463 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001464 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001465 IsNullPtr = false;
1466 }
1467
1468 void setNull(QualType PointerTy, uint64_t TargetVal) {
1469 Base = (Expr *)nullptr;
1470 Offset = CharUnits::fromQuantity(TargetVal);
1471 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001472 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1473 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001474 }
1475
George Burgess IV3a03fab2015-09-04 21:28:13 +00001476 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001477 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001478 }
1479
Hubert Tong147b7432018-12-12 16:53:43 +00001480 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001481 // Check that this LValue is not based on a null pointer. If it is, produce
1482 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001483 template <typename GenDiagType>
1484 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001485 if (Designator.Invalid)
1486 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001487 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001488 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001489 Designator.setInvalid();
1490 return false;
1491 }
1492 return true;
1493 }
1494
Hubert Tong147b7432018-12-12 16:53:43 +00001495 public:
1496 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1497 CheckSubobjectKind CSK) {
1498 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1499 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1500 });
1501 }
1502
1503 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1504 AccessKinds AK) {
1505 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1506 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1507 });
1508 }
1509
Richard Smitha8105bc2012-01-06 16:39:00 +00001510 // Check this LValue refers to an object. If not, set the designator to be
1511 // invalid and emit a diagnostic.
1512 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001513 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001514 Designator.checkSubobject(Info, E, CSK);
1515 }
1516
1517 void addDecl(EvalInfo &Info, const Expr *E,
1518 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001519 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1520 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001521 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001522 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1523 if (!Designator.Entries.empty()) {
1524 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1525 Designator.setInvalid();
1526 return;
1527 }
Richard Smithefdb5032017-11-15 03:03:56 +00001528 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1529 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1530 Designator.FirstEntryIsAnUnsizedArray = true;
1531 Designator.addUnsizedArrayUnchecked(ElemTy);
1532 }
George Burgess IVe3763372016-12-22 02:50:20 +00001533 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001534 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001535 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1536 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001537 }
Richard Smith66c96992012-02-18 22:04:06 +00001538 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001539 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1540 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001541 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001542 void clearIsNullPointer() {
1543 IsNullPtr = false;
1544 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001545 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1546 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001547 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1548 // but we're not required to diagnose it and it's valid in C++.)
1549 if (!Index)
1550 return;
1551
1552 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1553 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1554 // offsets.
1555 uint64_t Offset64 = Offset.getQuantity();
1556 uint64_t ElemSize64 = ElementSize.getQuantity();
1557 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1558 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1559
1560 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001561 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001562 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001563 }
1564 void adjustOffset(CharUnits N) {
1565 Offset += N;
1566 if (N.getQuantity())
1567 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001568 }
John McCall45d55e42010-05-07 21:00:08 +00001569 };
Richard Smith027bf112011-11-17 22:56:20 +00001570
1571 struct MemberPtr {
1572 MemberPtr() {}
1573 explicit MemberPtr(const ValueDecl *Decl) :
1574 DeclAndIsDerivedMember(Decl, false), Path() {}
1575
1576 /// The member or (direct or indirect) field referred to by this member
1577 /// pointer, or 0 if this is a null member pointer.
1578 const ValueDecl *getDecl() const {
1579 return DeclAndIsDerivedMember.getPointer();
1580 }
1581 /// Is this actually a member of some type derived from the relevant class?
1582 bool isDerivedMember() const {
1583 return DeclAndIsDerivedMember.getInt();
1584 }
1585 /// Get the class which the declaration actually lives in.
1586 const CXXRecordDecl *getContainingRecord() const {
1587 return cast<CXXRecordDecl>(
1588 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1589 }
1590
Richard Smith2e312c82012-03-03 22:46:17 +00001591 void moveInto(APValue &V) const {
1592 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001593 }
Richard Smith2e312c82012-03-03 22:46:17 +00001594 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001595 assert(V.isMemberPointer());
1596 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1597 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1598 Path.clear();
1599 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1600 Path.insert(Path.end(), P.begin(), P.end());
1601 }
1602
1603 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1604 /// whether the member is a member of some class derived from the class type
1605 /// of the member pointer.
1606 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1607 /// Path - The path of base/derived classes from the member declaration's
1608 /// class (exclusive) to the class type of the member pointer (inclusive).
1609 SmallVector<const CXXRecordDecl*, 4> Path;
1610
1611 /// Perform a cast towards the class of the Decl (either up or down the
1612 /// hierarchy).
1613 bool castBack(const CXXRecordDecl *Class) {
1614 assert(!Path.empty());
1615 const CXXRecordDecl *Expected;
1616 if (Path.size() >= 2)
1617 Expected = Path[Path.size() - 2];
1618 else
1619 Expected = getContainingRecord();
1620 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1621 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1622 // if B does not contain the original member and is not a base or
1623 // derived class of the class containing the original member, the result
1624 // of the cast is undefined.
1625 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1626 // (D::*). We consider that to be a language defect.
1627 return false;
1628 }
1629 Path.pop_back();
1630 return true;
1631 }
1632 /// Perform a base-to-derived member pointer cast.
1633 bool castToDerived(const CXXRecordDecl *Derived) {
1634 if (!getDecl())
1635 return true;
1636 if (!isDerivedMember()) {
1637 Path.push_back(Derived);
1638 return true;
1639 }
1640 if (!castBack(Derived))
1641 return false;
1642 if (Path.empty())
1643 DeclAndIsDerivedMember.setInt(false);
1644 return true;
1645 }
1646 /// Perform a derived-to-base member pointer cast.
1647 bool castToBase(const CXXRecordDecl *Base) {
1648 if (!getDecl())
1649 return true;
1650 if (Path.empty())
1651 DeclAndIsDerivedMember.setInt(true);
1652 if (isDerivedMember()) {
1653 Path.push_back(Base);
1654 return true;
1655 }
1656 return castBack(Base);
1657 }
1658 };
Richard Smith357362d2011-12-13 06:39:58 +00001659
Richard Smith7bb00672012-02-01 01:42:44 +00001660 /// Compare two member pointers, which are assumed to be of the same type.
1661 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1662 if (!LHS.getDecl() || !RHS.getDecl())
1663 return !LHS.getDecl() && !RHS.getDecl();
1664 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1665 return false;
1666 return LHS.Path == RHS.Path;
1667 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001668}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001669
Richard Smith2e312c82012-03-03 22:46:17 +00001670static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001671static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1672 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001673 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001674static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1675 bool InvalidBaseOK = false);
1676static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1677 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001678static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1679 EvalInfo &Info);
1680static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001681static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001682static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001683 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001684static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001685static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001686static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1687 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001688static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001689
Leonard Chand3f3e162019-01-18 21:04:25 +00001690/// Evaluate an integer or fixed point expression into an APResult.
1691static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1692 EvalInfo &Info);
1693
1694/// Evaluate only a fixed point expression into an APResult.
1695static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1696 EvalInfo &Info);
1697
Chris Lattner05706e882008-07-11 18:11:29 +00001698//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001699// Misc utilities
1700//===----------------------------------------------------------------------===//
1701
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001702/// A helper function to create a temporary and set an LValue.
1703template <class KeyTy>
1704static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1705 LValue &LV, CallStackFrame &Frame) {
1706 LV.set({Key, Frame.Info.CurrentCall->Index,
1707 Frame.Info.CurrentCall->getTempVersion()});
1708 return Frame.createTemporary(Key, IsLifetimeExtended);
1709}
1710
Richard Smithd6cc1982017-01-31 02:23:02 +00001711/// Negate an APSInt in place, converting it to a signed form if necessary, and
1712/// preserving its value (by extending by up to one bit as needed).
1713static void negateAsSigned(APSInt &Int) {
1714 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1715 Int = Int.extend(Int.getBitWidth() + 1);
1716 Int.setIsSigned(true);
1717 }
1718 Int = -Int;
1719}
1720
Richard Smith84401042013-06-03 05:03:02 +00001721/// Produce a string describing the given constexpr call.
1722static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1723 unsigned ArgIndex = 0;
1724 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1725 !isa<CXXConstructorDecl>(Frame->Callee) &&
1726 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1727
1728 if (!IsMemberCall)
1729 Out << *Frame->Callee << '(';
1730
1731 if (Frame->This && IsMemberCall) {
1732 APValue Val;
1733 Frame->This->moveInto(Val);
1734 Val.printPretty(Out, Frame->Info.Ctx,
1735 Frame->This->Designator.MostDerivedType);
1736 // FIXME: Add parens around Val if needed.
1737 Out << "->" << *Frame->Callee << '(';
1738 IsMemberCall = false;
1739 }
1740
1741 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1742 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1743 if (ArgIndex > (unsigned)IsMemberCall)
1744 Out << ", ";
1745
1746 const ParmVarDecl *Param = *I;
1747 const APValue &Arg = Frame->Arguments[ArgIndex];
1748 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1749
1750 if (ArgIndex == 0 && IsMemberCall)
1751 Out << "->" << *Frame->Callee << '(';
1752 }
1753
1754 Out << ')';
1755}
1756
Richard Smithd9f663b2013-04-22 15:31:51 +00001757/// Evaluate an expression to see if it had side-effects, and discard its
1758/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001759/// \return \c true if the caller should keep evaluating.
1760static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001761 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001762 if (!Evaluate(Scratch, Info, E))
1763 // We don't need the value, but we might have skipped a side effect here.
1764 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001765 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001766}
1767
Richard Smithd62306a2011-11-10 06:34:14 +00001768/// Should this call expression be treated as a string literal?
1769static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001770 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001771 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1772 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1773}
1774
Richard Smithce40ad62011-11-12 22:28:03 +00001775static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001776 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1777 // constant expression of pointer type that evaluates to...
1778
1779 // ... a null pointer value, or a prvalue core constant expression of type
1780 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001781 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001782
Richard Smithce40ad62011-11-12 22:28:03 +00001783 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1784 // ... the address of an object with static storage duration,
1785 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1786 return VD->hasGlobalStorage();
1787 // ... the address of a function,
1788 return isa<FunctionDecl>(D);
1789 }
1790
Richard Smithee0ce3022019-05-17 07:06:46 +00001791 if (B.is<TypeInfoLValue>())
1792 return true;
1793
Richard Smithce40ad62011-11-12 22:28:03 +00001794 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001795 switch (E->getStmtClass()) {
1796 default:
1797 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001798 case Expr::CompoundLiteralExprClass: {
1799 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1800 return CLE->isFileScope() && CLE->isLValue();
1801 }
Richard Smithe6c01442013-06-05 00:46:14 +00001802 case Expr::MaterializeTemporaryExprClass:
1803 // A materialized temporary might have been lifetime-extended to static
1804 // storage duration.
1805 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001806 // A string literal has static storage duration.
1807 case Expr::StringLiteralClass:
1808 case Expr::PredefinedExprClass:
1809 case Expr::ObjCStringLiteralClass:
1810 case Expr::ObjCEncodeExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001811 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001812 return true;
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001813 case Expr::ObjCBoxedExprClass:
1814 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
Richard Smithd62306a2011-11-10 06:34:14 +00001815 case Expr::CallExprClass:
1816 return IsStringLiteralCall(cast<CallExpr>(E));
1817 // For GCC compatibility, &&label has static storage duration.
1818 case Expr::AddrLabelExprClass:
1819 return true;
1820 // A Block literal expression may be used as the initialization value for
1821 // Block variables at global or local static scope.
1822 case Expr::BlockExprClass:
1823 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001824 case Expr::ImplicitValueInitExprClass:
1825 // FIXME:
1826 // We can never form an lvalue with an implicit value initialization as its
1827 // base through expression evaluation, so these only appear in one case: the
1828 // implicit variable declaration we invent when checking whether a constexpr
1829 // constructor can produce a constant expression. We must assume that such
1830 // an expression might be a global lvalue.
1831 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001832 }
John McCall95007602010-05-10 23:27:23 +00001833}
1834
Richard Smith06f71b52018-08-04 00:57:17 +00001835static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1836 return LVal.Base.dyn_cast<const ValueDecl*>();
1837}
1838
1839static bool IsLiteralLValue(const LValue &Value) {
1840 if (Value.getLValueCallIndex())
1841 return false;
1842 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1843 return E && !isa<MaterializeTemporaryExpr>(E);
1844}
1845
1846static bool IsWeakLValue(const LValue &Value) {
1847 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1848 return Decl && Decl->isWeak();
1849}
1850
1851static bool isZeroSized(const LValue &Value) {
1852 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1853 if (Decl && isa<VarDecl>(Decl)) {
1854 QualType Ty = Decl->getType();
1855 if (Ty->isArrayType())
1856 return Ty->isIncompleteType() ||
1857 Decl->getASTContext().getTypeSize(Ty) == 0;
1858 }
1859 return false;
1860}
1861
1862static bool HasSameBase(const LValue &A, const LValue &B) {
1863 if (!A.getLValueBase())
1864 return !B.getLValueBase();
1865 if (!B.getLValueBase())
1866 return false;
1867
1868 if (A.getLValueBase().getOpaqueValue() !=
1869 B.getLValueBase().getOpaqueValue()) {
1870 const Decl *ADecl = GetLValueBaseDecl(A);
1871 if (!ADecl)
1872 return false;
1873 const Decl *BDecl = GetLValueBaseDecl(B);
1874 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1875 return false;
1876 }
1877
1878 return IsGlobalLValue(A.getLValueBase()) ||
1879 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1880 A.getLValueVersion() == B.getLValueVersion());
1881}
1882
Richard Smithb228a862012-02-15 02:18:13 +00001883static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1884 assert(Base && "no location for a null lvalue");
1885 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1886 if (VD)
1887 Info.Note(VD->getLocation(), diag::note_declared_at);
Richard Smithee0ce3022019-05-17 07:06:46 +00001888 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1889 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1890 // We have no information to show for a typeid(T) object.
Richard Smithb228a862012-02-15 02:18:13 +00001891}
1892
Richard Smith80815602011-11-07 05:07:52 +00001893/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001894/// value for an address or reference constant expression. Return true if we
1895/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001896static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001897 QualType Type, const LValue &LVal,
1898 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001899 bool IsReferenceType = Type->isReferenceType();
1900
Richard Smith357362d2011-12-13 06:39:58 +00001901 APValue::LValueBase Base = LVal.getLValueBase();
1902 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1903
Richard Smith0dea49e2012-02-18 04:58:18 +00001904 // Check that the object is a global. Note that the fake 'this' object we
1905 // manufacture when checking potential constant expressions is conservatively
1906 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001907 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001908 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001909 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001910 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001911 << IsReferenceType << !Designator.Entries.empty()
1912 << !!VD << VD;
1913 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001914 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001915 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001916 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001917 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001918 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001919 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001920 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001921 LVal.getLValueCallIndex() == 0) &&
1922 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001923
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001924 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1925 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001926 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001927 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001928 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001929
Hans Wennborg82dd8772014-06-25 22:19:48 +00001930 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001931 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001932 return false;
1933 }
1934 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1935 // __declspec(dllimport) must be handled very carefully:
1936 // We must never initialize an expression with the thunk in C++.
1937 // Doing otherwise would allow the same id-expression to yield
1938 // different addresses for the same function in different translation
1939 // units. However, this means that we must dynamically initialize the
1940 // expression with the contents of the import address table at runtime.
1941 //
1942 // The C language has no notion of ODR; furthermore, it has no notion of
1943 // dynamic initialization. This means that we are permitted to
1944 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001945 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1946 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001947 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001948 }
1949 }
1950
Richard Smitha8105bc2012-01-06 16:39:00 +00001951 // Allow address constant expressions to be past-the-end pointers. This is
1952 // an extension: the standard requires them to point to an object.
1953 if (!IsReferenceType)
1954 return true;
1955
1956 // A reference constant expression must refer to an object.
1957 if (!Base) {
1958 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001959 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001960 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001961 }
1962
Richard Smith357362d2011-12-13 06:39:58 +00001963 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001964 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001965 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001966 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001967 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001968 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001969 }
1970
Richard Smith80815602011-11-07 05:07:52 +00001971 return true;
1972}
1973
Reid Klecknercd016d82017-07-07 22:04:29 +00001974/// Member pointers are constant expressions unless they point to a
1975/// non-virtual dllimport member function.
1976static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1977 SourceLocation Loc,
1978 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001979 const APValue &Value,
1980 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00001981 const ValueDecl *Member = Value.getMemberPointerDecl();
1982 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1983 if (!FD)
1984 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001985 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1986 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00001987}
1988
Richard Smithfddd3842011-12-30 21:15:51 +00001989/// Check that this core constant expression is of literal type, and if not,
1990/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001991static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001992 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001993 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001994 return true;
1995
Richard Smith7525ff62013-05-09 07:14:00 +00001996 // C++1y: A constant initializer for an object o [...] may also invoke
1997 // constexpr constructors for o and its subobjects even if those objects
1998 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001999 //
2000 // C++11 missed this detail for aggregates, so classes like this:
2001 // struct foo_t { union { int i; volatile int j; } u; };
2002 // are not (obviously) initializable like so:
2003 // __attribute__((__require_constant_initialization__))
2004 // static const foo_t x = {{0}};
2005 // because "i" is a subobject with non-literal initialization (due to the
2006 // volatile member of the union). See:
2007 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2008 // Therefore, we use the C++1y behavior.
2009 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00002010 return true;
2011
Richard Smithfddd3842011-12-30 21:15:51 +00002012 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002013 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002014 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00002015 << E->getType();
2016 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002017 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00002018 return false;
2019}
2020
Richard Smith0b0a0b62011-10-29 20:57:55 +00002021/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00002022/// constant expression. If not, report an appropriate diagnostic. Does not
2023/// check that the expression is of literal type.
Reid Kleckner1a840d22018-05-10 18:57:35 +00002024static bool
2025CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2026 const APValue &Value,
2027 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002028 if (!Value.hasValue()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002029 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00002030 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00002031 return false;
2032 }
2033
Richard Smith77be48a2014-07-31 06:31:19 +00002034 // We allow _Atomic(T) to be initialized from anything that T can be
2035 // initialized from.
2036 if (const AtomicType *AT = Type->getAs<AtomicType>())
2037 Type = AT->getValueType();
2038
Richard Smithb228a862012-02-15 02:18:13 +00002039 // Core issue 1454: For a literal constant expression of array or class type,
2040 // each subobject of its value shall have been initialized by a constant
2041 // expression.
2042 if (Value.isArray()) {
2043 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2044 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2045 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
Reid Kleckner1a840d22018-05-10 18:57:35 +00002046 Value.getArrayInitializedElt(I), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00002047 return false;
2048 }
2049 if (!Value.hasArrayFiller())
2050 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002051 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
2052 Usage);
Richard Smith80815602011-11-07 05:07:52 +00002053 }
Richard Smithb228a862012-02-15 02:18:13 +00002054 if (Value.isUnion() && Value.getUnionField()) {
2055 return CheckConstantExpression(Info, DiagLoc,
2056 Value.getUnionField()->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00002057 Value.getUnionValue(), Usage);
Richard Smithb228a862012-02-15 02:18:13 +00002058 }
2059 if (Value.isStruct()) {
2060 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2061 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2062 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002063 for (const CXXBaseSpecifier &BS : CD->bases()) {
2064 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
2065 Value.getStructBase(BaseIndex), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00002066 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002067 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00002068 }
2069 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002070 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00002071 if (I->isUnnamedBitfield())
2072 continue;
2073
David Blaikie2d7c57e2012-04-30 02:36:29 +00002074 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00002075 Value.getStructField(I->getFieldIndex()),
2076 Usage))
Richard Smithb228a862012-02-15 02:18:13 +00002077 return false;
2078 }
2079 }
2080
2081 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00002082 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00002083 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00002084 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00002085 }
2086
Reid Klecknercd016d82017-07-07 22:04:29 +00002087 if (Value.isMemberPointer())
Reid Kleckner1a840d22018-05-10 18:57:35 +00002088 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00002089
Richard Smithb228a862012-02-15 02:18:13 +00002090 // Everything else is fine.
2091 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002092}
2093
Richard Smith2e312c82012-03-03 22:46:17 +00002094static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00002095 // A null base expression indicates a null pointer. These are always
2096 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00002097 if (!Value.getLValueBase()) {
2098 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002099 return true;
2100 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002101
Richard Smith027bf112011-11-17 22:56:20 +00002102 // We have a non-null base. These are generally known to be true, but if it's
2103 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002104 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002105 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002106 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002107}
2108
Richard Smith2e312c82012-03-03 22:46:17 +00002109static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002110 switch (Val.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002111 case APValue::None:
2112 case APValue::Indeterminate:
Richard Smith11562c52011-10-28 17:51:58 +00002113 return false;
2114 case APValue::Int:
2115 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002116 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00002117 case APValue::FixedPoint:
2118 Result = Val.getFixedPoint().getBoolValue();
2119 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002120 case APValue::Float:
2121 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002122 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002123 case APValue::ComplexInt:
2124 Result = Val.getComplexIntReal().getBoolValue() ||
2125 Val.getComplexIntImag().getBoolValue();
2126 return true;
2127 case APValue::ComplexFloat:
2128 Result = !Val.getComplexFloatReal().isZero() ||
2129 !Val.getComplexFloatImag().isZero();
2130 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002131 case APValue::LValue:
2132 return EvalPointerValueAsBool(Val, Result);
2133 case APValue::MemberPointer:
2134 Result = Val.getMemberPointerDecl();
2135 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002136 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002137 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002138 case APValue::Struct:
2139 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002140 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002141 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002142 }
2143
Richard Smith11562c52011-10-28 17:51:58 +00002144 llvm_unreachable("unknown APValue kind");
2145}
2146
2147static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2148 EvalInfo &Info) {
2149 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002150 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002151 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002152 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002153 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002154}
2155
Richard Smith357362d2011-12-13 06:39:58 +00002156template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002157static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002158 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002159 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002160 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002161 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002162}
2163
2164static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2165 QualType SrcType, const APFloat &Value,
2166 QualType DestType, APSInt &Result) {
2167 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002168 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002169 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002170
Richard Smith357362d2011-12-13 06:39:58 +00002171 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002172 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002173 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2174 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002175 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002176 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002177}
2178
Richard Smith357362d2011-12-13 06:39:58 +00002179static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2180 QualType SrcType, QualType DestType,
2181 APFloat &Result) {
2182 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002183 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002184 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2185 APFloat::rmNearestTiesToEven, &ignored)
2186 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002187 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002188 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002189}
2190
Richard Smith911e1422012-01-30 22:27:01 +00002191static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2192 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002193 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002194 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002195 // Figure out if this is a truncate, extend or noop cast.
2196 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002197 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002198 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002199 if (DestType->isBooleanType())
2200 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002201 return Result;
2202}
2203
Richard Smith357362d2011-12-13 06:39:58 +00002204static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2205 QualType SrcType, const APSInt &Value,
2206 QualType DestType, APFloat &Result) {
2207 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2208 if (Result.convertFromAPInt(Value, Value.isSigned(),
2209 APFloat::rmNearestTiesToEven)
2210 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002211 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002212 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002213}
2214
Richard Smith49ca8aa2013-08-06 07:09:20 +00002215static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2216 APValue &Value, const FieldDecl *FD) {
2217 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2218
2219 if (!Value.isInt()) {
2220 // Trying to store a pointer-cast-to-integer into a bitfield.
2221 // FIXME: In this case, we should provide the diagnostic for casting
2222 // a pointer to an integer.
2223 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002224 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002225 return false;
2226 }
2227
2228 APSInt &Int = Value.getInt();
2229 unsigned OldBitWidth = Int.getBitWidth();
2230 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2231 if (NewBitWidth < OldBitWidth)
2232 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2233 return true;
2234}
2235
Eli Friedman803acb32011-12-22 03:51:45 +00002236static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2237 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002238 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002239 if (!Evaluate(SVal, Info, E))
2240 return false;
2241 if (SVal.isInt()) {
2242 Res = SVal.getInt();
2243 return true;
2244 }
2245 if (SVal.isFloat()) {
2246 Res = SVal.getFloat().bitcastToAPInt();
2247 return true;
2248 }
2249 if (SVal.isVector()) {
2250 QualType VecTy = E->getType();
2251 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2252 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2253 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2254 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2255 Res = llvm::APInt::getNullValue(VecSize);
2256 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2257 APValue &Elt = SVal.getVectorElt(i);
2258 llvm::APInt EltAsInt;
2259 if (Elt.isInt()) {
2260 EltAsInt = Elt.getInt();
2261 } else if (Elt.isFloat()) {
2262 EltAsInt = Elt.getFloat().bitcastToAPInt();
2263 } else {
2264 // Don't try to handle vectors of anything other than int or float
2265 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002266 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002267 return false;
2268 }
2269 unsigned BaseEltSize = EltAsInt.getBitWidth();
2270 if (BigEndian)
2271 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2272 else
2273 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2274 }
2275 return true;
2276 }
2277 // Give up if the input isn't an int, float, or vector. For example, we
2278 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002279 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002280 return false;
2281}
2282
Richard Smith43e77732013-05-07 04:50:00 +00002283/// Perform the given integer operation, which is known to need at most BitWidth
2284/// bits, and check for overflow in the original type (if that type was not an
2285/// unsigned type).
2286template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002287static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2288 const APSInt &LHS, const APSInt &RHS,
2289 unsigned BitWidth, Operation Op,
2290 APSInt &Result) {
2291 if (LHS.isUnsigned()) {
2292 Result = Op(LHS, RHS);
2293 return true;
2294 }
Richard Smith43e77732013-05-07 04:50:00 +00002295
2296 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002297 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002298 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002299 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002300 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002301 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002302 << Result.toString(10) << E->getType();
2303 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002304 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002305 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002306 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002307}
2308
2309/// Perform the given binary integer operation.
2310static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2311 BinaryOperatorKind Opcode, APSInt RHS,
2312 APSInt &Result) {
2313 switch (Opcode) {
2314 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002315 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002316 return false;
2317 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002318 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2319 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002320 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002321 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2322 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002323 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002324 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2325 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002326 case BO_And: Result = LHS & RHS; return true;
2327 case BO_Xor: Result = LHS ^ RHS; return true;
2328 case BO_Or: Result = LHS | RHS; return true;
2329 case BO_Div:
2330 case BO_Rem:
2331 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002332 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002333 return false;
2334 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002335 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2336 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2337 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002338 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2339 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002340 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2341 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002342 return true;
2343 case BO_Shl: {
2344 if (Info.getLangOpts().OpenCL)
2345 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2346 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2347 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2348 RHS.isUnsigned());
2349 else if (RHS.isSigned() && RHS.isNegative()) {
2350 // During constant-folding, a negative shift is an opposite shift. Such
2351 // a shift is not a constant expression.
2352 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2353 RHS = -RHS;
2354 goto shift_right;
2355 }
2356 shift_left:
2357 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2358 // the shifted type.
2359 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2360 if (SA != RHS) {
2361 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2362 << RHS << E->getType() << LHS.getBitWidth();
2363 } else if (LHS.isSigned()) {
2364 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2365 // operand, and must not overflow the corresponding unsigned type.
2366 if (LHS.isNegative())
2367 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2368 else if (LHS.countLeadingZeros() < SA)
2369 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2370 }
2371 Result = LHS << SA;
2372 return true;
2373 }
2374 case BO_Shr: {
2375 if (Info.getLangOpts().OpenCL)
2376 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2377 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2378 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2379 RHS.isUnsigned());
2380 else if (RHS.isSigned() && RHS.isNegative()) {
2381 // During constant-folding, a negative shift is an opposite shift. Such a
2382 // shift is not a constant expression.
2383 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2384 RHS = -RHS;
2385 goto shift_left;
2386 }
2387 shift_right:
2388 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2389 // shifted type.
2390 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2391 if (SA != RHS)
2392 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2393 << RHS << E->getType() << LHS.getBitWidth();
2394 Result = LHS >> SA;
2395 return true;
2396 }
2397
2398 case BO_LT: Result = LHS < RHS; return true;
2399 case BO_GT: Result = LHS > RHS; return true;
2400 case BO_LE: Result = LHS <= RHS; return true;
2401 case BO_GE: Result = LHS >= RHS; return true;
2402 case BO_EQ: Result = LHS == RHS; return true;
2403 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002404 case BO_Cmp:
2405 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002406 }
2407}
2408
Richard Smith861b5b52013-05-07 23:34:45 +00002409/// Perform the given binary floating-point operation, in-place, on LHS.
2410static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2411 APFloat &LHS, BinaryOperatorKind Opcode,
2412 const APFloat &RHS) {
2413 switch (Opcode) {
2414 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002415 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002416 return false;
2417 case BO_Mul:
2418 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2419 break;
2420 case BO_Add:
2421 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2422 break;
2423 case BO_Sub:
2424 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2425 break;
2426 case BO_Div:
2427 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2428 break;
2429 }
2430
Richard Smith0c6124b2015-12-03 01:36:22 +00002431 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002432 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002433 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002434 }
Richard Smith861b5b52013-05-07 23:34:45 +00002435 return true;
2436}
2437
Richard Smitha8105bc2012-01-06 16:39:00 +00002438/// Cast an lvalue referring to a base subobject to a derived class, by
2439/// truncating the lvalue's path to the given length.
2440static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2441 const RecordDecl *TruncatedType,
2442 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002443 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002444
2445 // Check we actually point to a derived class object.
2446 if (TruncatedElements == D.Entries.size())
2447 return true;
2448 assert(TruncatedElements >= D.MostDerivedPathLength &&
2449 "not casting to a derived class");
2450 if (!Result.checkSubobject(Info, E, CSK_Derived))
2451 return false;
2452
2453 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002454 const RecordDecl *RD = TruncatedType;
2455 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002456 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002457 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2458 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002459 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002460 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002461 else
Richard Smithd62306a2011-11-10 06:34:14 +00002462 Result.Offset -= Layout.getBaseClassOffset(Base);
2463 RD = Base;
2464 }
Richard Smith027bf112011-11-17 22:56:20 +00002465 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002466 return true;
2467}
2468
John McCalld7bca762012-05-01 00:38:49 +00002469static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002470 const CXXRecordDecl *Derived,
2471 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002472 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002473 if (!RL) {
2474 if (Derived->isInvalidDecl()) return false;
2475 RL = &Info.Ctx.getASTRecordLayout(Derived);
2476 }
2477
Richard Smithd62306a2011-11-10 06:34:14 +00002478 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002479 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002480 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002481}
2482
Richard Smitha8105bc2012-01-06 16:39:00 +00002483static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002484 const CXXRecordDecl *DerivedDecl,
2485 const CXXBaseSpecifier *Base) {
2486 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2487
John McCalld7bca762012-05-01 00:38:49 +00002488 if (!Base->isVirtual())
2489 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002490
Richard Smitha8105bc2012-01-06 16:39:00 +00002491 SubobjectDesignator &D = Obj.Designator;
2492 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002493 return false;
2494
Richard Smitha8105bc2012-01-06 16:39:00 +00002495 // Extract most-derived object and corresponding type.
2496 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2497 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2498 return false;
2499
2500 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002501 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002502 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2503 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002504 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002505 return true;
2506}
2507
Richard Smith84401042013-06-03 05:03:02 +00002508static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2509 QualType Type, LValue &Result) {
2510 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2511 PathE = E->path_end();
2512 PathI != PathE; ++PathI) {
2513 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2514 *PathI))
2515 return false;
2516 Type = (*PathI)->getType();
2517 }
2518 return true;
2519}
2520
Richard Smith921f1322019-05-13 23:35:21 +00002521/// Cast an lvalue referring to a derived class to a known base subobject.
2522static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2523 const CXXRecordDecl *DerivedRD,
2524 const CXXRecordDecl *BaseRD) {
2525 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2526 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2527 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2528 llvm_unreachable("Class must be derived from the passed in base class!");
2529
2530 for (CXXBasePathElement &Elem : Paths.front())
2531 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2532 return false;
2533 return true;
2534}
2535
Richard Smithd62306a2011-11-10 06:34:14 +00002536/// Update LVal to refer to the given field, which must be a member of the type
2537/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002538static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002539 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002540 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002541 if (!RL) {
2542 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002543 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002544 }
Richard Smithd62306a2011-11-10 06:34:14 +00002545
2546 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002547 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002548 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002549 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002550}
2551
Richard Smith1b78b3d2012-01-25 22:15:11 +00002552/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002553static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002554 LValue &LVal,
2555 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002556 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002557 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002558 return false;
2559 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002560}
2561
Richard Smithd62306a2011-11-10 06:34:14 +00002562/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002563static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2564 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002565 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2566 // extension.
2567 if (Type->isVoidType() || Type->isFunctionType()) {
2568 Size = CharUnits::One();
2569 return true;
2570 }
2571
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002572 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002573 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002574 return false;
2575 }
2576
Richard Smithd62306a2011-11-10 06:34:14 +00002577 if (!Type->isConstantSizeType()) {
2578 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002579 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002580 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002581 return false;
2582 }
2583
2584 Size = Info.Ctx.getTypeSizeInChars(Type);
2585 return true;
2586}
2587
2588/// Update a pointer value to model pointer arithmetic.
2589/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002590/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002591/// \param LVal - The pointer value to be updated.
2592/// \param EltTy - The pointee type represented by LVal.
2593/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002594static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2595 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002596 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002597 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002598 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002599 return false;
2600
Yaxun Liu402804b2016-12-15 08:09:08 +00002601 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002602 return true;
2603}
2604
Richard Smithd6cc1982017-01-31 02:23:02 +00002605static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2606 LValue &LVal, QualType EltTy,
2607 int64_t Adjustment) {
2608 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2609 APSInt::get(Adjustment));
2610}
2611
Richard Smith66c96992012-02-18 22:04:06 +00002612/// Update an lvalue to refer to a component of a complex number.
2613/// \param Info - Information about the ongoing evaluation.
2614/// \param LVal - The lvalue to be updated.
2615/// \param EltTy - The complex number's component type.
2616/// \param Imag - False for the real component, true for the imaginary.
2617static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2618 LValue &LVal, QualType EltTy,
2619 bool Imag) {
2620 if (Imag) {
2621 CharUnits SizeOfComponent;
2622 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2623 return false;
2624 LVal.Offset += SizeOfComponent;
2625 }
2626 LVal.addComplex(Info, E, EltTy, Imag);
2627 return true;
2628}
2629
Faisal Vali051e3a22017-02-16 04:12:21 +00002630static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2631 QualType Type, const LValue &LVal,
2632 APValue &RVal);
2633
Richard Smith27908702011-10-24 17:54:18 +00002634/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002635///
2636/// \param Info Information about the ongoing evaluation.
2637/// \param E An expression to be used when printing diagnostics.
2638/// \param VD The variable whose initializer should be obtained.
2639/// \param Frame The frame in which the variable was created. Must be null
2640/// if this variable is not local to the evaluation.
2641/// \param Result Filled in with a pointer to the value of the variable.
2642static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2643 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002644 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002645
Richard Smith254a73d2011-10-28 22:34:42 +00002646 // If this is a parameter to an active constexpr function call, perform
2647 // argument substitution.
2648 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002649 // Assume arguments of a potential constant expression are unknown
2650 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002651 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002652 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002653 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002654 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002655 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002656 }
Richard Smith3229b742013-05-05 21:17:10 +00002657 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002658 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002659 }
Richard Smith27908702011-10-24 17:54:18 +00002660
Richard Smithd9f663b2013-04-22 15:31:51 +00002661 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002662 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002663 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2664 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002665 if (!Result) {
2666 // Assume variables referenced within a lambda's call operator that were
2667 // not declared within the call operator are captures and during checking
2668 // of a potential constant expression, assume they are unknown constant
2669 // expressions.
2670 assert(isLambdaCallOperator(Frame->Callee) &&
2671 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2672 "missing value for local variable");
2673 if (Info.checkingPotentialConstantExpression())
2674 return false;
2675 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002676 Info.FFDiag(E->getBeginLoc(),
2677 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002678 << "captures not currently allowed";
2679 return false;
2680 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002681 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002682 }
2683
Richard Smithd0b4dd62011-12-19 06:19:21 +00002684 // Dig out the initializer, and use the declaration which it's attached to.
2685 const Expr *Init = VD->getAnyInitializer(VD);
2686 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002687 // If we're checking a potential constant expression, the variable could be
2688 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002689 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002690 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002691 return false;
2692 }
2693
Richard Smithd62306a2011-11-10 06:34:14 +00002694 // If we're currently evaluating the initializer of this declaration, use that
2695 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002696 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002697 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002698 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002699 }
2700
Richard Smithcecf1842011-11-01 21:06:14 +00002701 // Never evaluate the initializer of a weak variable. We can't be sure that
2702 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002703 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002704 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002705 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002706 }
Richard Smithcecf1842011-11-01 21:06:14 +00002707
Richard Smithd0b4dd62011-12-19 06:19:21 +00002708 // Check that we can fold the initializer. In C++, we will have already done
2709 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002710 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002711 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002712 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002713 Notes.size() + 1) << VD;
2714 Info.Note(VD->getLocation(), diag::note_declared_at);
2715 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002716 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002717 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002718 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002719 Notes.size() + 1) << VD;
2720 Info.Note(VD->getLocation(), diag::note_declared_at);
2721 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002722 }
Richard Smith27908702011-10-24 17:54:18 +00002723
Richard Smith3229b742013-05-05 21:17:10 +00002724 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002725 return true;
Richard Smith27908702011-10-24 17:54:18 +00002726}
2727
Richard Smith11562c52011-10-28 17:51:58 +00002728static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002729 Qualifiers Quals = T.getQualifiers();
2730 return Quals.hasConst() && !Quals.hasVolatile();
2731}
2732
Richard Smithe97cbd72011-11-11 04:05:33 +00002733/// Get the base index of the given base class within an APValue representing
2734/// the given derived class.
2735static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2736 const CXXRecordDecl *Base) {
2737 Base = Base->getCanonicalDecl();
2738 unsigned Index = 0;
2739 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2740 E = Derived->bases_end(); I != E; ++I, ++Index) {
2741 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2742 return Index;
2743 }
2744
2745 llvm_unreachable("base class missing from derived class's bases list");
2746}
2747
Richard Smith3da88fa2013-04-26 14:36:30 +00002748/// Extract the value of a character from a string literal.
2749static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2750 uint64_t Index) {
Eric Fiselier708afb52019-05-16 21:04:15 +00002751 assert(!isa<SourceLocExpr>(Lit) &&
2752 "SourceLocExpr should have already been converted to a StringLiteral");
2753
Akira Hatanakabc332642017-01-31 02:31:39 +00002754 // FIXME: Support MakeStringConstant
2755 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2756 std::string Str;
2757 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2758 assert(Index <= Str.size() && "Index too large");
2759 return APSInt::getUnsigned(Str.c_str()[Index]);
2760 }
2761
Alexey Bataevec474782014-10-09 08:45:04 +00002762 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2763 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002764 const StringLiteral *S = cast<StringLiteral>(Lit);
2765 const ConstantArrayType *CAT =
2766 Info.Ctx.getAsConstantArrayType(S->getType());
2767 assert(CAT && "string literal isn't an array");
2768 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002769 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002770
2771 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002772 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002773 if (Index < S->getLength())
2774 Value = S->getCodeUnit(Index);
2775 return Value;
2776}
2777
Richard Smith3da88fa2013-04-26 14:36:30 +00002778// Expand a string literal into an array of characters.
Eli Friedman3bf72d72019-02-08 21:18:46 +00002779//
2780// FIXME: This is inefficient; we should probably introduce something similar
2781// to the LLVM ConstantDataArray to make this cheaper.
2782static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
Richard Smith3da88fa2013-04-26 14:36:30 +00002783 APValue &Result) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002784 const ConstantArrayType *CAT =
2785 Info.Ctx.getAsConstantArrayType(S->getType());
2786 assert(CAT && "string literal isn't an array");
2787 QualType CharType = CAT->getElementType();
2788 assert(CharType->isIntegerType() && "unexpected character type");
2789
2790 unsigned Elts = CAT->getSize().getZExtValue();
2791 Result = APValue(APValue::UninitArray(),
2792 std::min(S->getLength(), Elts), Elts);
2793 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2794 CharType->isUnsignedIntegerType());
2795 if (Result.hasArrayFiller())
2796 Result.getArrayFiller() = APValue(Value);
2797 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2798 Value = S->getCodeUnit(I);
2799 Result.getArrayInitializedElt(I) = APValue(Value);
2800 }
2801}
2802
2803// Expand an array so that it has more than Index filled elements.
2804static void expandArray(APValue &Array, unsigned Index) {
2805 unsigned Size = Array.getArraySize();
2806 assert(Index < Size);
2807
2808 // Always at least double the number of elements for which we store a value.
2809 unsigned OldElts = Array.getArrayInitializedElts();
2810 unsigned NewElts = std::max(Index+1, OldElts * 2);
2811 NewElts = std::min(Size, std::max(NewElts, 8u));
2812
2813 // Copy the data across.
2814 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2815 for (unsigned I = 0; I != OldElts; ++I)
2816 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2817 for (unsigned I = OldElts; I != NewElts; ++I)
2818 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2819 if (NewValue.hasArrayFiller())
2820 NewValue.getArrayFiller() = Array.getArrayFiller();
2821 Array.swap(NewValue);
2822}
2823
Richard Smithb01fe402014-09-16 01:24:02 +00002824/// Determine whether a type would actually be read by an lvalue-to-rvalue
2825/// conversion. If it's of class type, we may assume that the copy operation
2826/// is trivial. Note that this is never true for a union type with fields
2827/// (because the copy always "reads" the active member) and always true for
2828/// a non-class type.
2829static bool isReadByLvalueToRvalueConversion(QualType T) {
2830 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2831 if (!RD || (RD->isUnion() && !RD->field_empty()))
2832 return true;
2833 if (RD->isEmpty())
2834 return false;
2835
2836 for (auto *Field : RD->fields())
2837 if (isReadByLvalueToRvalueConversion(Field->getType()))
2838 return true;
2839
2840 for (auto &BaseSpec : RD->bases())
2841 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2842 return true;
2843
2844 return false;
2845}
2846
2847/// Diagnose an attempt to read from any unreadable field within the specified
2848/// type, which might be a class type.
2849static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2850 QualType T) {
2851 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2852 if (!RD)
2853 return false;
2854
2855 if (!RD->hasMutableFields())
2856 return false;
2857
2858 for (auto *Field : RD->fields()) {
2859 // If we're actually going to read this field in some way, then it can't
2860 // be mutable. If we're in a union, then assigning to a mutable field
2861 // (even an empty one) can change the active member, so that's not OK.
2862 // FIXME: Add core issue number for the union case.
2863 if (Field->isMutable() &&
2864 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002865 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002866 Info.Note(Field->getLocation(), diag::note_declared_at);
2867 return true;
2868 }
2869
2870 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2871 return true;
2872 }
2873
2874 for (auto &BaseSpec : RD->bases())
2875 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2876 return true;
2877
2878 // All mutable fields were empty, and thus not actually read.
2879 return false;
2880}
2881
Richard Smithdebad642019-05-12 09:39:08 +00002882static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2883 APValue::LValueBase Base) {
2884 // A temporary we created.
2885 if (Base.getCallIndex())
2886 return true;
2887
2888 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2889 if (!Evaluating)
2890 return false;
2891
2892 // The variable whose initializer we're evaluating.
2893 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2894 if (declaresSameEntity(Evaluating, BaseD))
2895 return true;
2896
2897 // A temporary lifetime-extended by the variable whose initializer we're
2898 // evaluating.
2899 if (auto *BaseE = Base.dyn_cast<const Expr *>())
2900 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2901 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2902 return true;
2903
2904 return false;
2905}
2906
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002907namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002908/// A handle to a complete object (an object that is not a subobject of
2909/// another object).
2910struct CompleteObject {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002911 /// The identity of the object.
2912 APValue::LValueBase Base;
Richard Smith3229b742013-05-05 21:17:10 +00002913 /// The value of the complete object.
2914 APValue *Value;
2915 /// The type of the complete object.
2916 QualType Type;
2917
Craig Topper36250ad2014-05-12 05:36:57 +00002918 CompleteObject() : Value(nullptr) {}
Richard Smithdebad642019-05-12 09:39:08 +00002919 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2920 : Base(Base), Value(Value), Type(Type) {}
2921
2922 bool mayReadMutableMembers(EvalInfo &Info) const {
2923 // In C++14 onwards, it is permitted to read a mutable member whose
2924 // lifetime began within the evaluation.
2925 // FIXME: Should we also allow this in C++11?
2926 if (!Info.getLangOpts().CPlusPlus14)
2927 return false;
2928 return lifetimeStartedInEvaluation(Info, Base);
Richard Smith3229b742013-05-05 21:17:10 +00002929 }
2930
Richard Smithdebad642019-05-12 09:39:08 +00002931 explicit operator bool() const { return !Type.isNull(); }
Richard Smith3229b742013-05-05 21:17:10 +00002932};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002933} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002934
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002935static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2936 bool IsMutable = false) {
2937 // C++ [basic.type.qualifier]p1:
2938 // - A const object is an object of type const T or a non-mutable subobject
2939 // of a const object.
2940 if (ObjType.isConstQualified() && !IsMutable)
2941 SubobjType.addConst();
2942 // - A volatile object is an object of type const T or a subobject of a
2943 // volatile object.
2944 if (ObjType.isVolatileQualified())
2945 SubobjType.addVolatile();
2946 return SubobjType;
2947}
2948
Richard Smith3da88fa2013-04-26 14:36:30 +00002949/// Find the designated sub-object of an rvalue.
2950template<typename SubobjectHandler>
2951typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002952findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002953 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002954 if (Sub.Invalid)
2955 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002956 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002957 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002958 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002959 Info.FFDiag(E, Sub.isOnePastTheEnd()
2960 ? diag::note_constexpr_access_past_end
2961 : diag::note_constexpr_access_unsized_array)
2962 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002963 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002964 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002965 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002966 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002967
Richard Smith3229b742013-05-05 21:17:10 +00002968 APValue *O = Obj.Value;
2969 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002970 const FieldDecl *LastField = nullptr;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002971 const FieldDecl *VolatileField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002972
Richard Smithd62306a2011-11-10 06:34:14 +00002973 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002974 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002975 if (!O->hasValue()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002976 if (!Info.checkingPotentialConstantExpression())
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002977 Info.FFDiag(E, diag::note_constexpr_access_uninit)
Richard Smithe637cbe2019-05-21 23:15:18 +00002978 << handler.AccessKind << O->isIndeterminate();
Richard Smith08d6a2c2013-07-24 07:11:57 +00002979 return handler.failed();
2980 }
2981
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002982 // C++ [class.ctor]p5:
2983 // const and volatile semantics are not applied on an object under
2984 // construction.
2985 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
2986 ObjType->isRecordType() &&
2987 Info.isEvaluatingConstructor(
2988 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
2989 Sub.Entries.begin() + I)) !=
2990 ConstructionPhase::None) {
2991 ObjType = Info.Ctx.getCanonicalType(ObjType);
2992 ObjType.removeLocalConst();
2993 ObjType.removeLocalVolatile();
2994 }
2995
2996 // If this is our last pass, check that the final object type is OK.
2997 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
2998 // Accesses to volatile objects are prohibited.
Richard Smith7bd54ab2019-05-15 20:22:21 +00002999 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003000 if (Info.getLangOpts().CPlusPlus) {
3001 int DiagKind;
3002 SourceLocation Loc;
3003 const NamedDecl *Decl = nullptr;
3004 if (VolatileField) {
3005 DiagKind = 2;
3006 Loc = VolatileField->getLocation();
3007 Decl = VolatileField;
3008 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3009 DiagKind = 1;
3010 Loc = VD->getLocation();
3011 Decl = VD;
3012 } else {
3013 DiagKind = 0;
3014 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3015 Loc = E->getExprLoc();
3016 }
3017 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3018 << handler.AccessKind << DiagKind << Decl;
3019 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3020 } else {
3021 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3022 }
3023 return handler.failed();
3024 }
3025
Richard Smithb01fe402014-09-16 01:24:02 +00003026 // If we are reading an object of class type, there may still be more
3027 // things we need to check: if there are any mutable subobjects, we
3028 // cannot perform this read. (This only happens when performing a trivial
3029 // copy or assignment.)
3030 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smithdebad642019-05-12 09:39:08 +00003031 !Obj.mayReadMutableMembers(Info) &&
3032 diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00003033 return handler.failed();
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003034 }
Richard Smithb01fe402014-09-16 01:24:02 +00003035
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003036 if (I == N) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00003037 if (!handler.found(*O, ObjType))
3038 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003039
Richard Smith49ca8aa2013-08-06 07:09:20 +00003040 // If we modified a bit-field, truncate it to the right width.
Richard Smithdebad642019-05-12 09:39:08 +00003041 if (isModification(handler.AccessKind) &&
Richard Smith49ca8aa2013-08-06 07:09:20 +00003042 LastField && LastField->isBitField() &&
3043 !truncateBitfieldValue(Info, E, *O, LastField))
3044 return false;
3045
3046 return true;
3047 }
3048
Craig Topper36250ad2014-05-12 05:36:57 +00003049 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00003050 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00003051 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00003052 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003053 assert(CAT && "vla in literal type?");
Richard Smith5b5e27a2019-05-10 20:05:31 +00003054 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003055 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00003056 // Note, it should not be possible to form a pointer with a valid
3057 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00003058 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003059 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003060 << handler.AccessKind;
3061 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003062 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003063 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003064 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003065
3066 ObjType = CAT->getElementType();
3067
Richard Smith3da88fa2013-04-26 14:36:30 +00003068 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00003069 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00003070 else if (handler.AccessKind != AK_Read) {
3071 expandArray(*O, Index);
3072 O = &O->getArrayInitializedElt(Index);
3073 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00003074 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00003075 } else if (ObjType->isAnyComplexType()) {
3076 // Next subobject is a complex number.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003077 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smith66c96992012-02-18 22:04:06 +00003078 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003079 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003080 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003081 << handler.AccessKind;
3082 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003083 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003084 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00003085 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003086
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003087 ObjType = getSubobjectType(
3088 ObjType, ObjType->castAs<ComplexType>()->getElementType());
Richard Smith3da88fa2013-04-26 14:36:30 +00003089
Richard Smith66c96992012-02-18 22:04:06 +00003090 assert(I == N - 1 && "extracting subobject of scalar?");
3091 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003092 return handler.found(Index ? O->getComplexIntImag()
3093 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003094 } else {
3095 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00003096 return handler.found(Index ? O->getComplexFloatImag()
3097 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003098 }
Richard Smithd62306a2011-11-10 06:34:14 +00003099 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00003100 if (Field->isMutable() && handler.AccessKind == AK_Read &&
Richard Smithdebad642019-05-12 09:39:08 +00003101 !Obj.mayReadMutableMembers(Info)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003102 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00003103 << Field;
3104 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00003105 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00003106 }
3107
Richard Smithd62306a2011-11-10 06:34:14 +00003108 // Next subobject is a class, struct or union field.
3109 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3110 if (RD->isUnion()) {
3111 const FieldDecl *UnionField = O->getUnionField();
3112 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00003113 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003114 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00003115 << handler.AccessKind << Field << !UnionField << UnionField;
3116 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003117 }
Richard Smithd62306a2011-11-10 06:34:14 +00003118 O = &O->getUnionValue();
3119 } else
3120 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00003121
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003122 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
Richard Smith49ca8aa2013-08-06 07:09:20 +00003123 LastField = Field;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003124 if (Field->getType().isVolatileQualified())
3125 VolatileField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00003126 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00003127 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00003128 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3129 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3130 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00003131
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003132 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
Richard Smithf3e9e432011-11-07 09:22:26 +00003133 }
3134 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003135}
3136
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003137namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003138struct ExtractSubobjectHandler {
3139 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00003140 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00003141
3142 static const AccessKinds AccessKind = AK_Read;
3143
3144 typedef bool result_type;
3145 bool failed() { return false; }
3146 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003147 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00003148 return true;
3149 }
3150 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003151 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003152 return true;
3153 }
3154 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003155 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003156 return true;
3157 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003158};
Richard Smith3229b742013-05-05 21:17:10 +00003159} // end anonymous namespace
3160
Richard Smith3da88fa2013-04-26 14:36:30 +00003161const AccessKinds ExtractSubobjectHandler::AccessKind;
3162
3163/// Extract the designated sub-object of an rvalue.
3164static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003165 const CompleteObject &Obj,
3166 const SubobjectDesignator &Sub,
3167 APValue &Result) {
3168 ExtractSubobjectHandler Handler = { Info, Result };
3169 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003170}
3171
Richard Smith3229b742013-05-05 21:17:10 +00003172namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003173struct ModifySubobjectHandler {
3174 EvalInfo &Info;
3175 APValue &NewVal;
3176 const Expr *E;
3177
3178 typedef bool result_type;
3179 static const AccessKinds AccessKind = AK_Assign;
3180
3181 bool checkConst(QualType QT) {
3182 // Assigning to a const object has undefined behavior.
3183 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003184 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003185 return false;
3186 }
3187 return true;
3188 }
3189
3190 bool failed() { return false; }
3191 bool found(APValue &Subobj, QualType SubobjType) {
3192 if (!checkConst(SubobjType))
3193 return false;
3194 // We've been given ownership of NewVal, so just swap it in.
3195 Subobj.swap(NewVal);
3196 return true;
3197 }
3198 bool found(APSInt &Value, QualType SubobjType) {
3199 if (!checkConst(SubobjType))
3200 return false;
3201 if (!NewVal.isInt()) {
3202 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003203 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003204 return false;
3205 }
3206 Value = NewVal.getInt();
3207 return true;
3208 }
3209 bool found(APFloat &Value, QualType SubobjType) {
3210 if (!checkConst(SubobjType))
3211 return false;
3212 Value = NewVal.getFloat();
3213 return true;
3214 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003215};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003216} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003217
Richard Smith3229b742013-05-05 21:17:10 +00003218const AccessKinds ModifySubobjectHandler::AccessKind;
3219
Richard Smith3da88fa2013-04-26 14:36:30 +00003220/// Update the designated sub-object of an rvalue to the given value.
3221static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003222 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003223 const SubobjectDesignator &Sub,
3224 APValue &NewVal) {
3225 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003226 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003227}
3228
Richard Smith84f6dcf2012-02-02 01:16:57 +00003229/// Find the position where two subobject designators diverge, or equivalently
3230/// the length of the common initial subsequence.
3231static unsigned FindDesignatorMismatch(QualType ObjType,
3232 const SubobjectDesignator &A,
3233 const SubobjectDesignator &B,
3234 bool &WasArrayIndex) {
3235 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3236 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003237 if (!ObjType.isNull() &&
3238 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003239 // Next subobject is an array element.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003240 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003241 WasArrayIndex = true;
3242 return I;
3243 }
Richard Smith66c96992012-02-18 22:04:06 +00003244 if (ObjType->isAnyComplexType())
3245 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3246 else
3247 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003248 } else {
Richard Smith5b5e27a2019-05-10 20:05:31 +00003249 if (A.Entries[I].getAsBaseOrMember() !=
3250 B.Entries[I].getAsBaseOrMember()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003251 WasArrayIndex = false;
3252 return I;
3253 }
3254 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3255 // Next subobject is a field.
3256 ObjType = FD->getType();
3257 else
3258 // Next subobject is a base class.
3259 ObjType = QualType();
3260 }
3261 }
3262 WasArrayIndex = false;
3263 return I;
3264}
3265
3266/// Determine whether the given subobject designators refer to elements of the
3267/// same array object.
3268static bool AreElementsOfSameArray(QualType ObjType,
3269 const SubobjectDesignator &A,
3270 const SubobjectDesignator &B) {
3271 if (A.Entries.size() != B.Entries.size())
3272 return false;
3273
George Burgess IVa51c4072015-10-16 01:49:01 +00003274 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003275 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3276 // A is a subobject of the array element.
3277 return false;
3278
3279 // If A (and B) designates an array element, the last entry will be the array
3280 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3281 // of length 1' case, and the entire path must match.
3282 bool WasArrayIndex;
3283 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3284 return CommonLength >= A.Entries.size() - IsArray;
3285}
3286
Richard Smith3229b742013-05-05 21:17:10 +00003287/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003288static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3289 AccessKinds AK, const LValue &LVal,
3290 QualType LValType) {
Richard Smith51ce8442019-05-17 08:01:34 +00003291 if (LVal.InvalidBase) {
3292 Info.FFDiag(E);
3293 return CompleteObject();
3294 }
3295
Richard Smith3229b742013-05-05 21:17:10 +00003296 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003297 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003298 return CompleteObject();
3299 }
3300
Craig Topper36250ad2014-05-12 05:36:57 +00003301 CallStackFrame *Frame = nullptr;
Richard Smith37be3362019-05-04 04:00:45 +00003302 unsigned Depth = 0;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003303 if (LVal.getLValueCallIndex()) {
Richard Smith37be3362019-05-04 04:00:45 +00003304 std::tie(Frame, Depth) =
3305 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003306 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003307 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003308 << AK << LVal.Base.is<const ValueDecl*>();
3309 NoteLValueLocation(Info, LVal.Base);
3310 return CompleteObject();
3311 }
Richard Smith3229b742013-05-05 21:17:10 +00003312 }
3313
Richard Smith7bd54ab2019-05-15 20:22:21 +00003314 bool IsAccess = isFormalAccess(AK);
3315
Richard Smith3229b742013-05-05 21:17:10 +00003316 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3317 // is not a constant expression (even if the object is non-volatile). We also
3318 // apply this rule to C++98, in order to conform to the expected 'volatile'
3319 // semantics.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003320 if (IsAccess && LValType.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003321 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003322 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003323 << AK << LValType;
3324 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003325 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003326 return CompleteObject();
3327 }
3328
3329 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003330 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003331 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00003332
3333 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3334 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3335 // In C++11, constexpr, non-volatile variables initialized with constant
3336 // expressions are constant expressions too. Inside constexpr functions,
3337 // parameters are constant expressions even if they're non-const.
3338 // In C++1y, objects local to a constant expression (those with a Frame) are
3339 // both readable and writable inside constant expressions.
3340 // In C, such things can also be folded, although they are not ICEs.
3341 const VarDecl *VD = dyn_cast<VarDecl>(D);
3342 if (VD) {
3343 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3344 VD = VDef;
3345 }
3346 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003347 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003348 return CompleteObject();
3349 }
3350
Richard Smith3229b742013-05-05 21:17:10 +00003351 // Unless we're looking at a local variable or argument in a constexpr call,
3352 // the variable we're reading must be const.
3353 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003354 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smithdebad642019-05-12 09:39:08 +00003355 declaresSameEntity(
3356 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003357 // OK, we can read and modify an object if we're in the process of
3358 // evaluating its initializer, because its lifetime began in this
3359 // evaluation.
Richard Smithdebad642019-05-12 09:39:08 +00003360 } else if (isModification(AK)) {
3361 // All the remaining cases do not permit modification of the object.
Faisal Valie690b7a2016-07-02 22:34:24 +00003362 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003363 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003364 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003365 // OK, we can read this variable.
3366 } else if (BaseType->isIntegralOrEnumerationType()) {
Richard Smithdebad642019-05-12 09:39:08 +00003367 // In OpenCL if a variable is in constant address space it is a const
3368 // value.
Xiuli Pan244e3f62016-06-07 04:34:00 +00003369 if (!(BaseType.isConstQualified() ||
3370 (Info.getLangOpts().OpenCL &&
3371 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003372 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003373 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003374 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003375 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003376 Info.Note(VD->getLocation(), diag::note_declared_at);
3377 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003378 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003379 }
3380 return CompleteObject();
3381 }
Richard Smith7bd54ab2019-05-15 20:22:21 +00003382 } else if (!IsAccess) {
Richard Smithdebad642019-05-12 09:39:08 +00003383 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003384 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3385 // We support folding of const floating-point types, in order to make
3386 // static const data members of such types (supported as an extension)
3387 // more useful.
3388 if (Info.getLangOpts().CPlusPlus11) {
3389 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3390 Info.Note(VD->getLocation(), diag::note_declared_at);
3391 } else {
3392 Info.CCEDiag(E);
3393 }
George Burgess IVb5316982016-12-27 05:33:20 +00003394 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3395 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3396 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003397 } else {
3398 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003399 if (Info.checkingPotentialConstantExpression() &&
3400 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3401 // The definition of this variable could be constexpr. We can't
3402 // access it right now, but may be able to in future.
3403 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003404 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 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 }
3411 }
3412
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003413 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003414 return CompleteObject();
3415 } else {
3416 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3417
3418 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003419 if (const MaterializeTemporaryExpr *MTE =
Richard Smithee0ce3022019-05-17 07:06:46 +00003420 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
Richard Smithe6c01442013-06-05 00:46:14 +00003421 assert(MTE->getStorageDuration() == SD_Static &&
3422 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003423
Richard Smithe6c01442013-06-05 00:46:14 +00003424 // Per C++1y [expr.const]p2:
3425 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3426 // - a [...] glvalue of integral or enumeration type that refers to
3427 // a non-volatile const object [...]
3428 // [...]
3429 // - a [...] glvalue of literal type that refers to a non-volatile
3430 // object whose lifetime began within the evaluation of e.
3431 //
3432 // C++11 misses the 'began within the evaluation of e' check and
3433 // instead allows all temporaries, including things like:
3434 // int &&r = 1;
3435 // int x = ++r;
3436 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003437 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003438 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3439 const ValueDecl *ED = MTE->getExtendingDecl();
3440 if (!(BaseType.isConstQualified() &&
3441 BaseType->isIntegralOrEnumerationType()) &&
3442 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003443 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003444 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Faisal Valie690b7a2016-07-02 22:34:24 +00003445 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003446 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3447 return CompleteObject();
3448 }
3449
3450 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3451 assert(BaseVal && "got reference to unevaluated temporary");
3452 } else {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003453 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003454 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smithee0ce3022019-05-17 07:06:46 +00003455 APValue Val;
3456 LVal.moveInto(Val);
3457 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3458 << AK
3459 << Val.getAsString(Info.Ctx,
3460 Info.Ctx.getLValueReferenceType(LValType));
3461 NoteLValueLocation(Info, LVal.Base);
Richard Smithe6c01442013-06-05 00:46:14 +00003462 return CompleteObject();
3463 }
3464 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003465 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003466 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003467 }
Richard Smith7525ff62013-05-09 07:14:00 +00003468 }
3469
Richard Smith9defb7d2018-02-21 03:38:30 +00003470 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003471 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003472 //
3473 // FIXME: Not all local state is mutable. Allow local constant subobjects
3474 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003475 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3476 Info.EvalStatus.HasSideEffects) ||
Richard Smithdebad642019-05-12 09:39:08 +00003477 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
Richard Smith3229b742013-05-05 21:17:10 +00003478 return CompleteObject();
3479
Richard Smithdebad642019-05-12 09:39:08 +00003480 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003481}
3482
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003483/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003484/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3485/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003486///
3487/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003488/// \param Conv - The expression for which we are performing the conversion.
3489/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003490/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3491/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003492/// \param LVal - The glvalue on which we are attempting to perform this action.
3493/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003494static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003495 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003496 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003497 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003498 return false;
3499
Richard Smith3229b742013-05-05 21:17:10 +00003500 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003501 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Eric Fiselier708afb52019-05-16 21:04:15 +00003502
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003503 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003504 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3505 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3506 // initializer until now for such expressions. Such an expression can't be
3507 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003508 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003509 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003510 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003511 }
Richard Smith3229b742013-05-05 21:17:10 +00003512 APValue Lit;
3513 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3514 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003515 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
Richard Smith3229b742013-05-05 21:17:10 +00003516 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003517 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00003518 // Special-case character extraction so we don't have to construct an
3519 // APValue for the whole string.
Eli Friedman041adb02019-02-09 02:22:17 +00003520 assert(LVal.Designator.Entries.size() <= 1 &&
Eli Friedman3bf72d72019-02-08 21:18:46 +00003521 "Can only read characters from string literals");
Eli Friedman041adb02019-02-09 02:22:17 +00003522 if (LVal.Designator.Entries.empty()) {
3523 // Fail for now for LValue to RValue conversion of an array.
3524 // (This shouldn't show up in C/C++, but it could be triggered by a
3525 // weird EvaluateAsRValue call from a tool.)
3526 Info.FFDiag(Conv);
3527 return false;
3528 }
Eli Friedman3bf72d72019-02-08 21:18:46 +00003529 if (LVal.Designator.isOnePastTheEnd()) {
3530 if (Info.getLangOpts().CPlusPlus11)
3531 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3532 else
3533 Info.FFDiag(Conv);
3534 return false;
3535 }
Richard Smith5b5e27a2019-05-10 20:05:31 +00003536 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
Eli Friedman3bf72d72019-02-08 21:18:46 +00003537 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3538 return true;
Richard Smith96e0c102011-11-04 02:25:55 +00003539 }
Richard Smith11562c52011-10-28 17:51:58 +00003540 }
3541
Richard Smith3229b742013-05-05 21:17:10 +00003542 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3543 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003544}
3545
3546/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003547static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003548 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003549 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003550 return false;
3551
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003552 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003553 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003554 return false;
3555 }
3556
Richard Smith3229b742013-05-05 21:17:10 +00003557 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003558 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3559}
3560
3561namespace {
3562struct CompoundAssignSubobjectHandler {
3563 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003564 const Expr *E;
3565 QualType PromotedLHSType;
3566 BinaryOperatorKind Opcode;
3567 const APValue &RHS;
3568
3569 static const AccessKinds AccessKind = AK_Assign;
3570
3571 typedef bool result_type;
3572
3573 bool checkConst(QualType QT) {
3574 // Assigning to a const object has undefined behavior.
3575 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003576 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003577 return false;
3578 }
3579 return true;
3580 }
3581
3582 bool failed() { return false; }
3583 bool found(APValue &Subobj, QualType SubobjType) {
3584 switch (Subobj.getKind()) {
3585 case APValue::Int:
3586 return found(Subobj.getInt(), SubobjType);
3587 case APValue::Float:
3588 return found(Subobj.getFloat(), SubobjType);
3589 case APValue::ComplexInt:
3590 case APValue::ComplexFloat:
3591 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003592 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003593 return false;
3594 case APValue::LValue:
3595 return foundPointer(Subobj, SubobjType);
3596 default:
3597 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003598 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003599 return false;
3600 }
3601 }
3602 bool found(APSInt &Value, QualType SubobjType) {
3603 if (!checkConst(SubobjType))
3604 return false;
3605
Tan S. B.9f935e82018-12-18 07:38:06 +00003606 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003607 // We don't support compound assignment on integer-cast-to-pointer
3608 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003609 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003610 return false;
3611 }
3612
Tan S. B.9f935e82018-12-18 07:38:06 +00003613 if (RHS.isInt()) {
3614 APSInt LHS =
3615 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3616 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3617 return false;
3618 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3619 return true;
3620 } else if (RHS.isFloat()) {
3621 APFloat FValue(0.0);
3622 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3623 FValue) &&
3624 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3625 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3626 Value);
3627 }
3628
3629 Info.FFDiag(E);
3630 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003631 }
3632 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003633 return checkConst(SubobjType) &&
3634 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3635 Value) &&
3636 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3637 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003638 }
3639 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3640 if (!checkConst(SubobjType))
3641 return false;
3642
3643 QualType PointeeType;
3644 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3645 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003646
3647 if (PointeeType.isNull() || !RHS.isInt() ||
3648 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003649 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003650 return false;
3651 }
3652
Richard Smithd6cc1982017-01-31 02:23:02 +00003653 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003654 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003655 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003656
3657 LValue LVal;
3658 LVal.setFrom(Info.Ctx, Subobj);
3659 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3660 return false;
3661 LVal.moveInto(Subobj);
3662 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003663 }
Richard Smith43e77732013-05-07 04:50:00 +00003664};
3665} // end anonymous namespace
3666
3667const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3668
3669/// Perform a compound assignment of LVal <op>= RVal.
3670static bool handleCompoundAssignment(
3671 EvalInfo &Info, const Expr *E,
3672 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3673 BinaryOperatorKind Opcode, const APValue &RVal) {
3674 if (LVal.Designator.Invalid)
3675 return false;
3676
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003677 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003678 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003679 return false;
3680 }
3681
3682 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3683 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3684 RVal };
3685 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3686}
3687
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003688namespace {
3689struct IncDecSubobjectHandler {
3690 EvalInfo &Info;
3691 const UnaryOperator *E;
3692 AccessKinds AccessKind;
3693 APValue *Old;
3694
Richard Smith243ef902013-05-05 23:31:59 +00003695 typedef bool result_type;
3696
3697 bool checkConst(QualType QT) {
3698 // Assigning to a const object has undefined behavior.
3699 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003700 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003701 return false;
3702 }
3703 return true;
3704 }
3705
3706 bool failed() { return false; }
3707 bool found(APValue &Subobj, QualType SubobjType) {
3708 // Stash the old value. Also clear Old, so we don't clobber it later
3709 // if we're post-incrementing a complex.
3710 if (Old) {
3711 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003712 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003713 }
3714
3715 switch (Subobj.getKind()) {
3716 case APValue::Int:
3717 return found(Subobj.getInt(), SubobjType);
3718 case APValue::Float:
3719 return found(Subobj.getFloat(), SubobjType);
3720 case APValue::ComplexInt:
3721 return found(Subobj.getComplexIntReal(),
3722 SubobjType->castAs<ComplexType>()->getElementType()
3723 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3724 case APValue::ComplexFloat:
3725 return found(Subobj.getComplexFloatReal(),
3726 SubobjType->castAs<ComplexType>()->getElementType()
3727 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3728 case APValue::LValue:
3729 return foundPointer(Subobj, SubobjType);
3730 default:
3731 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003732 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003733 return false;
3734 }
3735 }
3736 bool found(APSInt &Value, QualType SubobjType) {
3737 if (!checkConst(SubobjType))
3738 return false;
3739
3740 if (!SubobjType->isIntegerType()) {
3741 // We don't support increment / decrement on integer-cast-to-pointer
3742 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003743 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003744 return false;
3745 }
3746
3747 if (Old) *Old = APValue(Value);
3748
3749 // bool arithmetic promotes to int, and the conversion back to bool
3750 // doesn't reduce mod 2^n, so special-case it.
3751 if (SubobjType->isBooleanType()) {
3752 if (AccessKind == AK_Increment)
3753 Value = 1;
3754 else
3755 Value = !Value;
3756 return true;
3757 }
3758
3759 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003760 if (AccessKind == AK_Increment) {
3761 ++Value;
3762
3763 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3764 APSInt ActualValue(Value, /*IsUnsigned*/true);
3765 return HandleOverflow(Info, E, ActualValue, SubobjType);
3766 }
3767 } else {
3768 --Value;
3769
3770 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3771 unsigned BitWidth = Value.getBitWidth();
3772 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3773 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003774 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003775 }
3776 }
3777 return true;
3778 }
3779 bool found(APFloat &Value, QualType SubobjType) {
3780 if (!checkConst(SubobjType))
3781 return false;
3782
3783 if (Old) *Old = APValue(Value);
3784
3785 APFloat One(Value.getSemantics(), 1);
3786 if (AccessKind == AK_Increment)
3787 Value.add(One, APFloat::rmNearestTiesToEven);
3788 else
3789 Value.subtract(One, APFloat::rmNearestTiesToEven);
3790 return true;
3791 }
3792 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3793 if (!checkConst(SubobjType))
3794 return false;
3795
3796 QualType PointeeType;
3797 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3798 PointeeType = PT->getPointeeType();
3799 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003800 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003801 return false;
3802 }
3803
3804 LValue LVal;
3805 LVal.setFrom(Info.Ctx, Subobj);
3806 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3807 AccessKind == AK_Increment ? 1 : -1))
3808 return false;
3809 LVal.moveInto(Subobj);
3810 return true;
3811 }
Richard Smith243ef902013-05-05 23:31:59 +00003812};
3813} // end anonymous namespace
3814
3815/// Perform an increment or decrement on LVal.
3816static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3817 QualType LValType, bool IsIncrement, APValue *Old) {
3818 if (LVal.Designator.Invalid)
3819 return false;
3820
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003821 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003822 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003823 return false;
3824 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003825
3826 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3827 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3828 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3829 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3830}
3831
Richard Smithe97cbd72011-11-11 04:05:33 +00003832/// Build an lvalue for the object argument of a member function call.
3833static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3834 LValue &This) {
3835 if (Object->getType()->isPointerType())
3836 return EvaluatePointer(Object, This, Info);
3837
3838 if (Object->isGLValue())
3839 return EvaluateLValue(Object, This, Info);
3840
Richard Smithd9f663b2013-04-22 15:31:51 +00003841 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003842 return EvaluateTemporary(Object, This, Info);
3843
Faisal Valie690b7a2016-07-02 22:34:24 +00003844 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003845 return false;
3846}
3847
3848/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3849/// lvalue referring to the result.
3850///
3851/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003852/// \param LV - An lvalue referring to the base of the member pointer.
3853/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003854/// \param IncludeMember - Specifies whether the member itself is included in
3855/// the resulting LValue subobject designator. This is not possible when
3856/// creating a bound member function.
3857/// \return The field or method declaration to which the member pointer refers,
3858/// or 0 if evaluation fails.
3859static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003860 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003861 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003862 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003863 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003864 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003865 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003866 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003867
3868 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3869 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003870 if (!MemPtr.getDecl()) {
3871 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003872 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003873 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003874 }
Richard Smith253c2a32012-01-27 01:14:48 +00003875
Richard Smith027bf112011-11-17 22:56:20 +00003876 if (MemPtr.isDerivedMember()) {
3877 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003878 // The end of the derived-to-base path for the base object must match the
3879 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003880 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003881 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003882 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003883 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003884 }
Richard Smith027bf112011-11-17 22:56:20 +00003885 unsigned PathLengthToMember =
3886 LV.Designator.Entries.size() - MemPtr.Path.size();
3887 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3888 const CXXRecordDecl *LVDecl = getAsBaseClass(
3889 LV.Designator.Entries[PathLengthToMember + I]);
3890 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003891 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003892 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003893 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003894 }
Richard Smith027bf112011-11-17 22:56:20 +00003895 }
3896
3897 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003898 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003899 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003900 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003901 } else if (!MemPtr.Path.empty()) {
3902 // Extend the LValue path with the member pointer's path.
3903 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3904 MemPtr.Path.size() + IncludeMember);
3905
3906 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003907 if (const PointerType *PT = LVType->getAs<PointerType>())
3908 LVType = PT->getPointeeType();
3909 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3910 assert(RD && "member pointer access on non-class-type expression");
3911 // The first class in the path is that of the lvalue.
3912 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3913 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003914 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003915 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003916 RD = Base;
3917 }
3918 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003919 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3920 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003921 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003922 }
3923
3924 // Add the member. Note that we cannot build bound member functions here.
3925 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003926 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003927 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003928 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003929 } else if (const IndirectFieldDecl *IFD =
3930 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003931 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003932 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003933 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003934 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003935 }
Richard Smith027bf112011-11-17 22:56:20 +00003936 }
3937
3938 return MemPtr.getDecl();
3939}
3940
Richard Smith84401042013-06-03 05:03:02 +00003941static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3942 const BinaryOperator *BO,
3943 LValue &LV,
3944 bool IncludeMember = true) {
3945 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3946
3947 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003948 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003949 MemberPtr MemPtr;
3950 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3951 }
Craig Topper36250ad2014-05-12 05:36:57 +00003952 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003953 }
3954
3955 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3956 BO->getRHS(), IncludeMember);
3957}
3958
Richard Smith027bf112011-11-17 22:56:20 +00003959/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3960/// the provided lvalue, which currently refers to the base object.
3961static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3962 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003963 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003964 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003965 return false;
3966
Richard Smitha8105bc2012-01-06 16:39:00 +00003967 QualType TargetQT = E->getType();
3968 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3969 TargetQT = PT->getPointeeType();
3970
3971 // Check this cast lands within the final derived-to-base subobject path.
3972 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003973 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003974 << D.MostDerivedType << TargetQT;
3975 return false;
3976 }
3977
Richard Smith027bf112011-11-17 22:56:20 +00003978 // Check the type of the final cast. We don't need to check the path,
3979 // since a cast can only be formed if the path is unique.
3980 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003981 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3982 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003983 if (NewEntriesSize == D.MostDerivedPathLength)
3984 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3985 else
Richard Smith027bf112011-11-17 22:56:20 +00003986 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003987 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003988 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003989 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003990 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003991 }
Richard Smith027bf112011-11-17 22:56:20 +00003992
3993 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003994 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003995}
3996
Mike Stump876387b2009-10-27 22:09:17 +00003997namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003998enum EvalStmtResult {
3999 /// Evaluation failed.
4000 ESR_Failed,
4001 /// Hit a 'return' statement.
4002 ESR_Returned,
4003 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00004004 ESR_Succeeded,
4005 /// Hit a 'continue' statement.
4006 ESR_Continue,
4007 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00004008 ESR_Break,
4009 /// Still scanning for 'case' or 'default' statement.
4010 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00004011};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004012}
Richard Smith254a73d2011-10-28 22:34:42 +00004013
Richard Smith97fcf4b2016-08-14 23:15:52 +00004014static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4015 // We don't need to evaluate the initializer for a static local.
4016 if (!VD->hasLocalStorage())
4017 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00004018
Richard Smith97fcf4b2016-08-14 23:15:52 +00004019 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004020 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00004021
Richard Smith97fcf4b2016-08-14 23:15:52 +00004022 const Expr *InitE = VD->getInit();
4023 if (!InitE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004024 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
4025 << false << VD->getType();
Richard Smith97fcf4b2016-08-14 23:15:52 +00004026 Val = APValue();
4027 return false;
4028 }
Richard Smith51f03172013-06-20 03:00:05 +00004029
Richard Smith97fcf4b2016-08-14 23:15:52 +00004030 if (InitE->isValueDependent())
4031 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00004032
Richard Smith97fcf4b2016-08-14 23:15:52 +00004033 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4034 // Wipe out any partially-computed value, to allow tracking that this
4035 // evaluation failed.
4036 Val = APValue();
4037 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00004038 }
4039
4040 return true;
4041}
4042
Richard Smith97fcf4b2016-08-14 23:15:52 +00004043static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4044 bool OK = true;
4045
4046 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4047 OK &= EvaluateVarDecl(Info, VD);
4048
4049 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4050 for (auto *BD : DD->bindings())
4051 if (auto *VD = BD->getHoldingVar())
4052 OK &= EvaluateDecl(Info, VD);
4053
4054 return OK;
4055}
4056
4057
Richard Smith4e18ca52013-05-06 05:56:11 +00004058/// Evaluate a condition (either a variable declaration or an expression).
4059static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4060 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004061 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004062 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4063 return false;
4064 return EvaluateAsBooleanCondition(Cond, Result, Info);
4065}
4066
Richard Smith89210072016-04-04 23:29:43 +00004067namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004068/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00004069/// statement should be stored.
4070struct StmtResult {
4071 /// The APValue that should be filled in with the returned value.
4072 APValue &Value;
4073 /// The location containing the result, if any (used to support RVO).
4074 const LValue *Slot;
4075};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004076
4077struct TempVersionRAII {
4078 CallStackFrame &Frame;
4079
4080 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4081 Frame.pushTempVersion();
4082 }
4083
4084 ~TempVersionRAII() {
4085 Frame.popTempVersion();
4086 }
4087};
4088
Richard Smith89210072016-04-04 23:29:43 +00004089}
Richard Smith52a980a2015-08-28 02:43:42 +00004090
4091static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00004092 const Stmt *S,
4093 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00004094
4095/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00004096static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004097 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00004098 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004099 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00004100 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00004101 case ESR_Break:
4102 return ESR_Succeeded;
4103 case ESR_Succeeded:
4104 case ESR_Continue:
4105 return ESR_Continue;
4106 case ESR_Failed:
4107 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00004108 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00004109 return ESR;
4110 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00004111 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00004112}
4113
Richard Smith496ddcf2013-05-12 17:32:42 +00004114/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004115static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004116 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004117 BlockScopeRAII Scope(Info);
4118
Richard Smith496ddcf2013-05-12 17:32:42 +00004119 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00004120 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004121 {
4122 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004123 if (const Stmt *Init = SS->getInit()) {
4124 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4125 if (ESR != ESR_Succeeded)
4126 return ESR;
4127 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004128 if (SS->getConditionVariable() &&
4129 !EvaluateDecl(Info, SS->getConditionVariable()))
4130 return ESR_Failed;
4131 if (!EvaluateInteger(SS->getCond(), Value, Info))
4132 return ESR_Failed;
4133 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004134
4135 // Find the switch case corresponding to the value of the condition.
4136 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00004137 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004138 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4139 SC = SC->getNextSwitchCase()) {
4140 if (isa<DefaultStmt>(SC)) {
4141 Found = SC;
4142 continue;
4143 }
4144
4145 const CaseStmt *CS = cast<CaseStmt>(SC);
4146 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4147 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4148 : LHS;
4149 if (LHS <= Value && Value <= RHS) {
4150 Found = SC;
4151 break;
4152 }
4153 }
4154
4155 if (!Found)
4156 return ESR_Succeeded;
4157
4158 // Search the switch body for the switch case and evaluate it from there.
4159 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4160 case ESR_Break:
4161 return ESR_Succeeded;
4162 case ESR_Succeeded:
4163 case ESR_Continue:
4164 case ESR_Failed:
4165 case ESR_Returned:
4166 return ESR;
4167 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004168 // This can only happen if the switch case is nested within a statement
4169 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004170 Info.FFDiag(Found->getBeginLoc(),
4171 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004172 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004173 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004174 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004175}
4176
Richard Smith254a73d2011-10-28 22:34:42 +00004177// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004178static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004179 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004180 if (!Info.nextStep(S))
4181 return ESR_Failed;
4182
Richard Smith496ddcf2013-05-12 17:32:42 +00004183 // If we're hunting down a 'case' or 'default' label, recurse through
4184 // substatements until we hit the label.
4185 if (Case) {
4186 // FIXME: We don't start the lifetime of objects whose initialization we
4187 // jump over. However, such objects must be of class type with a trivial
4188 // default constructor that initialize all subobjects, so must be empty,
4189 // so this almost never matters.
4190 switch (S->getStmtClass()) {
4191 case Stmt::CompoundStmtClass:
4192 // FIXME: Precompute which substatement of a compound statement we
4193 // would jump to, and go straight there rather than performing a
4194 // linear scan each time.
4195 case Stmt::LabelStmtClass:
4196 case Stmt::AttributedStmtClass:
4197 case Stmt::DoStmtClass:
4198 break;
4199
4200 case Stmt::CaseStmtClass:
4201 case Stmt::DefaultStmtClass:
4202 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004203 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004204 break;
4205
4206 case Stmt::IfStmtClass: {
4207 // FIXME: Precompute which side of an 'if' we would jump to, and go
4208 // straight there rather than scanning both sides.
4209 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004210
4211 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4212 // preceded by our switch label.
4213 BlockScopeRAII Scope(Info);
4214
Richard Smith496ddcf2013-05-12 17:32:42 +00004215 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4216 if (ESR != ESR_CaseNotFound || !IS->getElse())
4217 return ESR;
4218 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4219 }
4220
4221 case Stmt::WhileStmtClass: {
4222 EvalStmtResult ESR =
4223 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4224 if (ESR != ESR_Continue)
4225 return ESR;
4226 break;
4227 }
4228
4229 case Stmt::ForStmtClass: {
4230 const ForStmt *FS = cast<ForStmt>(S);
4231 EvalStmtResult ESR =
4232 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4233 if (ESR != ESR_Continue)
4234 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004235 if (FS->getInc()) {
4236 FullExpressionRAII IncScope(Info);
4237 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4238 return ESR_Failed;
4239 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004240 break;
4241 }
4242
4243 case Stmt::DeclStmtClass:
4244 // FIXME: If the variable has initialization that can't be jumped over,
4245 // bail out of any immediately-surrounding compound-statement too.
4246 default:
4247 return ESR_CaseNotFound;
4248 }
4249 }
4250
Richard Smith254a73d2011-10-28 22:34:42 +00004251 switch (S->getStmtClass()) {
4252 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004253 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004254 // Don't bother evaluating beyond an expression-statement which couldn't
4255 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004256 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004257 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004258 return ESR_Failed;
4259 return ESR_Succeeded;
4260 }
4261
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004262 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004263 return ESR_Failed;
4264
4265 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004266 return ESR_Succeeded;
4267
Richard Smithd9f663b2013-04-22 15:31:51 +00004268 case Stmt::DeclStmtClass: {
4269 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004270 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004271 // Each declaration initialization is its own full-expression.
4272 // FIXME: This isn't quite right; if we're performing aggregate
4273 // initialization, each braced subexpression is its own full-expression.
4274 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004275 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004276 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004277 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004278 return ESR_Succeeded;
4279 }
4280
Richard Smith357362d2011-12-13 06:39:58 +00004281 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004282 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004283 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004284 if (RetExpr &&
4285 !(Result.Slot
4286 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4287 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004288 return ESR_Failed;
4289 return ESR_Returned;
4290 }
Richard Smith254a73d2011-10-28 22:34:42 +00004291
4292 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004293 BlockScopeRAII Scope(Info);
4294
Richard Smith254a73d2011-10-28 22:34:42 +00004295 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004296 for (const auto *BI : CS->body()) {
4297 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004298 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004299 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004300 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004301 return ESR;
4302 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004303 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004304 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004305
4306 case Stmt::IfStmtClass: {
4307 const IfStmt *IS = cast<IfStmt>(S);
4308
4309 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004310 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004311 if (const Stmt *Init = IS->getInit()) {
4312 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4313 if (ESR != ESR_Succeeded)
4314 return ESR;
4315 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004316 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004317 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004318 return ESR_Failed;
4319
4320 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4321 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4322 if (ESR != ESR_Succeeded)
4323 return ESR;
4324 }
4325 return ESR_Succeeded;
4326 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004327
4328 case Stmt::WhileStmtClass: {
4329 const WhileStmt *WS = cast<WhileStmt>(S);
4330 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004331 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004332 bool Continue;
4333 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4334 Continue))
4335 return ESR_Failed;
4336 if (!Continue)
4337 break;
4338
4339 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4340 if (ESR != ESR_Continue)
4341 return ESR;
4342 }
4343 return ESR_Succeeded;
4344 }
4345
4346 case Stmt::DoStmtClass: {
4347 const DoStmt *DS = cast<DoStmt>(S);
4348 bool Continue;
4349 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004350 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004351 if (ESR != ESR_Continue)
4352 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004353 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004354
Richard Smith08d6a2c2013-07-24 07:11:57 +00004355 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004356 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4357 return ESR_Failed;
4358 } while (Continue);
4359 return ESR_Succeeded;
4360 }
4361
4362 case Stmt::ForStmtClass: {
4363 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004364 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004365 if (FS->getInit()) {
4366 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4367 if (ESR != ESR_Succeeded)
4368 return ESR;
4369 }
4370 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004371 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004372 bool Continue = true;
4373 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4374 FS->getCond(), Continue))
4375 return ESR_Failed;
4376 if (!Continue)
4377 break;
4378
4379 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4380 if (ESR != ESR_Continue)
4381 return ESR;
4382
Richard Smith08d6a2c2013-07-24 07:11:57 +00004383 if (FS->getInc()) {
4384 FullExpressionRAII IncScope(Info);
4385 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4386 return ESR_Failed;
4387 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004388 }
4389 return ESR_Succeeded;
4390 }
4391
Richard Smith896e0d72013-05-06 06:51:17 +00004392 case Stmt::CXXForRangeStmtClass: {
4393 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004394 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004395
Richard Smith8baa5002018-09-28 18:44:09 +00004396 // Evaluate the init-statement if present.
4397 if (FS->getInit()) {
4398 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4399 if (ESR != ESR_Succeeded)
4400 return ESR;
4401 }
4402
Richard Smith896e0d72013-05-06 06:51:17 +00004403 // Initialize the __range variable.
4404 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4405 if (ESR != ESR_Succeeded)
4406 return ESR;
4407
4408 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004409 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4410 if (ESR != ESR_Succeeded)
4411 return ESR;
4412 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004413 if (ESR != ESR_Succeeded)
4414 return ESR;
4415
4416 while (true) {
4417 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004418 {
4419 bool Continue = true;
4420 FullExpressionRAII CondExpr(Info);
4421 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4422 return ESR_Failed;
4423 if (!Continue)
4424 break;
4425 }
Richard Smith896e0d72013-05-06 06:51:17 +00004426
4427 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004428 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004429 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4430 if (ESR != ESR_Succeeded)
4431 return ESR;
4432
4433 // Loop body.
4434 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4435 if (ESR != ESR_Continue)
4436 return ESR;
4437
4438 // Increment: ++__begin
4439 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4440 return ESR_Failed;
4441 }
4442
4443 return ESR_Succeeded;
4444 }
4445
Richard Smith496ddcf2013-05-12 17:32:42 +00004446 case Stmt::SwitchStmtClass:
4447 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4448
Richard Smith4e18ca52013-05-06 05:56:11 +00004449 case Stmt::ContinueStmtClass:
4450 return ESR_Continue;
4451
4452 case Stmt::BreakStmtClass:
4453 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004454
4455 case Stmt::LabelStmtClass:
4456 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4457
4458 case Stmt::AttributedStmtClass:
4459 // As a general principle, C++11 attributes can be ignored without
4460 // any semantic impact.
4461 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4462 Case);
4463
4464 case Stmt::CaseStmtClass:
4465 case Stmt::DefaultStmtClass:
4466 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004467 case Stmt::CXXTryStmtClass:
4468 // Evaluate try blocks by evaluating all sub statements.
4469 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004470 }
4471}
4472
Richard Smithcc36f692011-12-22 02:22:31 +00004473/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4474/// default constructor. If so, we'll fold it whether or not it's marked as
4475/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4476/// so we need special handling.
4477static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004478 const CXXConstructorDecl *CD,
4479 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004480 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4481 return false;
4482
Richard Smith66e05fe2012-01-18 05:21:49 +00004483 // Value-initialization does not call a trivial default constructor, so such a
4484 // call is a core constant expression whether or not the constructor is
4485 // constexpr.
4486 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004487 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004488 // FIXME: If DiagDecl is an implicitly-declared special member function,
4489 // we should be much more explicit about why it's not constexpr.
4490 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4491 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4492 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004493 } else {
4494 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4495 }
4496 }
4497 return true;
4498}
4499
Richard Smith357362d2011-12-13 06:39:58 +00004500/// CheckConstexprFunction - Check that a function can be called in a constant
4501/// expression.
4502static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4503 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004504 const FunctionDecl *Definition,
4505 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004506 // Potential constant expressions can contain calls to declared, but not yet
4507 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004508 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004509 Declaration->isConstexpr())
4510 return false;
4511
James Y Knightc7d3e602018-10-05 17:49:48 +00004512 // Bail out if the function declaration itself is invalid. We will
4513 // have produced a relevant diagnostic while parsing it, so just
4514 // note the problematic sub-expression.
4515 if (Declaration->isInvalidDecl()) {
4516 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004517 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004518 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004519
Richard Smithd9c6b032019-05-09 19:45:49 +00004520 // DR1872: An instantiated virtual constexpr function can't be called in a
Richard Smith921f1322019-05-13 23:35:21 +00004521 // constant expression (prior to C++20). We can still constant-fold such a
4522 // call.
4523 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4524 cast<CXXMethodDecl>(Declaration)->isVirtual())
4525 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4526
4527 if (Definition && Definition->isInvalidDecl()) {
4528 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd9c6b032019-05-09 19:45:49 +00004529 return false;
4530 }
4531
Richard Smith357362d2011-12-13 06:39:58 +00004532 // Can we evaluate this function call?
Richard Smith921f1322019-05-13 23:35:21 +00004533 if (Definition && Definition->isConstexpr() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004534 return true;
4535
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004536 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004537 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004538
Richard Smith5179eb72016-06-28 19:03:57 +00004539 // If this function is not constexpr because it is an inherited
4540 // non-constexpr constructor, diagnose that directly.
4541 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4542 if (CD && CD->isInheritingConstructor()) {
4543 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004544 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004545 DiagDecl = CD = Inherited;
4546 }
4547
4548 // FIXME: If DiagDecl is an implicitly-declared special member function
4549 // or an inheriting constructor, we should be much more explicit about why
4550 // it's not constexpr.
4551 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004552 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004553 << CD->getInheritedConstructor().getConstructor()->getParent();
4554 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004555 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004556 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004557 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4558 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004559 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004560 }
4561 return false;
4562}
4563
Richard Smithdebad642019-05-12 09:39:08 +00004564namespace {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004565struct CheckDynamicTypeHandler {
4566 AccessKinds AccessKind;
Richard Smithdebad642019-05-12 09:39:08 +00004567 typedef bool result_type;
4568 bool failed() { return false; }
4569 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4570 bool found(APSInt &Value, QualType SubobjType) { return true; }
4571 bool found(APFloat &Value, QualType SubobjType) { return true; }
4572};
4573} // end anonymous namespace
4574
Richard Smith7bd54ab2019-05-15 20:22:21 +00004575/// Check that we can access the notional vptr of an object / determine its
4576/// dynamic type.
4577static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4578 AccessKinds AK, bool Polymorphic) {
Richard Smithdab287b2019-05-13 07:51:29 +00004579 if (This.Designator.Invalid)
4580 return false;
4581
Richard Smith7bd54ab2019-05-15 20:22:21 +00004582 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
Richard Smithdebad642019-05-12 09:39:08 +00004583
4584 if (!Obj)
4585 return false;
4586
4587 if (!Obj.Value) {
4588 // The object is not usable in constant expressions, so we can't inspect
4589 // its value to see if it's in-lifetime or what the active union members
4590 // are. We can still check for a one-past-the-end lvalue.
4591 if (This.Designator.isOnePastTheEnd() ||
4592 This.Designator.isMostDerivedAnUnsizedArray()) {
4593 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4594 ? diag::note_constexpr_access_past_end
4595 : diag::note_constexpr_access_unsized_array)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004596 << AK;
Richard Smithdebad642019-05-12 09:39:08 +00004597 return false;
Richard Smith7bd54ab2019-05-15 20:22:21 +00004598 } else if (Polymorphic) {
4599 // Conservatively refuse to perform a polymorphic operation if we would
Richard Smith921f1322019-05-13 23:35:21 +00004600 // not be able to read a notional 'vptr' value.
4601 APValue Val;
4602 This.moveInto(Val);
4603 QualType StarThisType =
4604 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
Richard Smith7bd54ab2019-05-15 20:22:21 +00004605 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4606 << AK << Val.getAsString(Info.Ctx, StarThisType);
Richard Smith921f1322019-05-13 23:35:21 +00004607 return false;
Richard Smithdebad642019-05-12 09:39:08 +00004608 }
4609 return true;
4610 }
4611
Richard Smith7bd54ab2019-05-15 20:22:21 +00004612 CheckDynamicTypeHandler Handler{AK};
Richard Smithdebad642019-05-12 09:39:08 +00004613 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4614}
4615
Richard Smith7bd54ab2019-05-15 20:22:21 +00004616/// Check that the pointee of the 'this' pointer in a member function call is
4617/// either within its lifetime or in its period of construction or destruction.
4618static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4619 const LValue &This) {
4620 return checkDynamicType(Info, E, This, AK_MemberCall, false);
4621}
4622
Richard Smith921f1322019-05-13 23:35:21 +00004623struct DynamicType {
4624 /// The dynamic class type of the object.
4625 const CXXRecordDecl *Type;
4626 /// The corresponding path length in the lvalue.
4627 unsigned PathLength;
4628};
4629
4630static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4631 unsigned PathLength) {
4632 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4633 Designator.Entries.size() && "invalid path length");
4634 return (PathLength == Designator.MostDerivedPathLength)
4635 ? Designator.MostDerivedType->getAsCXXRecordDecl()
4636 : getAsBaseClass(Designator.Entries[PathLength - 1]);
4637}
4638
4639/// Determine the dynamic type of an object.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004640static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4641 LValue &This, AccessKinds AK) {
Richard Smith921f1322019-05-13 23:35:21 +00004642 // If we don't have an lvalue denoting an object of class type, there is no
4643 // meaningful dynamic type. (We consider objects of non-class type to have no
4644 // dynamic type.)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004645 if (!checkDynamicType(Info, E, This, AK, true))
Richard Smith921f1322019-05-13 23:35:21 +00004646 return None;
4647
Richard Smith7bd54ab2019-05-15 20:22:21 +00004648 // Refuse to compute a dynamic type in the presence of virtual bases. This
4649 // shouldn't happen other than in constant-folding situations, since literal
4650 // types can't have virtual bases.
4651 //
4652 // Note that consumers of DynamicType assume that the type has no virtual
4653 // bases, and will need modifications if this restriction is relaxed.
4654 const CXXRecordDecl *Class =
4655 This.Designator.MostDerivedType->getAsCXXRecordDecl();
4656 if (!Class || Class->getNumVBases()) {
4657 Info.FFDiag(E);
4658 return None;
4659 }
4660
Richard Smith921f1322019-05-13 23:35:21 +00004661 // FIXME: For very deep class hierarchies, it might be beneficial to use a
4662 // binary search here instead. But the overwhelmingly common case is that
4663 // we're not in the middle of a constructor, so it probably doesn't matter
4664 // in practice.
4665 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4666 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4667 PathLength <= Path.size(); ++PathLength) {
4668 switch (Info.isEvaluatingConstructor(This.getLValueBase(),
4669 Path.slice(0, PathLength))) {
4670 case ConstructionPhase::Bases:
4671 // We're constructing a base class. This is not the dynamic type.
4672 break;
4673
4674 case ConstructionPhase::None:
4675 case ConstructionPhase::AfterBases:
4676 // We've finished constructing the base classes, so this is the dynamic
4677 // type.
4678 return DynamicType{getBaseClassType(This.Designator, PathLength),
4679 PathLength};
4680 }
4681 }
4682
4683 // CWG issue 1517: we're constructing a base class of the object described by
4684 // 'This', so that object has not yet begun its period of construction and
4685 // any polymorphic operation on it results in undefined behavior.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004686 Info.FFDiag(E);
Richard Smith921f1322019-05-13 23:35:21 +00004687 return None;
4688}
4689
4690/// Perform virtual dispatch.
4691static const CXXMethodDecl *HandleVirtualDispatch(
4692 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4693 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004694 Optional<DynamicType> DynType =
4695 ComputeDynamicType(Info, E, This, AK_MemberCall);
4696 if (!DynType)
Richard Smith921f1322019-05-13 23:35:21 +00004697 return nullptr;
Richard Smith921f1322019-05-13 23:35:21 +00004698
4699 // Find the final overrider. It must be declared in one of the classes on the
4700 // path from the dynamic type to the static type.
4701 // FIXME: If we ever allow literal types to have virtual base classes, that
4702 // won't be true.
4703 const CXXMethodDecl *Callee = Found;
4704 unsigned PathLength = DynType->PathLength;
4705 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4706 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
Richard Smith921f1322019-05-13 23:35:21 +00004707 const CXXMethodDecl *Overrider =
4708 Found->getCorrespondingMethodDeclaredInClass(Class, false);
4709 if (Overrider) {
4710 Callee = Overrider;
4711 break;
4712 }
4713 }
4714
4715 // C++2a [class.abstract]p6:
4716 // the effect of making a virtual call to a pure virtual function [...] is
4717 // undefined
4718 if (Callee->isPure()) {
4719 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4720 Info.Note(Callee->getLocation(), diag::note_declared_at);
4721 return nullptr;
4722 }
4723
4724 // If necessary, walk the rest of the path to determine the sequence of
4725 // covariant adjustment steps to apply.
4726 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4727 Found->getReturnType())) {
4728 CovariantAdjustmentPath.push_back(Callee->getReturnType());
4729 for (unsigned CovariantPathLength = PathLength + 1;
4730 CovariantPathLength != This.Designator.Entries.size();
4731 ++CovariantPathLength) {
4732 const CXXRecordDecl *NextClass =
4733 getBaseClassType(This.Designator, CovariantPathLength);
4734 const CXXMethodDecl *Next =
4735 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4736 if (Next && !Info.Ctx.hasSameUnqualifiedType(
4737 Next->getReturnType(), CovariantAdjustmentPath.back()))
4738 CovariantAdjustmentPath.push_back(Next->getReturnType());
4739 }
4740 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4741 CovariantAdjustmentPath.back()))
4742 CovariantAdjustmentPath.push_back(Found->getReturnType());
4743 }
4744
4745 // Perform 'this' adjustment.
4746 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4747 return nullptr;
4748
4749 return Callee;
4750}
4751
4752/// Perform the adjustment from a value returned by a virtual function to
4753/// a value of the statically expected type, which may be a pointer or
4754/// reference to a base class of the returned type.
4755static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4756 APValue &Result,
4757 ArrayRef<QualType> Path) {
4758 assert(Result.isLValue() &&
4759 "unexpected kind of APValue for covariant return");
4760 if (Result.isNullPointer())
4761 return true;
4762
4763 LValue LVal;
4764 LVal.setFrom(Info.Ctx, Result);
4765
4766 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4767 for (unsigned I = 1; I != Path.size(); ++I) {
4768 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4769 assert(OldClass && NewClass && "unexpected kind of covariant return");
4770 if (OldClass != NewClass &&
4771 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4772 return false;
4773 OldClass = NewClass;
4774 }
4775
4776 LVal.moveInto(Result);
4777 return true;
4778}
4779
Richard Smith7bd54ab2019-05-15 20:22:21 +00004780/// Determine whether \p Base, which is known to be a direct base class of
4781/// \p Derived, is a public base class.
4782static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4783 const CXXRecordDecl *Base) {
4784 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4785 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4786 if (BaseClass && declaresSameEntity(BaseClass, Base))
4787 return BaseSpec.getAccessSpecifier() == AS_public;
4788 }
4789 llvm_unreachable("Base is not a direct base of Derived");
4790}
4791
4792/// Apply the given dynamic cast operation on the provided lvalue.
4793///
4794/// This implements the hard case of dynamic_cast, requiring a "runtime check"
4795/// to find a suitable target subobject.
4796static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4797 LValue &Ptr) {
4798 // We can't do anything with a non-symbolic pointer value.
4799 SubobjectDesignator &D = Ptr.Designator;
4800 if (D.Invalid)
4801 return false;
4802
4803 // C++ [expr.dynamic.cast]p6:
4804 // If v is a null pointer value, the result is a null pointer value.
4805 if (Ptr.isNullPointer() && !E->isGLValue())
4806 return true;
4807
4808 // For all the other cases, we need the pointer to point to an object within
4809 // its lifetime / period of construction / destruction, and we need to know
4810 // its dynamic type.
4811 Optional<DynamicType> DynType =
4812 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4813 if (!DynType)
4814 return false;
4815
4816 // C++ [expr.dynamic.cast]p7:
4817 // If T is "pointer to cv void", then the result is a pointer to the most
4818 // derived object
4819 if (E->getType()->isVoidPointerType())
4820 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4821
4822 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
4823 assert(C && "dynamic_cast target is not void pointer nor class");
4824 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4825
4826 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4827 // C++ [expr.dynamic.cast]p9:
4828 if (!E->isGLValue()) {
4829 // The value of a failed cast to pointer type is the null pointer value
4830 // of the required result type.
4831 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4832 Ptr.setNull(E->getType(), TargetVal);
4833 return true;
4834 }
4835
4836 // A failed cast to reference type throws [...] std::bad_cast.
4837 unsigned DiagKind;
4838 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4839 DynType->Type->isDerivedFrom(C)))
4840 DiagKind = 0;
4841 else if (!Paths || Paths->begin() == Paths->end())
4842 DiagKind = 1;
4843 else if (Paths->isAmbiguous(CQT))
4844 DiagKind = 2;
4845 else {
4846 assert(Paths->front().Access != AS_public && "why did the cast fail?");
4847 DiagKind = 3;
4848 }
4849 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4850 << DiagKind << Ptr.Designator.getType(Info.Ctx)
4851 << Info.Ctx.getRecordType(DynType->Type)
4852 << E->getType().getUnqualifiedType();
4853 return false;
4854 };
4855
4856 // Runtime check, phase 1:
4857 // Walk from the base subobject towards the derived object looking for the
4858 // target type.
4859 for (int PathLength = Ptr.Designator.Entries.size();
4860 PathLength >= (int)DynType->PathLength; --PathLength) {
4861 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4862 if (declaresSameEntity(Class, C))
4863 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4864 // We can only walk across public inheritance edges.
4865 if (PathLength > (int)DynType->PathLength &&
4866 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4867 Class))
4868 return RuntimeCheckFailed(nullptr);
4869 }
4870
4871 // Runtime check, phase 2:
4872 // Search the dynamic type for an unambiguous public base of type C.
4873 CXXBasePaths Paths(/*FindAmbiguities=*/true,
4874 /*RecordPaths=*/true, /*DetectVirtual=*/false);
4875 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4876 Paths.front().Access == AS_public) {
4877 // Downcast to the dynamic type...
4878 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4879 return false;
4880 // ... then upcast to the chosen base class subobject.
4881 for (CXXBasePathElement &Elem : Paths.front())
4882 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4883 return false;
4884 return true;
4885 }
4886
4887 // Otherwise, the runtime check fails.
4888 return RuntimeCheckFailed(&Paths);
4889}
4890
Richard Smithbe6dd812014-11-19 21:27:17 +00004891/// Determine if a class has any fields that might need to be copied by a
4892/// trivial copy or move operation.
4893static bool hasFields(const CXXRecordDecl *RD) {
4894 if (!RD || RD->isEmpty())
4895 return false;
4896 for (auto *FD : RD->fields()) {
4897 if (FD->isUnnamedBitfield())
4898 continue;
4899 return true;
4900 }
4901 for (auto &Base : RD->bases())
4902 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4903 return true;
4904 return false;
4905}
4906
Richard Smithd62306a2011-11-10 06:34:14 +00004907namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004908typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004909}
4910
4911/// EvaluateArgs - Evaluate the arguments to a function call.
4912static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4913 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004914 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004915 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004916 I != E; ++I) {
4917 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4918 // If we're checking for a potential constant expression, evaluate all
4919 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004920 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004921 return false;
4922 Success = false;
4923 }
4924 }
4925 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004926}
4927
Richard Smith254a73d2011-10-28 22:34:42 +00004928/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004929static bool HandleFunctionCall(SourceLocation CallLoc,
4930 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004931 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004932 EvalInfo &Info, APValue &Result,
4933 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004934 ArgVector ArgValues(Args.size());
4935 if (!EvaluateArgs(Args, ArgValues, Info))
4936 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004937
Richard Smith253c2a32012-01-27 01:14:48 +00004938 if (!Info.CheckCallLimit(CallLoc))
4939 return false;
4940
4941 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004942
4943 // For a trivial copy or move assignment, perform an APValue copy. This is
4944 // essential for unions, where the operations performed by the assignment
4945 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004946 //
4947 // Skip this for non-union classes with no fields; in that case, the defaulted
4948 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004949 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004950 if (MD && MD->isDefaulted() &&
4951 (MD->getParent()->isUnion() ||
4952 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004953 assert(This &&
4954 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4955 LValue RHS;
4956 RHS.setFrom(Info.Ctx, ArgValues[0]);
4957 APValue RHSValue;
4958 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4959 RHS, RHSValue))
4960 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00004961 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00004962 RHSValue))
4963 return false;
4964 This->moveInto(Result);
4965 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004966 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00004967 // We're in a lambda; determine the lambda capture field maps unless we're
4968 // just constexpr checking a lambda's call operator. constexpr checking is
4969 // done before the captures have been added to the closure object (unless
4970 // we're inferring constexpr-ness), so we don't have access to them in this
4971 // case. But since we don't need the captures to constexpr check, we can
4972 // just ignore them.
4973 if (!Info.checkingPotentialConstantExpression())
4974 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4975 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004976 }
4977
Richard Smith52a980a2015-08-28 02:43:42 +00004978 StmtResult Ret = {Result, ResultSlot};
4979 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004980 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004981 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004982 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004983 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004984 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004985 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004986}
4987
Richard Smithd62306a2011-11-10 06:34:14 +00004988/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004989static bool HandleConstructorCall(const Expr *E, const LValue &This,
4990 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004991 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004992 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004993 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004994 if (!Info.CheckCallLimit(CallLoc))
4995 return false;
4996
Richard Smith3607ffe2012-02-13 03:54:03 +00004997 const CXXRecordDecl *RD = Definition->getParent();
4998 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004999 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00005000 return false;
5001 }
5002
Erik Pilkington42925492017-10-04 00:18:55 +00005003 EvalInfo::EvaluatingConstructorRAII EvalObj(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005004 Info,
5005 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5006 RD->getNumBases());
Richard Smith5179eb72016-06-28 19:03:57 +00005007 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00005008
Richard Smith52a980a2015-08-28 02:43:42 +00005009 // FIXME: Creating an APValue just to hold a nonexistent return value is
5010 // wasteful.
5011 APValue RetVal;
5012 StmtResult Ret = {RetVal, nullptr};
5013
Richard Smith5179eb72016-06-28 19:03:57 +00005014 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00005015 if (Definition->isDelegatingConstructor()) {
5016 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00005017 {
5018 FullExpressionRAII InitScope(Info);
5019 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
5020 return false;
5021 }
Richard Smith52a980a2015-08-28 02:43:42 +00005022 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005023 }
5024
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005025 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00005026 // essential for unions (or classes with anonymous union members), where the
5027 // operations performed by the constructor cannot be represented by
5028 // ctor-initializers.
5029 //
5030 // Skip this for empty non-union classes; we should not perform an
5031 // lvalue-to-rvalue conversion on them because their copy constructor does not
5032 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00005033 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00005034 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00005035 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005036 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00005037 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00005038 return handleLValueToRValueConversion(
5039 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5040 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005041 }
5042
5043 // Reserve space for the struct members.
Richard Smithe637cbe2019-05-21 23:15:18 +00005044 if (!RD->isUnion() && !Result.hasValue())
Richard Smithd62306a2011-11-10 06:34:14 +00005045 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005046 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005047
John McCalld7bca762012-05-01 00:38:49 +00005048 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005049 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5050
Richard Smith08d6a2c2013-07-24 07:11:57 +00005051 // A scope for temporaries lifetime-extended by reference members.
5052 BlockScopeRAII LifetimeExtendedScope(Info);
5053
Richard Smith253c2a32012-01-27 01:14:48 +00005054 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005055 unsigned BasesSeen = 0;
5056#ifndef NDEBUG
5057 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5058#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005059 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005060 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005061 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00005062 APValue *Value = &Result;
5063
5064 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00005065 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005066 if (I->isBaseInitializer()) {
5067 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00005068#ifndef NDEBUG
5069 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00005070 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00005071 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5072 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5073 "base class initializers not in expected order");
5074 ++BaseIt;
5075#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005076 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00005077 BaseType->getAsCXXRecordDecl(), &Layout))
5078 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005079 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00005080 } else if ((FD = I->getMember())) {
5081 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005082 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005083 if (RD->isUnion()) {
5084 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00005085 Value = &Result.getUnionValue();
5086 } else {
5087 Value = &Result.getStructField(FD->getFieldIndex());
5088 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00005089 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005090 // Walk the indirect field decl's chain to find the object to initialize,
5091 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005092 auto IndirectFieldChain = IFD->chain();
5093 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00005094 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005095 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5096 // Switch the union field if it differs. This happens if we had
5097 // preceding zero-initialization, and we're now initializing a union
5098 // subobject other than the first.
5099 // FIXME: In this case, the values of the other subobjects are
5100 // specified, since zero-initialization sets all padding bits to zero.
Richard Smithe637cbe2019-05-21 23:15:18 +00005101 if (!Value->hasValue() ||
Richard Smith1b78b3d2012-01-25 22:15:11 +00005102 (Value->isUnion() && Value->getUnionField() != FD)) {
5103 if (CD->isUnion())
5104 *Value = APValue(FD);
5105 else
5106 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005107 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00005108 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005109 // Store Subobject as its parent before updating it for the last element
5110 // in the chain.
5111 if (C == IndirectFieldChain.back())
5112 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005113 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00005114 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005115 if (CD->isUnion())
5116 Value = &Value->getUnionValue();
5117 else
5118 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00005119 }
Richard Smithd62306a2011-11-10 06:34:14 +00005120 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005121 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00005122 }
Richard Smith253c2a32012-01-27 01:14:48 +00005123
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005124 // Need to override This for implicit field initializers as in this case
5125 // This refers to innermost anonymous struct/union containing initializer,
5126 // not to currently constructed class.
5127 const Expr *Init = I->getInit();
5128 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5129 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00005130 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005131 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5132 (FD && FD->isBitField() &&
5133 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005134 // If we're checking for a potential constant expression, evaluate all
5135 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005136 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005137 return false;
5138 Success = false;
5139 }
Richard Smith921f1322019-05-13 23:35:21 +00005140
5141 // This is the point at which the dynamic type of the object becomes this
5142 // class type.
5143 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5144 EvalObj.finishedConstructingBases();
Richard Smithd62306a2011-11-10 06:34:14 +00005145 }
5146
Richard Smithd9f663b2013-04-22 15:31:51 +00005147 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00005148 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005149}
5150
Richard Smith5179eb72016-06-28 19:03:57 +00005151static bool HandleConstructorCall(const Expr *E, const LValue &This,
5152 ArrayRef<const Expr*> Args,
5153 const CXXConstructorDecl *Definition,
5154 EvalInfo &Info, APValue &Result) {
5155 ArgVector ArgValues(Args.size());
5156 if (!EvaluateArgs(Args, ArgValues, Info))
5157 return false;
5158
5159 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5160 Info, Result);
5161}
5162
Eli Friedman9a156e52008-11-12 09:44:48 +00005163//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00005164// Generic Evaluation
5165//===----------------------------------------------------------------------===//
5166namespace {
5167
Aaron Ballman68af21c2014-01-03 19:26:43 +00005168template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00005169class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005170 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00005171private:
Richard Smith52a980a2015-08-28 02:43:42 +00005172 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005173 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005174 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005175 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005176 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005177 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005178 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005179
Richard Smith17100ba2012-02-16 02:46:34 +00005180 // Check whether a conditional operator with a non-constant condition is a
5181 // potential constant expression. If neither arm is a potential constant
5182 // expression, then the conditional operator is not either.
5183 template<typename ConditionalOperator>
5184 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005185 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00005186
5187 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00005188 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00005189 {
Richard Smith17100ba2012-02-16 02:46:34 +00005190 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00005191 StmtVisitorTy::Visit(E->getFalseExpr());
5192 if (Diag.empty())
5193 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00005194 }
Richard Smith17100ba2012-02-16 02:46:34 +00005195
George Burgess IV8c892b52016-05-25 22:31:54 +00005196 {
5197 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00005198 Diag.clear();
5199 StmtVisitorTy::Visit(E->getTrueExpr());
5200 if (Diag.empty())
5201 return;
5202 }
5203
5204 Error(E, diag::note_constexpr_conditional_never_const);
5205 }
5206
5207
5208 template<typename ConditionalOperator>
5209 bool HandleConditionalOperator(const ConditionalOperator *E) {
5210 bool BoolResult;
5211 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00005212 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00005213 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00005214 return false;
5215 }
5216 if (Info.noteFailure()) {
5217 StmtVisitorTy::Visit(E->getTrueExpr());
5218 StmtVisitorTy::Visit(E->getFalseExpr());
5219 }
Richard Smith17100ba2012-02-16 02:46:34 +00005220 return false;
5221 }
5222
5223 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
5224 return StmtVisitorTy::Visit(EvalExpr);
5225 }
5226
Peter Collingbournee9200682011-05-13 03:29:01 +00005227protected:
5228 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005229 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00005230 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
5231
Richard Smith92b1ce02011-12-12 09:28:41 +00005232 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005233 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005234 }
5235
Aaron Ballman68af21c2014-01-03 19:26:43 +00005236 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005237
5238public:
5239 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
5240
5241 EvalInfo &getEvalInfo() { return Info; }
5242
Richard Smithf57d8cb2011-12-09 22:58:01 +00005243 /// Report an evaluation error. This should only be called when an error is
5244 /// first discovered. When propagating an error, just return false.
5245 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005246 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005247 return false;
5248 }
5249 bool Error(const Expr *E) {
5250 return Error(E, diag::note_invalid_subexpr_in_const_expr);
5251 }
5252
Aaron Ballman68af21c2014-01-03 19:26:43 +00005253 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00005254 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00005255 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005256 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005257 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005258 }
5259
Bill Wendling8003edc2018-11-09 00:41:36 +00005260 bool VisitConstantExpr(const ConstantExpr *E)
5261 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005262 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005263 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005264 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005265 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005266 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005267 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005268 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00005269 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005270 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005271 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005272 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00005273 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005274 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
5275 TempVersionRAII RAII(*Info.CurrentCall);
Eric Fiselier708afb52019-05-16 21:04:15 +00005276 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005277 return StmtVisitorTy::Visit(E->getExpr());
5278 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005279 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005280 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00005281 // The initializer may not have been parsed yet, or might be erroneous.
5282 if (!E->getExpr())
5283 return Error(E);
Eric Fiselier708afb52019-05-16 21:04:15 +00005284 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Richard Smith17e32462013-09-13 20:51:45 +00005285 return StmtVisitorTy::Visit(E->getExpr());
5286 }
Eric Fiselier708afb52019-05-16 21:04:15 +00005287
Richard Smith5894a912011-12-19 22:12:41 +00005288 // We cannot create any objects for which cleanups are required, so there is
5289 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00005290 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00005291 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005292
Aaron Ballman68af21c2014-01-03 19:26:43 +00005293 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005294 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
5295 return static_cast<Derived*>(this)->VisitCastExpr(E);
5296 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005297 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00005298 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
5299 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005300 return static_cast<Derived*>(this)->VisitCastExpr(E);
5301 }
5302
Aaron Ballman68af21c2014-01-03 19:26:43 +00005303 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005304 switch (E->getOpcode()) {
5305 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005306 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005307
5308 case BO_Comma:
5309 VisitIgnoredValue(E->getLHS());
5310 return StmtVisitorTy::Visit(E->getRHS());
5311
5312 case BO_PtrMemD:
5313 case BO_PtrMemI: {
5314 LValue Obj;
5315 if (!HandleMemberPointerAccess(Info, E, Obj))
5316 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005317 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00005318 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005319 return false;
5320 return DerivedSuccess(Result, E);
5321 }
5322 }
5323 }
5324
Aaron Ballman68af21c2014-01-03 19:26:43 +00005325 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00005326 // Evaluate and cache the common expression. We treat it as a temporary,
5327 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00005328 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00005329 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005330 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00005331
Richard Smith17100ba2012-02-16 02:46:34 +00005332 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005333 }
5334
Aaron Ballman68af21c2014-01-03 19:26:43 +00005335 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005336 bool IsBcpCall = false;
5337 // If the condition (ignoring parens) is a __builtin_constant_p call,
5338 // the result is a constant expression if it can be folded without
5339 // side-effects. This is an important GNU extension. See GCC PR38377
5340 // for discussion.
5341 if (const CallExpr *CallCE =
5342 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00005343 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00005344 IsBcpCall = true;
5345
5346 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
5347 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00005348 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00005349 return false;
5350
Richard Smith6d4c6582013-11-05 22:18:15 +00005351 FoldConstant Fold(Info, IsBcpCall);
5352 if (!HandleConditionalOperator(E)) {
5353 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00005354 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00005355 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00005356
5357 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00005358 }
5359
Aaron Ballman68af21c2014-01-03 19:26:43 +00005360 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005361 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00005362 return DerivedSuccess(*Value, E);
5363
5364 const Expr *Source = E->getSourceExpr();
5365 if (!Source)
5366 return Error(E);
5367 if (Source == E) { // sanity checking.
5368 assert(0 && "OpaqueValueExpr recursively refers to itself");
5369 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00005370 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00005371 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00005372 }
Richard Smith4ce706a2011-10-11 21:43:33 +00005373
Aaron Ballman68af21c2014-01-03 19:26:43 +00005374 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005375 APValue Result;
5376 if (!handleCallExpr(E, Result, nullptr))
5377 return false;
5378 return DerivedSuccess(Result, E);
5379 }
5380
5381 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00005382 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00005383 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00005384 QualType CalleeType = Callee->getType();
5385
Craig Topper36250ad2014-05-12 05:36:57 +00005386 const FunctionDecl *FD = nullptr;
5387 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00005388 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith921f1322019-05-13 23:35:21 +00005389 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00005390
Richard Smithe97cbd72011-11-11 04:05:33 +00005391 // Extract function decl and 'this' pointer from the callee.
5392 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smith921f1322019-05-13 23:35:21 +00005393 const CXXMethodDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005394 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
5395 // Explicit bound member calls, such as x.f() or p->g();
5396 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005397 return false;
Richard Smith921f1322019-05-13 23:35:21 +00005398 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
5399 if (!Member)
5400 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00005401 This = &ThisVal;
Richard Smith921f1322019-05-13 23:35:21 +00005402 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00005403 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
5404 // Indirect bound member calls ('.*' or '->*').
Richard Smith921f1322019-05-13 23:35:21 +00005405 Member = dyn_cast_or_null<CXXMethodDecl>(
5406 HandleMemberPointerAccess(Info, BE, ThisVal, false));
5407 if (!Member)
5408 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00005409 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00005410 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00005411 return Error(Callee);
Richard Smith921f1322019-05-13 23:35:21 +00005412 FD = Member;
Richard Smithe97cbd72011-11-11 04:05:33 +00005413 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00005414 LValue Call;
5415 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005416 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00005417
Richard Smitha8105bc2012-01-06 16:39:00 +00005418 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005419 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00005420 FD = dyn_cast_or_null<FunctionDecl>(
5421 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00005422 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005423 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00005424 // Don't call function pointers which have been cast to some other type.
5425 // Per DR (no number yet), the caller and callee can differ in noexcept.
5426 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
5427 CalleeType->getPointeeType(), FD->getType())) {
5428 return Error(E);
5429 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005430
5431 // Overloaded operator calls to member functions are represented as normal
5432 // calls with '*this' as the first argument.
5433 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
5434 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005435 // FIXME: When selecting an implicit conversion for an overloaded
5436 // operator delete, we sometimes try to evaluate calls to conversion
5437 // operators without a 'this' parameter!
5438 if (Args.empty())
5439 return Error(E);
5440
Nick Lewycky13073a62017-06-12 21:15:44 +00005441 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00005442 return false;
5443 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00005444 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00005445 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00005446 // Map the static invoker for the lambda back to the call operator.
5447 // Conveniently, we don't have to slice out the 'this' argument (as is
5448 // being done for the non-static case), since a static member function
5449 // doesn't have an implicit argument passed in.
5450 const CXXRecordDecl *ClosureClass = MD->getParent();
5451 assert(
5452 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
5453 "Number of captures must be zero for conversion to function-ptr");
5454
5455 const CXXMethodDecl *LambdaCallOp =
5456 ClosureClass->getLambdaCallOperator();
5457
5458 // Set 'FD', the function that will be called below, to the call
5459 // operator. If the closure object represents a generic lambda, find
5460 // the corresponding specialization of the call operator.
5461
5462 if (ClosureClass->isGenericLambda()) {
5463 assert(MD->isFunctionTemplateSpecialization() &&
5464 "A generic lambda's static-invoker function must be a "
5465 "template specialization");
5466 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
5467 FunctionTemplateDecl *CallOpTemplate =
5468 LambdaCallOp->getDescribedFunctionTemplate();
5469 void *InsertPos = nullptr;
5470 FunctionDecl *CorrespondingCallOpSpecialization =
5471 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
5472 assert(CorrespondingCallOpSpecialization &&
5473 "We must always have a function call operator specialization "
5474 "that corresponds to our static invoker specialization");
5475 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
5476 } else
5477 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00005478 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005479 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00005480 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00005481
Richard Smith921f1322019-05-13 23:35:21 +00005482 SmallVector<QualType, 4> CovariantAdjustmentPath;
5483 if (This) {
5484 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
Richard Smith7bd54ab2019-05-15 20:22:21 +00005485 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
5486 // Perform virtual dispatch, if necessary.
5487 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
5488 CovariantAdjustmentPath);
5489 if (!FD)
5490 return false;
5491 } else {
5492 // Check that the 'this' pointer points to an object of the right type.
5493 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
5494 return false;
5495 }
Richard Smith921f1322019-05-13 23:35:21 +00005496 }
Richard Smith47b34932012-02-01 02:39:43 +00005497
Craig Topper36250ad2014-05-12 05:36:57 +00005498 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00005499 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00005500
Nick Lewycky13073a62017-06-12 21:15:44 +00005501 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
5502 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00005503 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005504 return false;
5505
Richard Smith921f1322019-05-13 23:35:21 +00005506 if (!CovariantAdjustmentPath.empty() &&
5507 !HandleCovariantReturnAdjustment(Info, E, Result,
5508 CovariantAdjustmentPath))
5509 return false;
5510
Richard Smith52a980a2015-08-28 02:43:42 +00005511 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00005512 }
5513
Aaron Ballman68af21c2014-01-03 19:26:43 +00005514 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005515 return StmtVisitorTy::Visit(E->getInitializer());
5516 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005517 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00005518 if (E->getNumInits() == 0)
5519 return DerivedZeroInitialization(E);
5520 if (E->getNumInits() == 1)
5521 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00005522 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005523 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005524 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005525 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005526 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005527 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005528 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005529 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005530 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005531 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005532 }
Richard Smith4ce706a2011-10-11 21:43:33 +00005533
Richard Smithd62306a2011-11-10 06:34:14 +00005534 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00005535 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005536 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
5537 "missing temporary materialization conversion");
Richard Smithd62306a2011-11-10 06:34:14 +00005538 assert(!E->isArrow() && "missing call to bound member function?");
5539
Richard Smith2e312c82012-03-03 22:46:17 +00005540 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00005541 if (!Evaluate(Val, Info, E->getBase()))
5542 return false;
5543
5544 QualType BaseTy = E->getBase()->getType();
5545
5546 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00005547 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005548 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00005549 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00005550 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5551
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005552 // Note: there is no lvalue base here. But this case should only ever
5553 // happen in C or in C++98, where we cannot be evaluating a constexpr
5554 // constructor, which is the only case the base matters.
Richard Smithdebad642019-05-12 09:39:08 +00005555 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00005556 SubobjectDesignator Designator(BaseTy);
5557 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00005558
Richard Smith3229b742013-05-05 21:17:10 +00005559 APValue Result;
5560 return extractSubobject(Info, E, Obj, Designator, Result) &&
5561 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00005562 }
5563
Aaron Ballman68af21c2014-01-03 19:26:43 +00005564 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005565 switch (E->getCastKind()) {
5566 default:
5567 break;
5568
Richard Smitha23ab512013-05-23 00:30:41 +00005569 case CK_AtomicToNonAtomic: {
5570 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00005571 // This does not need to be done in place even for class/array types:
5572 // atomic-to-non-atomic conversion implies copying the object
5573 // representation.
5574 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00005575 return false;
5576 return DerivedSuccess(AtomicVal, E);
5577 }
5578
Richard Smith11562c52011-10-28 17:51:58 +00005579 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00005580 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00005581 return StmtVisitorTy::Visit(E->getSubExpr());
5582
5583 case CK_LValueToRValue: {
5584 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005585 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5586 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005587 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00005588 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00005589 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00005590 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005591 return false;
5592 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00005593 }
5594 }
5595
Richard Smithf57d8cb2011-12-09 22:58:01 +00005596 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005597 }
5598
Aaron Ballman68af21c2014-01-03 19:26:43 +00005599 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005600 return VisitUnaryPostIncDec(UO);
5601 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005602 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005603 return VisitUnaryPostIncDec(UO);
5604 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005605 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005606 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005607 return Error(UO);
5608
5609 LValue LVal;
5610 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5611 return false;
5612 APValue RVal;
5613 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5614 UO->isIncrementOp(), &RVal))
5615 return false;
5616 return DerivedSuccess(RVal, UO);
5617 }
5618
Aaron Ballman68af21c2014-01-03 19:26:43 +00005619 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00005620 // We will have checked the full-expressions inside the statement expression
5621 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00005622 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00005623 return Error(E);
5624
Richard Smith08d6a2c2013-07-24 07:11:57 +00005625 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00005626 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005627 if (CS->body_empty())
5628 return true;
5629
Richard Smith51f03172013-06-20 03:00:05 +00005630 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5631 BE = CS->body_end();
5632 /**/; ++BI) {
5633 if (BI + 1 == BE) {
5634 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5635 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005636 Info.FFDiag((*BI)->getBeginLoc(),
5637 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005638 return false;
5639 }
5640 return this->Visit(FinalExpr);
5641 }
5642
5643 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00005644 StmtResult Result = { ReturnValue, nullptr };
5645 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00005646 if (ESR != ESR_Succeeded) {
5647 // FIXME: If the statement-expression terminated due to 'return',
5648 // 'break', or 'continue', it would be nice to propagate that to
5649 // the outer statement evaluation rather than bailing out.
5650 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005651 Info.FFDiag((*BI)->getBeginLoc(),
5652 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005653 return false;
5654 }
5655 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005656
5657 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00005658 }
5659
Richard Smith4a678122011-10-24 18:44:57 +00005660 /// Visit a value which is evaluated, but whose value is ignored.
5661 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00005662 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00005663 }
David Majnemere9807b22016-02-26 04:23:19 +00005664
5665 /// Potentially visit a MemberExpr's base expression.
5666 void VisitIgnoredBaseExpression(const Expr *E) {
5667 // While MSVC doesn't evaluate the base expression, it does diagnose the
5668 // presence of side-effecting behavior.
5669 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5670 return;
5671 VisitIgnoredValue(E);
5672 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005673};
5674
Eric Fiselier0683c0e2018-05-07 21:07:10 +00005675} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00005676
5677//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005678// Common base class for lvalue and temporary evaluation.
5679//===----------------------------------------------------------------------===//
5680namespace {
5681template<class Derived>
5682class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005683 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00005684protected:
5685 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005686 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005687 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005688 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005689
5690 bool Success(APValue::LValueBase B) {
5691 Result.set(B);
5692 return true;
5693 }
5694
George Burgess IVf9013bf2017-02-10 22:52:29 +00005695 bool evaluatePointer(const Expr *E, LValue &Result) {
5696 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5697 }
5698
Richard Smith027bf112011-11-17 22:56:20 +00005699public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005700 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5701 : ExprEvaluatorBaseTy(Info), Result(Result),
5702 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005703
Richard Smith2e312c82012-03-03 22:46:17 +00005704 bool Success(const APValue &V, const Expr *E) {
5705 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005706 return true;
5707 }
Richard Smith027bf112011-11-17 22:56:20 +00005708
Richard Smith027bf112011-11-17 22:56:20 +00005709 bool VisitMemberExpr(const MemberExpr *E) {
5710 // Handle non-static data members.
5711 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005712 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005713 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005714 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005715 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005716 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005717 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005718 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005719 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005720 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005721 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005722 BaseTy = E->getBase()->getType();
5723 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005724 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005725 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005726 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005727 Result.setInvalid(E);
5728 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005729 }
Richard Smith027bf112011-11-17 22:56:20 +00005730
Richard Smith1b78b3d2012-01-25 22:15:11 +00005731 const ValueDecl *MD = E->getMemberDecl();
5732 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5733 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5734 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5735 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005736 if (!HandleLValueMember(this->Info, E, Result, FD))
5737 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005738 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005739 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5740 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005741 } else
5742 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005743
Richard Smith1b78b3d2012-01-25 22:15:11 +00005744 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005745 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005746 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005747 RefValue))
5748 return false;
5749 return Success(RefValue, E);
5750 }
5751 return true;
5752 }
5753
5754 bool VisitBinaryOperator(const BinaryOperator *E) {
5755 switch (E->getOpcode()) {
5756 default:
5757 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5758
5759 case BO_PtrMemD:
5760 case BO_PtrMemI:
5761 return HandleMemberPointerAccess(this->Info, E, Result);
5762 }
5763 }
5764
5765 bool VisitCastExpr(const CastExpr *E) {
5766 switch (E->getCastKind()) {
5767 default:
5768 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5769
5770 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005771 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005772 if (!this->Visit(E->getSubExpr()))
5773 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005774
5775 // Now figure out the necessary offset to add to the base LV to get from
5776 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005777 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5778 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005779 }
5780 }
5781};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005782}
Richard Smith027bf112011-11-17 22:56:20 +00005783
5784//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005785// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005786//
5787// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5788// function designators (in C), decl references to void objects (in C), and
5789// temporaries (if building with -Wno-address-of-temporary).
5790//
5791// LValue evaluation produces values comprising a base expression of one of the
5792// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005793// - Declarations
5794// * VarDecl
5795// * FunctionDecl
5796// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005797// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005798// * StringLiteral
5799// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005800// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005801// * ObjCEncodeExpr
5802// * AddrLabelExpr
5803// * BlockExpr
5804// * CallExpr for a MakeStringConstant builtin
Richard Smithee0ce3022019-05-17 07:06:46 +00005805// - typeid(T) expressions, as TypeInfoLValues
Richard Smithce40ad62011-11-12 22:28:03 +00005806// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005807// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005808// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005809// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5810// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005811// * A MaterializeTemporaryExpr that has static storage duration, with no
5812// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005813// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005814//===----------------------------------------------------------------------===//
5815namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005816class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005817 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005818public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005819 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5820 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005821
Richard Smith11562c52011-10-28 17:51:58 +00005822 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005823 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005824
Peter Collingbournee9200682011-05-13 03:29:01 +00005825 bool VisitDeclRefExpr(const DeclRefExpr *E);
5826 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005827 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005828 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5829 bool VisitMemberExpr(const MemberExpr *E);
5830 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5831 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005832 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005833 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005834 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5835 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005836 bool VisitUnaryReal(const UnaryOperator *E);
5837 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005838 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5839 return VisitUnaryPreIncDec(UO);
5840 }
5841 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5842 return VisitUnaryPreIncDec(UO);
5843 }
Richard Smith3229b742013-05-05 21:17:10 +00005844 bool VisitBinAssign(const BinaryOperator *BO);
5845 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005846
Peter Collingbournee9200682011-05-13 03:29:01 +00005847 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005848 switch (E->getCastKind()) {
5849 default:
Richard Smith027bf112011-11-17 22:56:20 +00005850 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005851
Eli Friedmance3e02a2011-10-11 00:13:24 +00005852 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005853 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005854 if (!Visit(E->getSubExpr()))
5855 return false;
5856 Result.Designator.setInvalid();
5857 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005858
Richard Smith027bf112011-11-17 22:56:20 +00005859 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005860 if (!Visit(E->getSubExpr()))
5861 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005862 return HandleBaseToDerivedCast(Info, E, Result);
Richard Smith7bd54ab2019-05-15 20:22:21 +00005863
5864 case CK_Dynamic:
5865 if (!Visit(E->getSubExpr()))
5866 return false;
5867 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005868 }
5869 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005870};
5871} // end anonymous namespace
5872
Richard Smith11562c52011-10-28 17:51:58 +00005873/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005874/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005875/// * function designators in C, and
5876/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005877/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005878static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5879 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005880 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005881 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005882 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005883}
5884
Peter Collingbournee9200682011-05-13 03:29:01 +00005885bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005886 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005887 return Success(FD);
5888 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005889 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005890 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005891 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005892 return Error(E);
5893}
Richard Smith733237d2011-10-24 23:14:33 +00005894
Faisal Vali0528a312016-11-13 06:09:16 +00005895
Richard Smith11562c52011-10-28 17:51:58 +00005896bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005897
5898 // If we are within a lambda's call operator, check whether the 'VD' referred
5899 // to within 'E' actually represents a lambda-capture that maps to a
5900 // data-member/field within the closure object, and if so, evaluate to the
5901 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00005902 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5903 isa<DeclRefExpr>(E) &&
5904 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5905 // We don't always have a complete capture-map when checking or inferring if
5906 // the function call operator meets the requirements of a constexpr function
5907 // - but we don't need to evaluate the captures to determine constexprness
5908 // (dcl.constexpr C++17).
5909 if (Info.checkingPotentialConstantExpression())
5910 return false;
5911
Faisal Vali051e3a22017-02-16 04:12:21 +00005912 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005913 // Start with 'Result' referring to the complete closure object...
5914 Result = *Info.CurrentCall->This;
5915 // ... then update it to refer to the field of the closure object
5916 // that represents the capture.
5917 if (!HandleLValueMember(Info, E, Result, FD))
5918 return false;
5919 // And if the field is of reference type, update 'Result' to refer to what
5920 // the field refers to.
5921 if (FD->getType()->isReferenceType()) {
5922 APValue RVal;
5923 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5924 RVal))
5925 return false;
5926 Result.setFrom(Info.Ctx, RVal);
5927 }
5928 return true;
5929 }
5930 }
Craig Topper36250ad2014-05-12 05:36:57 +00005931 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005932 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5933 // Only if a local variable was declared in the function currently being
5934 // evaluated, do we expect to be able to find its value in the current
5935 // frame. (Otherwise it was likely declared in an enclosing context and
5936 // could either have a valid evaluatable value (for e.g. a constexpr
5937 // variable) or be ill-formed (and trigger an appropriate evaluation
5938 // diagnostic)).
5939 if (Info.CurrentCall->Callee &&
5940 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5941 Frame = Info.CurrentCall;
5942 }
5943 }
Richard Smith3229b742013-05-05 21:17:10 +00005944
Richard Smithfec09922011-11-01 16:57:24 +00005945 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005946 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005947 Result.set({VD, Frame->Index,
5948 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00005949 return true;
5950 }
Richard Smithce40ad62011-11-12 22:28:03 +00005951 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005952 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005953
Richard Smith3229b742013-05-05 21:17:10 +00005954 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005955 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005956 return false;
Richard Smithe637cbe2019-05-21 23:15:18 +00005957 if (!V->hasValue()) {
5958 // FIXME: Is it possible for V to be indeterminate here? If so, we should
5959 // adjust the diagnostic to say that.
Richard Smith6d4c6582013-11-05 22:18:15 +00005960 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005961 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005962 return false;
5963 }
Richard Smith3229b742013-05-05 21:17:10 +00005964 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005965}
5966
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005967bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5968 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005969 // Walk through the expression to find the materialized temporary itself.
5970 SmallVector<const Expr *, 2> CommaLHSs;
5971 SmallVector<SubobjectAdjustment, 2> Adjustments;
5972 const Expr *Inner = E->GetTemporaryExpr()->
5973 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005974
Richard Smith84401042013-06-03 05:03:02 +00005975 // If we passed any comma operators, evaluate their LHSs.
5976 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5977 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5978 return false;
5979
Richard Smithe6c01442013-06-05 00:46:14 +00005980 // A materialized temporary with static storage duration can appear within the
5981 // result of a constant expression evaluation, so we need to preserve its
5982 // value for use outside this evaluation.
5983 APValue *Value;
5984 if (E->getStorageDuration() == SD_Static) {
5985 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005986 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005987 Result.set(E);
5988 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005989 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5990 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00005991 }
5992
Richard Smithea4ad5d2013-06-06 08:19:16 +00005993 QualType Type = Inner->getType();
5994
Richard Smith84401042013-06-03 05:03:02 +00005995 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005996 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5997 (E->getStorageDuration() == SD_Static &&
5998 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5999 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00006000 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00006001 }
Richard Smith84401042013-06-03 05:03:02 +00006002
6003 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00006004 for (unsigned I = Adjustments.size(); I != 0; /**/) {
6005 --I;
6006 switch (Adjustments[I].Kind) {
6007 case SubobjectAdjustment::DerivedToBaseAdjustment:
6008 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6009 Type, Result))
6010 return false;
6011 Type = Adjustments[I].DerivedToBase.BasePath->getType();
6012 break;
6013
6014 case SubobjectAdjustment::FieldAdjustment:
6015 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6016 return false;
6017 Type = Adjustments[I].Field->getType();
6018 break;
6019
6020 case SubobjectAdjustment::MemberPointerAdjustment:
6021 if (!HandleMemberPointerAccess(this->Info, Type, Result,
6022 Adjustments[I].Ptr.RHS))
6023 return false;
6024 Type = Adjustments[I].Ptr.MPT->getPointeeType();
6025 break;
6026 }
6027 }
6028
6029 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006030}
6031
Peter Collingbournee9200682011-05-13 03:29:01 +00006032bool
6033LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00006034 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6035 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00006036 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6037 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00006038 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006039}
6040
Richard Smith6e525142011-12-27 12:18:28 +00006041bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smitha9330302019-05-17 19:19:28 +00006042 TypeInfoLValue TypeInfo;
6043
Richard Smithee0ce3022019-05-17 07:06:46 +00006044 if (!E->isPotentiallyEvaluated()) {
Richard Smithee0ce3022019-05-17 07:06:46 +00006045 if (E->isTypeOperand())
6046 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6047 else
6048 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
Richard Smitha9330302019-05-17 19:19:28 +00006049 } else {
6050 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
6051 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
6052 << E->getExprOperand()->getType()
6053 << E->getExprOperand()->getSourceRange();
6054 }
6055
6056 if (!Visit(E->getExprOperand()))
6057 return false;
6058
6059 Optional<DynamicType> DynType =
6060 ComputeDynamicType(Info, E, Result, AK_TypeId);
6061 if (!DynType)
6062 return false;
6063
6064 TypeInfo =
6065 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
Richard Smithee0ce3022019-05-17 07:06:46 +00006066 }
Richard Smith6f3d4352012-10-17 23:52:07 +00006067
Richard Smitha9330302019-05-17 19:19:28 +00006068 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
Richard Smith6e525142011-12-27 12:18:28 +00006069}
6070
Francois Pichet0066db92012-04-16 04:08:35 +00006071bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
6072 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00006073}
Francois Pichet0066db92012-04-16 04:08:35 +00006074
Peter Collingbournee9200682011-05-13 03:29:01 +00006075bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006076 // Handle static data members.
6077 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006078 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00006079 return VisitVarDecl(E, VD);
6080 }
6081
Richard Smith254a73d2011-10-28 22:34:42 +00006082 // Handle static member functions.
6083 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
6084 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00006085 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00006086 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00006087 }
6088 }
6089
Richard Smithd62306a2011-11-10 06:34:14 +00006090 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00006091 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006092}
6093
Peter Collingbournee9200682011-05-13 03:29:01 +00006094bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006095 // FIXME: Deal with vectors as array subscript bases.
6096 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006097 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00006098
Nick Lewyckyad888682017-04-27 07:27:36 +00006099 bool Success = true;
6100 if (!evaluatePointer(E->getBase(), Result)) {
6101 if (!Info.noteFailure())
6102 return false;
6103 Success = false;
6104 }
Mike Stump11289f42009-09-09 15:08:12 +00006105
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006106 APSInt Index;
6107 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00006108 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006109
Nick Lewyckyad888682017-04-27 07:27:36 +00006110 return Success &&
6111 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006112}
Eli Friedman9a156e52008-11-12 09:44:48 +00006113
Peter Collingbournee9200682011-05-13 03:29:01 +00006114bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006115 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00006116}
6117
Richard Smith66c96992012-02-18 22:04:06 +00006118bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6119 if (!Visit(E->getSubExpr()))
6120 return false;
6121 // __real is a no-op on scalar lvalues.
6122 if (E->getSubExpr()->getType()->isAnyComplexType())
6123 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
6124 return true;
6125}
6126
6127bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6128 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
6129 "lvalue __imag__ on scalar?");
6130 if (!Visit(E->getSubExpr()))
6131 return false;
6132 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
6133 return true;
6134}
6135
Richard Smith243ef902013-05-05 23:31:59 +00006136bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006137 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00006138 return Error(UO);
6139
6140 if (!this->Visit(UO->getSubExpr()))
6141 return false;
6142
Richard Smith243ef902013-05-05 23:31:59 +00006143 return handleIncDec(
6144 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00006145 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00006146}
6147
6148bool LValueExprEvaluator::VisitCompoundAssignOperator(
6149 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006150 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00006151 return Error(CAO);
6152
Richard Smith3229b742013-05-05 21:17:10 +00006153 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00006154
6155 // The overall lvalue result is the result of evaluating the LHS.
6156 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00006157 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006158 Evaluate(RHS, this->Info, CAO->getRHS());
6159 return false;
6160 }
6161
Richard Smith3229b742013-05-05 21:17:10 +00006162 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
6163 return false;
6164
Richard Smith43e77732013-05-07 04:50:00 +00006165 return handleCompoundAssignment(
6166 this->Info, CAO,
6167 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
6168 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00006169}
6170
6171bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006172 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006173 return Error(E);
6174
Richard Smith3229b742013-05-05 21:17:10 +00006175 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00006176
6177 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00006178 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006179 Evaluate(NewVal, this->Info, E->getRHS());
6180 return false;
6181 }
6182
Richard Smith3229b742013-05-05 21:17:10 +00006183 if (!Evaluate(NewVal, this->Info, E->getRHS()))
6184 return false;
Richard Smith243ef902013-05-05 23:31:59 +00006185
6186 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00006187 NewVal);
6188}
6189
Eli Friedman9a156e52008-11-12 09:44:48 +00006190//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006191// Pointer Evaluation
6192//===----------------------------------------------------------------------===//
6193
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006194/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00006195/// returned by a function with the alloc_size attribute. Returns true if we
6196/// were successful. Places an unsigned number into `Result`.
6197///
6198/// This expects the given CallExpr to be a call to a function with an
6199/// alloc_size attribute.
6200static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6201 const CallExpr *Call,
6202 llvm::APInt &Result) {
6203 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
6204
Joel E. Denny81508102018-03-13 14:51:22 +00006205 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
6206 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00006207 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
6208 if (Call->getNumArgs() <= SizeArgNo)
6209 return false;
6210
6211 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00006212 Expr::EvalResult ExprResult;
6213 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00006214 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006215 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00006216 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
6217 return false;
6218 Into = Into.zextOrSelf(BitsInSizeT);
6219 return true;
6220 };
6221
6222 APSInt SizeOfElem;
6223 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
6224 return false;
6225
Joel E. Denny81508102018-03-13 14:51:22 +00006226 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00006227 Result = std::move(SizeOfElem);
6228 return true;
6229 }
6230
6231 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00006232 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00006233 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
6234 return false;
6235
6236 bool Overflow;
6237 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
6238 if (Overflow)
6239 return false;
6240
6241 Result = std::move(BytesAvailable);
6242 return true;
6243}
6244
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006245/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00006246/// function.
6247static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6248 const LValue &LVal,
6249 llvm::APInt &Result) {
6250 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
6251 "Can't get the size of a non alloc_size function");
6252 const auto *Base = LVal.getLValueBase().get<const Expr *>();
6253 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
6254 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
6255}
6256
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006257/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00006258/// a function with the alloc_size attribute. If it was possible to do so, this
6259/// function will return true, make Result's Base point to said function call,
6260/// and mark Result's Base as invalid.
6261static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
6262 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006263 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00006264 return false;
6265
6266 // Because we do no form of static analysis, we only support const variables.
6267 //
6268 // Additionally, we can't support parameters, nor can we support static
6269 // variables (in the latter case, use-before-assign isn't UB; in the former,
6270 // we have no clue what they'll be assigned to).
6271 const auto *VD =
6272 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
6273 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
6274 return false;
6275
6276 const Expr *Init = VD->getAnyInitializer();
6277 if (!Init)
6278 return false;
6279
6280 const Expr *E = Init->IgnoreParens();
6281 if (!tryUnwrapAllocSizeCall(E))
6282 return false;
6283
6284 // Store E instead of E unwrapped so that the type of the LValue's base is
6285 // what the user wanted.
6286 Result.setInvalid(E);
6287
6288 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006289 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00006290 return true;
6291}
6292
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006293namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006294class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006295 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00006296 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006297 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00006298
Peter Collingbournee9200682011-05-13 03:29:01 +00006299 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00006300 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00006301 return true;
6302 }
George Burgess IVe3763372016-12-22 02:50:20 +00006303
George Burgess IVf9013bf2017-02-10 22:52:29 +00006304 bool evaluateLValue(const Expr *E, LValue &Result) {
6305 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
6306 }
6307
6308 bool evaluatePointer(const Expr *E, LValue &Result) {
6309 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
6310 }
6311
George Burgess IVe3763372016-12-22 02:50:20 +00006312 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006313public:
Mike Stump11289f42009-09-09 15:08:12 +00006314
George Burgess IVf9013bf2017-02-10 22:52:29 +00006315 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
6316 : ExprEvaluatorBaseTy(info), Result(Result),
6317 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006318
Richard Smith2e312c82012-03-03 22:46:17 +00006319 bool Success(const APValue &V, const Expr *E) {
6320 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00006321 return true;
6322 }
Richard Smithfddd3842011-12-30 21:15:51 +00006323 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00006324 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
6325 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00006326 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00006327 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006328
John McCall45d55e42010-05-07 21:00:08 +00006329 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006330 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00006331 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006332 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00006333 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00006334 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00006335 if (E->isExpressibleAsConstantInitializer())
6336 return Success(E);
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00006337 if (Info.noteFailure())
6338 EvaluateIgnoredValue(Info, E->getSubExpr());
6339 return Error(E);
6340 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006341 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00006342 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00006343 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006344 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00006345 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00006346 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00006347 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006348 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00006349 }
Richard Smithd62306a2011-11-10 06:34:14 +00006350 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00006351 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00006352 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00006353 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00006354 if (!Info.CurrentCall->This) {
6355 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00006356 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00006357 else
Faisal Valie690b7a2016-07-02 22:34:24 +00006358 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00006359 return false;
6360 }
Richard Smithd62306a2011-11-10 06:34:14 +00006361 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00006362 // If we are inside a lambda's call operator, the 'this' expression refers
6363 // to the enclosing '*this' object (either by value or reference) which is
6364 // either copied into the closure object's field that represents the '*this'
6365 // or refers to '*this'.
6366 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
6367 // Update 'Result' to refer to the data member/field of the closure object
6368 // that represents the '*this' capture.
6369 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00006370 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00006371 return false;
6372 // If we captured '*this' by reference, replace the field with its referent.
6373 if (Info.CurrentCall->LambdaThisCaptureField->getType()
6374 ->isPointerType()) {
6375 APValue RVal;
6376 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
6377 RVal))
6378 return false;
6379
6380 Result.setFrom(Info.Ctx, RVal);
6381 }
6382 }
Richard Smithd62306a2011-11-10 06:34:14 +00006383 return true;
6384 }
John McCallc07a0c72011-02-17 10:25:35 +00006385
Eric Fiselier708afb52019-05-16 21:04:15 +00006386 bool VisitSourceLocExpr(const SourceLocExpr *E) {
6387 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
6388 APValue LValResult = E->EvaluateInContext(
6389 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
6390 Result.setFrom(Info.Ctx, LValResult);
6391 return true;
6392 }
6393
Eli Friedman449fe542009-03-23 04:56:01 +00006394 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006395};
Chris Lattner05706e882008-07-11 18:11:29 +00006396} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006397
George Burgess IVf9013bf2017-02-10 22:52:29 +00006398static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
6399 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00006400 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00006401 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00006402}
6403
John McCall45d55e42010-05-07 21:00:08 +00006404bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00006405 if (E->getOpcode() != BO_Add &&
6406 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00006407 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00006408
Chris Lattner05706e882008-07-11 18:11:29 +00006409 const Expr *PExp = E->getLHS();
6410 const Expr *IExp = E->getRHS();
6411 if (IExp->getType()->isPointerType())
6412 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00006413
George Burgess IVf9013bf2017-02-10 22:52:29 +00006414 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00006415 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00006416 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006417
John McCall45d55e42010-05-07 21:00:08 +00006418 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00006419 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00006420 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00006421
Richard Smith96e0c102011-11-04 02:25:55 +00006422 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00006423 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00006424
Ted Kremenek28831752012-08-23 20:46:57 +00006425 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00006426 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00006427}
Eli Friedman9a156e52008-11-12 09:44:48 +00006428
John McCall45d55e42010-05-07 21:00:08 +00006429bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006430 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006431}
Mike Stump11289f42009-09-09 15:08:12 +00006432
Richard Smith81dfef92018-07-11 00:29:05 +00006433bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6434 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00006435
Eli Friedman847a2bc2009-12-27 05:43:15 +00006436 switch (E->getCastKind()) {
6437 default:
6438 break;
6439
John McCalle3027922010-08-25 11:45:40 +00006440 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00006441 case CK_CPointerToObjCPointerCast:
6442 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00006443 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00006444 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00006445 if (!Visit(SubExpr))
6446 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00006447 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
6448 // permitted in constant expressions in C++11. Bitcasts from cv void* are
6449 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00006450 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00006451 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00006452 if (SubExpr->getType()->isVoidPointerType())
6453 CCEDiag(E, diag::note_constexpr_invalid_cast)
6454 << 3 << SubExpr->getType();
6455 else
6456 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6457 }
Yaxun Liu402804b2016-12-15 08:09:08 +00006458 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
6459 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00006460 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00006461
Anders Carlsson18275092010-10-31 20:41:46 +00006462 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00006463 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006464 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00006465 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006466 if (!Result.Base && Result.Offset.isZero())
6467 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00006468
Richard Smithd62306a2011-11-10 06:34:14 +00006469 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00006470 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00006471 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
6472 castAs<PointerType>()->getPointeeType(),
6473 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00006474
Richard Smith027bf112011-11-17 22:56:20 +00006475 case CK_BaseToDerived:
6476 if (!Visit(E->getSubExpr()))
6477 return false;
6478 if (!Result.Base && Result.Offset.isZero())
6479 return true;
6480 return HandleBaseToDerivedCast(Info, E, Result);
6481
Richard Smith7bd54ab2019-05-15 20:22:21 +00006482 case CK_Dynamic:
6483 if (!Visit(E->getSubExpr()))
6484 return false;
6485 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
6486
Richard Smith0b0a0b62011-10-29 20:57:55 +00006487 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006488 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006489 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00006490
John McCalle3027922010-08-25 11:45:40 +00006491 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006492 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6493
Richard Smith2e312c82012-03-03 22:46:17 +00006494 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00006495 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00006496 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00006497
John McCall45d55e42010-05-07 21:00:08 +00006498 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00006499 unsigned Size = Info.Ctx.getTypeSize(E->getType());
6500 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006501 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006502 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00006503 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00006504 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00006505 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00006506 return true;
6507 } else {
6508 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00006509 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00006510 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00006511 }
6512 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00006513
6514 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00006515 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006516 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00006517 return false;
6518 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006519 APValue &Value = createTemporary(SubExpr, false, Result,
6520 *Info.CurrentCall);
6521 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00006522 return false;
6523 }
Richard Smith96e0c102011-11-04 02:25:55 +00006524 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00006525 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
6526 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00006527 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00006528 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00006529 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00006530 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00006531 }
Richard Smithdd785442011-10-31 20:57:44 +00006532
John McCalle3027922010-08-25 11:45:40 +00006533 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006534 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00006535
6536 case CK_LValueToRValue: {
6537 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006538 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00006539 return false;
6540
6541 APValue RVal;
6542 // Note, we use the subexpression's type in order to retain cv-qualifiers.
6543 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6544 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00006545 return InvalidBaseOK &&
6546 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00006547 return Success(RVal, E);
6548 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006549 }
6550
Richard Smith11562c52011-10-28 17:51:58 +00006551 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00006552}
Chris Lattner05706e882008-07-11 18:11:29 +00006553
Richard Smith6822bd72018-10-26 19:26:45 +00006554static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
6555 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006556 // C++ [expr.alignof]p3:
6557 // When alignof is applied to a reference type, the result is the
6558 // alignment of the referenced type.
6559 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6560 T = Ref->getPointeeType();
6561
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00006562 if (T.getQualifiers().hasUnaligned())
6563 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00006564
6565 const bool AlignOfReturnsPreferred =
6566 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
6567
6568 // __alignof is defined to return the preferred alignment.
6569 // Before 8, clang returned the preferred alignment for alignof and _Alignof
6570 // as well.
6571 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
6572 return Info.Ctx.toCharUnitsFromBits(
6573 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6574 // alignof and _Alignof are defined to return the ABI alignment.
6575 else if (ExprKind == UETT_AlignOf)
6576 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
6577 else
6578 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00006579}
6580
Richard Smith6822bd72018-10-26 19:26:45 +00006581static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
6582 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006583 E = E->IgnoreParens();
6584
6585 // The kinds of expressions that we have special-case logic here for
6586 // should be kept up to date with the special checks for those
6587 // expressions in Sema.
6588
6589 // alignof decl is always accepted, even if it doesn't make sense: we default
6590 // to 1 in those cases.
6591 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6592 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6593 /*RefAsPointee*/true);
6594
6595 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6596 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6597 /*RefAsPointee*/true);
6598
Richard Smith6822bd72018-10-26 19:26:45 +00006599 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006600}
6601
George Burgess IVe3763372016-12-22 02:50:20 +00006602// To be clear: this happily visits unsupported builtins. Better name welcomed.
6603bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6604 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6605 return true;
6606
George Burgess IVf9013bf2017-02-10 22:52:29 +00006607 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00006608 return false;
6609
6610 Result.setInvalid(E);
6611 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006612 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00006613 return true;
6614}
6615
Peter Collingbournee9200682011-05-13 03:29:01 +00006616bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006617 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00006618 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00006619
Richard Smith6328cbd2016-11-16 00:57:23 +00006620 if (unsigned BuiltinOp = E->getBuiltinCallee())
6621 return VisitBuiltinCallExpr(E, BuiltinOp);
6622
George Burgess IVe3763372016-12-22 02:50:20 +00006623 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006624}
6625
6626bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6627 unsigned BuiltinOp) {
6628 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00006629 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006630 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006631 case Builtin::BI__builtin_assume_aligned: {
6632 // We need to be very careful here because: if the pointer does not have the
6633 // asserted alignment, then the behavior is undefined, and undefined
6634 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00006635 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00006636 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00006637
Hal Finkel0dd05d42014-10-03 17:18:37 +00006638 LValue OffsetResult(Result);
6639 APSInt Alignment;
6640 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6641 return false;
Richard Smith642a2362017-01-30 23:30:26 +00006642 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00006643
6644 if (E->getNumArgs() > 2) {
6645 APSInt Offset;
6646 if (!EvaluateInteger(E->getArg(2), Offset, Info))
6647 return false;
6648
Richard Smith642a2362017-01-30 23:30:26 +00006649 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006650 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6651 }
6652
6653 // If there is a base object, then it must have the correct alignment.
6654 if (OffsetResult.Base) {
6655 CharUnits BaseAlignment;
6656 if (const ValueDecl *VD =
6657 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6658 BaseAlignment = Info.Ctx.getDeclAlign(VD);
Richard Smithee0ce3022019-05-17 07:06:46 +00006659 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
6660 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006661 } else {
Richard Smithee0ce3022019-05-17 07:06:46 +00006662 BaseAlignment = GetAlignOfType(
6663 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006664 }
6665
6666 if (BaseAlignment < Align) {
6667 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00006668 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00006669 CCEDiag(E->getArg(0),
6670 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00006671 << (unsigned)BaseAlignment.getQuantity()
6672 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006673 return false;
6674 }
6675 }
6676
6677 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006678 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006679 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006680
Richard Smith642a2362017-01-30 23:30:26 +00006681 (OffsetResult.Base
6682 ? CCEDiag(E->getArg(0),
6683 diag::note_constexpr_baa_insufficient_alignment) << 1
6684 : CCEDiag(E->getArg(0),
6685 diag::note_constexpr_baa_value_insufficient_alignment))
6686 << (int)OffsetResult.Offset.getQuantity()
6687 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006688 return false;
6689 }
6690
6691 return true;
6692 }
Eric Fiselier26187502018-12-14 21:11:28 +00006693 case Builtin::BI__builtin_launder:
6694 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00006695 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006696 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00006697 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006698 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00006699 if (Info.getLangOpts().CPlusPlus11)
6700 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6701 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00006702 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00006703 else
6704 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006705 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00006706 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006707 case Builtin::BI__builtin_wcschr:
6708 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006709 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006710 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00006711 if (!Visit(E->getArg(0)))
6712 return false;
6713 APSInt Desired;
6714 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6715 return false;
6716 uint64_t MaxLength = uint64_t(-1);
6717 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00006718 BuiltinOp != Builtin::BIwcschr &&
6719 BuiltinOp != Builtin::BI__builtin_strchr &&
6720 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00006721 APSInt N;
6722 if (!EvaluateInteger(E->getArg(2), N, Info))
6723 return false;
6724 MaxLength = N.getExtValue();
6725 }
Hubert Tong147b7432018-12-12 16:53:43 +00006726 // We cannot find the value if there are no candidates to match against.
6727 if (MaxLength == 0u)
6728 return ZeroInitialization(E);
6729 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
6730 Result.Designator.Invalid)
6731 return false;
6732 QualType CharTy = Result.Designator.getType(Info.Ctx);
6733 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
6734 BuiltinOp == Builtin::BI__builtin_memchr;
6735 assert(IsRawByte ||
6736 Info.Ctx.hasSameUnqualifiedType(
6737 CharTy, E->getArg(0)->getType()->getPointeeType()));
6738 // Pointers to const void may point to objects of incomplete type.
6739 if (IsRawByte && CharTy->isIncompleteType()) {
6740 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
6741 return false;
6742 }
6743 // Give up on byte-oriented matching against multibyte elements.
6744 // FIXME: We can compare the bytes in the correct order.
6745 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
6746 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00006747 // Figure out what value we're actually looking for (after converting to
6748 // the corresponding unsigned type if necessary).
6749 uint64_t DesiredVal;
6750 bool StopAtNull = false;
6751 switch (BuiltinOp) {
6752 case Builtin::BIstrchr:
6753 case Builtin::BI__builtin_strchr:
6754 // strchr compares directly to the passed integer, and therefore
6755 // always fails if given an int that is not a char.
6756 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6757 E->getArg(1)->getType(),
6758 Desired),
6759 Desired))
6760 return ZeroInitialization(E);
6761 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006762 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006763 case Builtin::BImemchr:
6764 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006765 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006766 // memchr compares by converting both sides to unsigned char. That's also
6767 // correct for strchr if we get this far (to cope with plain char being
6768 // unsigned in the strchr case).
6769 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6770 break;
Richard Smithe9507952016-11-12 01:39:56 +00006771
Richard Smith8110c9d2016-11-29 19:45:17 +00006772 case Builtin::BIwcschr:
6773 case Builtin::BI__builtin_wcschr:
6774 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006775 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006776 case Builtin::BIwmemchr:
6777 case Builtin::BI__builtin_wmemchr:
6778 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6779 DesiredVal = Desired.getZExtValue();
6780 break;
6781 }
Richard Smithe9507952016-11-12 01:39:56 +00006782
6783 for (; MaxLength; --MaxLength) {
6784 APValue Char;
6785 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6786 !Char.isInt())
6787 return false;
6788 if (Char.getInt().getZExtValue() == DesiredVal)
6789 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006790 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006791 break;
6792 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6793 return false;
6794 }
6795 // Not found: return nullptr.
6796 return ZeroInitialization(E);
6797 }
6798
Richard Smith06f71b52018-08-04 00:57:17 +00006799 case Builtin::BImemcpy:
6800 case Builtin::BImemmove:
6801 case Builtin::BIwmemcpy:
6802 case Builtin::BIwmemmove:
6803 if (Info.getLangOpts().CPlusPlus11)
6804 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6805 << /*isConstexpr*/0 << /*isConstructor*/0
6806 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6807 else
6808 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6809 LLVM_FALLTHROUGH;
6810 case Builtin::BI__builtin_memcpy:
6811 case Builtin::BI__builtin_memmove:
6812 case Builtin::BI__builtin_wmemcpy:
6813 case Builtin::BI__builtin_wmemmove: {
6814 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6815 BuiltinOp == Builtin::BIwmemmove ||
6816 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6817 BuiltinOp == Builtin::BI__builtin_wmemmove;
6818 bool Move = BuiltinOp == Builtin::BImemmove ||
6819 BuiltinOp == Builtin::BIwmemmove ||
6820 BuiltinOp == Builtin::BI__builtin_memmove ||
6821 BuiltinOp == Builtin::BI__builtin_wmemmove;
6822
6823 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00006824 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00006825 return false;
6826 LValue Dest = Result;
6827
6828 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00006829 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00006830 return false;
6831
6832 APSInt N;
6833 if (!EvaluateInteger(E->getArg(2), N, Info))
6834 return false;
6835 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6836
6837 // If the size is zero, we treat this as always being a valid no-op.
6838 // (Even if one of the src and dest pointers is null.)
6839 if (!N)
6840 return true;
6841
Richard Smith128719c2018-09-13 22:47:33 +00006842 // Otherwise, if either of the operands is null, we can't proceed. Don't
6843 // try to determine the type of the copied objects, because there aren't
6844 // any.
6845 if (!Src.Base || !Dest.Base) {
6846 APValue Val;
6847 (!Src.Base ? Src : Dest).moveInto(Val);
6848 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6849 << Move << WChar << !!Src.Base
6850 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6851 return false;
6852 }
6853 if (Src.Designator.Invalid || Dest.Designator.Invalid)
6854 return false;
6855
Richard Smith06f71b52018-08-04 00:57:17 +00006856 // We require that Src and Dest are both pointers to arrays of
6857 // trivially-copyable type. (For the wide version, the designator will be
6858 // invalid if the designated object is not a wchar_t.)
6859 QualType T = Dest.Designator.getType(Info.Ctx);
6860 QualType SrcT = Src.Designator.getType(Info.Ctx);
6861 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6862 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6863 return false;
6864 }
Petr Pavlued083f22018-10-04 09:25:44 +00006865 if (T->isIncompleteType()) {
6866 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6867 return false;
6868 }
Richard Smith06f71b52018-08-04 00:57:17 +00006869 if (!T.isTriviallyCopyableType(Info.Ctx)) {
6870 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6871 return false;
6872 }
6873
6874 // Figure out how many T's we're copying.
6875 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6876 if (!WChar) {
6877 uint64_t Remainder;
6878 llvm::APInt OrigN = N;
6879 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6880 if (Remainder) {
6881 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6882 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6883 << (unsigned)TSize;
6884 return false;
6885 }
6886 }
6887
6888 // Check that the copying will remain within the arrays, just so that we
6889 // can give a more meaningful diagnostic. This implicitly also checks that
6890 // N fits into 64 bits.
6891 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6892 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6893 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6894 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6895 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6896 << N.toString(10, /*Signed*/false);
6897 return false;
6898 }
6899 uint64_t NElems = N.getZExtValue();
6900 uint64_t NBytes = NElems * TSize;
6901
6902 // Check for overlap.
6903 int Direction = 1;
6904 if (HasSameBase(Src, Dest)) {
6905 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6906 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6907 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6908 // Dest is inside the source region.
6909 if (!Move) {
6910 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6911 return false;
6912 }
6913 // For memmove and friends, copy backwards.
6914 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6915 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6916 return false;
6917 Direction = -1;
6918 } else if (!Move && SrcOffset >= DestOffset &&
6919 SrcOffset - DestOffset < NBytes) {
6920 // Src is inside the destination region for memcpy: invalid.
6921 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6922 return false;
6923 }
6924 }
6925
6926 while (true) {
6927 APValue Val;
6928 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6929 !handleAssignment(Info, E, Dest, T, Val))
6930 return false;
6931 // Do not iterate past the last element; if we're copying backwards, that
6932 // might take us off the start of the array.
6933 if (--NElems == 0)
6934 return true;
6935 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6936 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6937 return false;
6938 }
6939 }
6940
Richard Smith6cbd65d2013-07-11 02:27:57 +00006941 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006942 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006943 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006944}
Chris Lattner05706e882008-07-11 18:11:29 +00006945
6946//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006947// Member Pointer Evaluation
6948//===----------------------------------------------------------------------===//
6949
6950namespace {
6951class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006952 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006953 MemberPtr &Result;
6954
6955 bool Success(const ValueDecl *D) {
6956 Result = MemberPtr(D);
6957 return true;
6958 }
6959public:
6960
6961 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6962 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6963
Richard Smith2e312c82012-03-03 22:46:17 +00006964 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006965 Result.setFrom(V);
6966 return true;
6967 }
Richard Smithfddd3842011-12-30 21:15:51 +00006968 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006969 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006970 }
6971
6972 bool VisitCastExpr(const CastExpr *E);
6973 bool VisitUnaryAddrOf(const UnaryOperator *E);
6974};
6975} // end anonymous namespace
6976
6977static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6978 EvalInfo &Info) {
6979 assert(E->isRValue() && E->getType()->isMemberPointerType());
6980 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6981}
6982
6983bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6984 switch (E->getCastKind()) {
6985 default:
6986 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6987
6988 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006989 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006990 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006991
6992 case CK_BaseToDerivedMemberPointer: {
6993 if (!Visit(E->getSubExpr()))
6994 return false;
6995 if (E->path_empty())
6996 return true;
6997 // Base-to-derived member pointer casts store the path in derived-to-base
6998 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6999 // the wrong end of the derived->base arc, so stagger the path by one class.
7000 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
7001 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
7002 PathI != PathE; ++PathI) {
7003 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7004 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7005 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007006 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007007 }
7008 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7009 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007010 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007011 return true;
7012 }
7013
7014 case CK_DerivedToBaseMemberPointer:
7015 if (!Visit(E->getSubExpr()))
7016 return false;
7017 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7018 PathE = E->path_end(); PathI != PathE; ++PathI) {
7019 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7020 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7021 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007022 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007023 }
7024 return true;
7025 }
7026}
7027
7028bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7029 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7030 // member can be formed.
7031 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7032}
7033
7034//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00007035// Record Evaluation
7036//===----------------------------------------------------------------------===//
7037
7038namespace {
7039 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007040 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007041 const LValue &This;
7042 APValue &Result;
7043 public:
7044
7045 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
7046 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
7047
Richard Smith2e312c82012-03-03 22:46:17 +00007048 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00007049 Result = V;
7050 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00007051 }
Richard Smithb8348f52016-05-12 22:16:28 +00007052 bool ZeroInitialization(const Expr *E) {
7053 return ZeroInitialization(E, E->getType());
7054 }
7055 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00007056
Richard Smith52a980a2015-08-28 02:43:42 +00007057 bool VisitCallExpr(const CallExpr *E) {
7058 return handleCallExpr(E, Result, &This);
7059 }
Richard Smithe97cbd72011-11-11 04:05:33 +00007060 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00007061 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00007062 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7063 return VisitCXXConstructExpr(E, E->getType());
7064 }
Faisal Valic72a08c2017-01-09 03:02:53 +00007065 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00007066 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00007067 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007068 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007069
7070 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00007071 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007072}
Richard Smithd62306a2011-11-10 06:34:14 +00007073
Richard Smithfddd3842011-12-30 21:15:51 +00007074/// Perform zero-initialization on an object of non-union class type.
7075/// C++11 [dcl.init]p5:
7076/// To zero-initialize an object or reference of type T means:
7077/// [...]
7078/// -- if T is a (possibly cv-qualified) non-union class type,
7079/// each non-static data member and each base-class subobject is
7080/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00007081static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
7082 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00007083 const LValue &This, APValue &Result) {
7084 assert(!RD->isUnion() && "Expected non-union class type");
7085 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
7086 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00007087 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00007088
John McCalld7bca762012-05-01 00:38:49 +00007089 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007090 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7091
7092 if (CD) {
7093 unsigned Index = 0;
7094 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00007095 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00007096 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
7097 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00007098 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
7099 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00007100 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00007101 Result.getStructBase(Index)))
7102 return false;
7103 }
7104 }
7105
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007106 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00007107 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00007108 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00007109 continue;
7110
7111 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007112 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00007113 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007114
David Blaikie2d7c57e2012-04-30 02:36:29 +00007115 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007116 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00007117 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00007118 return false;
7119 }
7120
7121 return true;
7122}
7123
Richard Smithb8348f52016-05-12 22:16:28 +00007124bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
7125 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00007126 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007127 if (RD->isUnion()) {
7128 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
7129 // object's first non-static named data member is zero-initialized
7130 RecordDecl::field_iterator I = RD->field_begin();
7131 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00007132 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00007133 return true;
7134 }
7135
7136 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00007137 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00007138 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00007139 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00007140 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007141 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00007142 }
7143
Richard Smith5d108602012-02-17 00:44:16 +00007144 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00007145 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00007146 return false;
7147 }
7148
Richard Smitha8105bc2012-01-06 16:39:00 +00007149 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00007150}
7151
Richard Smithe97cbd72011-11-11 04:05:33 +00007152bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
7153 switch (E->getCastKind()) {
7154 default:
7155 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7156
7157 case CK_ConstructorConversion:
7158 return Visit(E->getSubExpr());
7159
7160 case CK_DerivedToBase:
7161 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00007162 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007163 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00007164 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007165 if (!DerivedObject.isStruct())
7166 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00007167
7168 // Derived-to-base rvalue conversion: just slice off the derived part.
7169 APValue *Value = &DerivedObject;
7170 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
7171 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7172 PathE = E->path_end(); PathI != PathE; ++PathI) {
7173 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
7174 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7175 Value = &Value->getStructBase(getBaseIndex(RD, Base));
7176 RD = Base;
7177 }
7178 Result = *Value;
7179 return true;
7180 }
7181 }
7182}
7183
Richard Smithd62306a2011-11-10 06:34:14 +00007184bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00007185 if (E->isTransparent())
7186 return Visit(E->getInit(0));
7187
Richard Smithd62306a2011-11-10 06:34:14 +00007188 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00007189 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007190 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007191 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
7192
7193 EvalInfo::EvaluatingConstructorRAII EvalObj(
7194 Info,
7195 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7196 CXXRD && CXXRD->getNumBases());
Richard Smithd62306a2011-11-10 06:34:14 +00007197
7198 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00007199 const FieldDecl *Field = E->getInitializedFieldInUnion();
7200 Result = APValue(Field);
7201 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00007202 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00007203
7204 // If the initializer list for a union does not contain any elements, the
7205 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00007206 // FIXME: The element should be initialized from an initializer list.
7207 // Is this difference ever observable for initializer lists which
7208 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00007209 ImplicitValueInitExpr VIE(Field->getType());
7210 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
7211
Richard Smithd62306a2011-11-10 06:34:14 +00007212 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00007213 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
7214 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00007215
7216 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7217 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7218 isa<CXXDefaultInitExpr>(InitExpr));
7219
Richard Smithb228a862012-02-15 02:18:13 +00007220 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00007221 }
7222
Richard Smithe637cbe2019-05-21 23:15:18 +00007223 if (!Result.hasValue())
Richard Smithc0d04a22016-05-25 22:06:25 +00007224 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
7225 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00007226 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00007227 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00007228
7229 // Initialize base classes.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007230 if (CXXRD && CXXRD->getNumBases()) {
Richard Smith872307e2016-03-08 22:17:41 +00007231 for (const auto &Base : CXXRD->bases()) {
7232 assert(ElementNo < E->getNumInits() && "missing init for base class");
7233 const Expr *Init = E->getInit(ElementNo);
7234
7235 LValue Subobject = This;
7236 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
7237 return false;
7238
7239 APValue &FieldVal = Result.getStructBase(ElementNo);
7240 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007241 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00007242 return false;
7243 Success = false;
7244 }
7245 ++ElementNo;
7246 }
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007247
7248 EvalObj.finishedConstructingBases();
Richard Smith872307e2016-03-08 22:17:41 +00007249 }
7250
7251 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007252 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007253 // Anonymous bit-fields are not considered members of the class for
7254 // purposes of aggregate initialization.
7255 if (Field->isUnnamedBitfield())
7256 continue;
7257
7258 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00007259
Richard Smith253c2a32012-01-27 01:14:48 +00007260 bool HaveInit = ElementNo < E->getNumInits();
7261
7262 // FIXME: Diagnostics here should point to the end of the initializer
7263 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00007264 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007265 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00007266 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00007267
7268 // Perform an implicit value-initialization for members beyond the end of
7269 // the initializer list.
7270 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00007271 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00007272
Richard Smith852c9db2013-04-20 22:23:05 +00007273 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7274 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7275 isa<CXXDefaultInitExpr>(Init));
7276
Richard Smith49ca8aa2013-08-06 07:09:20 +00007277 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7278 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
7279 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007280 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00007281 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00007282 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00007283 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00007284 }
7285 }
7286
Richard Smith253c2a32012-01-27 01:14:48 +00007287 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00007288}
7289
Richard Smithb8348f52016-05-12 22:16:28 +00007290bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7291 QualType T) {
7292 // Note that E's type is not necessarily the type of our class here; we might
7293 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00007294 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00007295 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
7296
Richard Smithfddd3842011-12-30 21:15:51 +00007297 bool ZeroInit = E->requiresZeroInitialization();
7298 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00007299 // If we've already performed zero-initialization, we're already done.
Richard Smithe637cbe2019-05-21 23:15:18 +00007300 if (Result.hasValue())
Richard Smith9eae7232012-01-12 18:54:33 +00007301 return true;
7302
Richard Smithda3f4fd2014-03-05 23:32:50 +00007303 // We can get here in two different ways:
7304 // 1) We're performing value-initialization, and should zero-initialize
7305 // the object, or
7306 // 2) We're performing default-initialization of an object with a trivial
7307 // constexpr default constructor, in which case we should start the
7308 // lifetimes of all the base subobjects (there can be no data member
7309 // subobjects in this case) per [basic.life]p1.
7310 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00007311 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00007312 }
7313
Craig Topper36250ad2014-05-12 05:36:57 +00007314 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00007315 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00007316
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00007317 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00007318 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007319
Richard Smith1bc5c2c2012-01-10 04:32:03 +00007320 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00007321 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00007322 if (const MaterializeTemporaryExpr *ME
7323 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
7324 return Visit(ME->GetTemporaryExpr());
7325
Richard Smithb8348f52016-05-12 22:16:28 +00007326 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00007327 return false;
7328
Craig Topper5fc8fc22014-08-27 06:28:36 +00007329 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00007330 return HandleConstructorCall(E, This, Args,
7331 cast<CXXConstructorDecl>(Definition), Info,
7332 Result);
7333}
7334
7335bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
7336 const CXXInheritedCtorInitExpr *E) {
7337 if (!Info.CurrentCall) {
7338 assert(Info.checkingPotentialConstantExpression());
7339 return false;
7340 }
7341
7342 const CXXConstructorDecl *FD = E->getConstructor();
7343 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
7344 return false;
7345
7346 const FunctionDecl *Definition = nullptr;
7347 auto Body = FD->getBody(Definition);
7348
7349 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
7350 return false;
7351
7352 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00007353 cast<CXXConstructorDecl>(Definition), Info,
7354 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00007355}
7356
Richard Smithcc1b96d2013-06-12 22:31:48 +00007357bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
7358 const CXXStdInitializerListExpr *E) {
7359 const ConstantArrayType *ArrayType =
7360 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
7361
7362 LValue Array;
7363 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
7364 return false;
7365
7366 // Get a pointer to the first element of the array.
7367 Array.addArray(Info, E, ArrayType);
7368
7369 // FIXME: Perform the checks on the field types in SemaInit.
7370 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
7371 RecordDecl::field_iterator Field = Record->field_begin();
7372 if (Field == Record->field_end())
7373 return Error(E);
7374
7375 // Start pointer.
7376 if (!Field->getType()->isPointerType() ||
7377 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
7378 ArrayType->getElementType()))
7379 return Error(E);
7380
7381 // FIXME: What if the initializer_list type has base classes, etc?
7382 Result = APValue(APValue::UninitStruct(), 0, 2);
7383 Array.moveInto(Result.getStructField(0));
7384
7385 if (++Field == Record->field_end())
7386 return Error(E);
7387
7388 if (Field->getType()->isPointerType() &&
7389 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
7390 ArrayType->getElementType())) {
7391 // End pointer.
7392 if (!HandleLValueArrayAdjustment(Info, E, Array,
7393 ArrayType->getElementType(),
7394 ArrayType->getSize().getZExtValue()))
7395 return false;
7396 Array.moveInto(Result.getStructField(1));
7397 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
7398 // Length.
7399 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
7400 else
7401 return Error(E);
7402
7403 if (++Field != Record->field_end())
7404 return Error(E);
7405
7406 return true;
7407}
7408
Faisal Valic72a08c2017-01-09 03:02:53 +00007409bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
7410 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
7411 if (ClosureClass->isInvalidDecl()) return false;
7412
7413 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00007414
Faisal Vali051e3a22017-02-16 04:12:21 +00007415 const size_t NumFields =
7416 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00007417
7418 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
7419 E->capture_init_end()) &&
7420 "The number of lambda capture initializers should equal the number of "
7421 "fields within the closure type");
7422
Faisal Vali051e3a22017-02-16 04:12:21 +00007423 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
7424 // Iterate through all the lambda's closure object's fields and initialize
7425 // them.
7426 auto *CaptureInitIt = E->capture_init_begin();
7427 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
7428 bool Success = true;
7429 for (const auto *Field : ClosureClass->fields()) {
7430 assert(CaptureInitIt != E->capture_init_end());
7431 // Get the initializer for this field
7432 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00007433
Faisal Vali051e3a22017-02-16 04:12:21 +00007434 // If there is no initializer, either this is a VLA or an error has
7435 // occurred.
7436 if (!CurFieldInit)
7437 return Error(E);
7438
7439 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7440 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
7441 if (!Info.keepEvaluatingAfterFailure())
7442 return false;
7443 Success = false;
7444 }
7445 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00007446 }
Faisal Vali051e3a22017-02-16 04:12:21 +00007447 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00007448}
7449
Richard Smithd62306a2011-11-10 06:34:14 +00007450static bool EvaluateRecord(const Expr *E, const LValue &This,
7451 APValue &Result, EvalInfo &Info) {
7452 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00007453 "can't evaluate expression as a record rvalue");
7454 return RecordExprEvaluator(Info, This, Result).Visit(E);
7455}
7456
7457//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00007458// Temporary Evaluation
7459//
7460// Temporaries are represented in the AST as rvalues, but generally behave like
7461// lvalues. The full-object of which the temporary is a subobject is implicitly
7462// materialized so that a reference can bind to it.
7463//===----------------------------------------------------------------------===//
7464namespace {
7465class TemporaryExprEvaluator
7466 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
7467public:
7468 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00007469 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00007470
7471 /// Visit an expression which constructs the value of this temporary.
7472 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007473 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
7474 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00007475 }
7476
7477 bool VisitCastExpr(const CastExpr *E) {
7478 switch (E->getCastKind()) {
7479 default:
7480 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7481
7482 case CK_ConstructorConversion:
7483 return VisitConstructExpr(E->getSubExpr());
7484 }
7485 }
7486 bool VisitInitListExpr(const InitListExpr *E) {
7487 return VisitConstructExpr(E);
7488 }
7489 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7490 return VisitConstructExpr(E);
7491 }
7492 bool VisitCallExpr(const CallExpr *E) {
7493 return VisitConstructExpr(E);
7494 }
Richard Smith513955c2014-12-17 19:24:30 +00007495 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
7496 return VisitConstructExpr(E);
7497 }
Faisal Valic72a08c2017-01-09 03:02:53 +00007498 bool VisitLambdaExpr(const LambdaExpr *E) {
7499 return VisitConstructExpr(E);
7500 }
Richard Smith027bf112011-11-17 22:56:20 +00007501};
7502} // end anonymous namespace
7503
7504/// Evaluate an expression of record type as a temporary.
7505static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00007506 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00007507 return TemporaryExprEvaluator(Info, Result).Visit(E);
7508}
7509
7510//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007511// Vector Evaluation
7512//===----------------------------------------------------------------------===//
7513
7514namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007515 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007516 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00007517 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007518 public:
Mike Stump11289f42009-09-09 15:08:12 +00007519
Richard Smith2d406342011-10-22 21:10:00 +00007520 VectorExprEvaluator(EvalInfo &info, APValue &Result)
7521 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00007522
Craig Topper9798b932015-09-29 04:30:05 +00007523 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007524 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
7525 // FIXME: remove this APValue copy.
7526 Result = APValue(V.data(), V.size());
7527 return true;
7528 }
Richard Smith2e312c82012-03-03 22:46:17 +00007529 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00007530 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00007531 Result = V;
7532 return true;
7533 }
Richard Smithfddd3842011-12-30 21:15:51 +00007534 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00007535
Richard Smith2d406342011-10-22 21:10:00 +00007536 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00007537 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00007538 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00007539 bool VisitInitListExpr(const InitListExpr *E);
7540 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007541 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00007542 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00007543 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007544 };
7545} // end anonymous namespace
7546
7547static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007548 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00007549 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007550}
7551
George Burgess IV533ff002015-12-11 00:23:35 +00007552bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007553 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00007554 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007555
Richard Smith161f09a2011-12-06 22:44:34 +00007556 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00007557 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007558
Eli Friedmanc757de22011-03-25 00:43:55 +00007559 switch (E->getCastKind()) {
7560 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00007561 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00007562 if (SETy->isIntegerType()) {
7563 APSInt IntResult;
7564 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00007565 return false;
7566 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00007567 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00007568 APFloat FloatResult(0.0);
7569 if (!EvaluateFloat(SE, FloatResult, Info))
7570 return false;
7571 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00007572 } else {
Richard Smith2d406342011-10-22 21:10:00 +00007573 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007574 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00007575
7576 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00007577 SmallVector<APValue, 4> Elts(NElts, Val);
7578 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00007579 }
Eli Friedman803acb32011-12-22 03:51:45 +00007580 case CK_BitCast: {
7581 // Evaluate the operand into an APInt we can extract from.
7582 llvm::APInt SValInt;
7583 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
7584 return false;
7585 // Extract the elements
7586 QualType EltTy = VTy->getElementType();
7587 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
7588 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7589 SmallVector<APValue, 4> Elts;
7590 if (EltTy->isRealFloatingType()) {
7591 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00007592 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00007593 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00007594 FloatEltSize = 80;
7595 for (unsigned i = 0; i < NElts; i++) {
7596 llvm::APInt Elt;
7597 if (BigEndian)
7598 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
7599 else
7600 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00007601 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00007602 }
7603 } else if (EltTy->isIntegerType()) {
7604 for (unsigned i = 0; i < NElts; i++) {
7605 llvm::APInt Elt;
7606 if (BigEndian)
7607 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
7608 else
7609 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
7610 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
7611 }
7612 } else {
7613 return Error(E);
7614 }
7615 return Success(Elts, E);
7616 }
Eli Friedmanc757de22011-03-25 00:43:55 +00007617 default:
Richard Smith11562c52011-10-28 17:51:58 +00007618 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007619 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007620}
7621
Richard Smith2d406342011-10-22 21:10:00 +00007622bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007623VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007624 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007625 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00007626 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007627
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007628 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007629 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007630
Eli Friedmanb9c71292012-01-03 23:24:20 +00007631 // The number of initializers can be less than the number of
7632 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00007633 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00007634 // should be initialized with zeroes.
7635 unsigned CountInits = 0, CountElts = 0;
7636 while (CountElts < NumElements) {
7637 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00007638 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00007639 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00007640 APValue v;
7641 if (!EvaluateVector(E->getInit(CountInits), v, Info))
7642 return Error(E);
7643 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00007644 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00007645 Elements.push_back(v.getVectorElt(j));
7646 CountElts += vlen;
7647 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007648 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007649 if (CountInits < NumInits) {
7650 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007651 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007652 } else // trailing integer zero.
7653 sInt = Info.Ctx.MakeIntValue(0, EltTy);
7654 Elements.push_back(APValue(sInt));
7655 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007656 } else {
7657 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007658 if (CountInits < NumInits) {
7659 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007660 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007661 } else // trailing float zero.
7662 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7663 Elements.push_back(APValue(f));
7664 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00007665 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00007666 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007667 }
Richard Smith2d406342011-10-22 21:10:00 +00007668 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007669}
7670
Richard Smith2d406342011-10-22 21:10:00 +00007671bool
Richard Smithfddd3842011-12-30 21:15:51 +00007672VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007673 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00007674 QualType EltTy = VT->getElementType();
7675 APValue ZeroElement;
7676 if (EltTy->isIntegerType())
7677 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7678 else
7679 ZeroElement =
7680 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7681
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007682 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00007683 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007684}
7685
Richard Smith2d406342011-10-22 21:10:00 +00007686bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00007687 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007688 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007689}
7690
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007691//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00007692// Array Evaluation
7693//===----------------------------------------------------------------------===//
7694
7695namespace {
7696 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007697 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007698 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00007699 APValue &Result;
7700 public:
7701
Richard Smithd62306a2011-11-10 06:34:14 +00007702 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7703 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00007704
7705 bool Success(const APValue &V, const Expr *E) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00007706 assert(V.isArray() && "expected array");
Richard Smithf3e9e432011-11-07 09:22:26 +00007707 Result = V;
7708 return true;
7709 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007710
Richard Smithfddd3842011-12-30 21:15:51 +00007711 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007712 const ConstantArrayType *CAT =
7713 Info.Ctx.getAsConstantArrayType(E->getType());
7714 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007715 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007716
7717 Result = APValue(APValue::UninitArray(), 0,
7718 CAT->getSize().getZExtValue());
7719 if (!Result.hasArrayFiller()) return true;
7720
Richard Smithfddd3842011-12-30 21:15:51 +00007721 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00007722 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007723 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00007724 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00007725 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00007726 }
7727
Richard Smith52a980a2015-08-28 02:43:42 +00007728 bool VisitCallExpr(const CallExpr *E) {
7729 return handleCallExpr(E, Result, &This);
7730 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007731 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00007732 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00007733 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00007734 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7735 const LValue &Subobject,
7736 APValue *Value, QualType Type);
Eli Friedman3bf72d72019-02-08 21:18:46 +00007737 bool VisitStringLiteral(const StringLiteral *E) {
7738 expandStringLiteral(Info, E, Result);
7739 return true;
7740 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007741 };
7742} // end anonymous namespace
7743
Richard Smithd62306a2011-11-10 06:34:14 +00007744static bool EvaluateArray(const Expr *E, const LValue &This,
7745 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00007746 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00007747 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007748}
7749
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007750// Return true iff the given array filler may depend on the element index.
7751static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7752 // For now, just whitelist non-class value-initialization and initialization
7753 // lists comprised of them.
7754 if (isa<ImplicitValueInitExpr>(FillerExpr))
7755 return false;
7756 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7757 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7758 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7759 return true;
7760 }
7761 return false;
7762 }
7763 return true;
7764}
7765
Richard Smithf3e9e432011-11-07 09:22:26 +00007766bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7767 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7768 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007769 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007770
Richard Smithca2cfbf2011-12-22 01:07:19 +00007771 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7772 // an appropriately-typed string literal enclosed in braces.
Eli Friedman3bf72d72019-02-08 21:18:46 +00007773 if (E->isStringLiteralInit())
7774 return Visit(E->getInit(0));
Richard Smithca2cfbf2011-12-22 01:07:19 +00007775
Richard Smith253c2a32012-01-27 01:14:48 +00007776 bool Success = true;
7777
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007778 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7779 "zero-initialized array shouldn't have any initialized elts");
7780 APValue Filler;
7781 if (Result.isArray() && Result.hasArrayFiller())
7782 Filler = Result.getArrayFiller();
7783
Richard Smith9543c5e2013-04-22 14:44:29 +00007784 unsigned NumEltsToInit = E->getNumInits();
7785 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007786 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00007787
7788 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007789 // array element.
7790 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00007791 NumEltsToInit = NumElts;
7792
Nicola Zaghen3538b392018-05-15 13:30:56 +00007793 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7794 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007795
Richard Smith9543c5e2013-04-22 14:44:29 +00007796 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007797
7798 // If the array was previously zero-initialized, preserve the
7799 // zero-initialized values.
Richard Smithe637cbe2019-05-21 23:15:18 +00007800 if (Filler.hasValue()) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007801 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7802 Result.getArrayInitializedElt(I) = Filler;
7803 if (Result.hasArrayFiller())
7804 Result.getArrayFiller() = Filler;
7805 }
7806
Richard Smithd62306a2011-11-10 06:34:14 +00007807 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007808 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00007809 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7810 const Expr *Init =
7811 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00007812 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00007813 Info, Subobject, Init) ||
7814 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00007815 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007816 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00007817 return false;
7818 Success = false;
7819 }
Richard Smithd62306a2011-11-10 06:34:14 +00007820 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007821
Richard Smith9543c5e2013-04-22 14:44:29 +00007822 if (!Result.hasArrayFiller())
7823 return Success;
7824
7825 // If we get here, we have a trivial filler, which we can just evaluate
7826 // once and splat over the rest of the array elements.
7827 assert(FillerExpr && "no array filler for incomplete init list");
7828 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7829 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00007830}
7831
Richard Smith410306b2016-12-12 02:53:20 +00007832bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7833 if (E->getCommonExpr() &&
7834 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7835 Info, E->getCommonExpr()->getSourceExpr()))
7836 return false;
7837
7838 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7839
7840 uint64_t Elements = CAT->getSize().getZExtValue();
7841 Result = APValue(APValue::UninitArray(), Elements, Elements);
7842
7843 LValue Subobject = This;
7844 Subobject.addArray(Info, E, CAT);
7845
7846 bool Success = true;
7847 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7848 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7849 Info, Subobject, E->getSubExpr()) ||
7850 !HandleLValueArrayAdjustment(Info, E, Subobject,
7851 CAT->getElementType(), 1)) {
7852 if (!Info.noteFailure())
7853 return false;
7854 Success = false;
7855 }
7856 }
7857
7858 return Success;
7859}
7860
Richard Smith027bf112011-11-17 22:56:20 +00007861bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00007862 return VisitCXXConstructExpr(E, This, &Result, E->getType());
7863}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007864
Richard Smith9543c5e2013-04-22 14:44:29 +00007865bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7866 const LValue &Subobject,
7867 APValue *Value,
7868 QualType Type) {
Richard Smithe637cbe2019-05-21 23:15:18 +00007869 bool HadZeroInit = Value->hasValue();
Richard Smith9543c5e2013-04-22 14:44:29 +00007870
7871 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7872 unsigned N = CAT->getSize().getZExtValue();
7873
7874 // Preserve the array filler if we had prior zero-initialization.
7875 APValue Filler =
7876 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7877 : APValue();
7878
7879 *Value = APValue(APValue::UninitArray(), N, N);
7880
7881 if (HadZeroInit)
7882 for (unsigned I = 0; I != N; ++I)
7883 Value->getArrayInitializedElt(I) = Filler;
7884
7885 // Initialize the elements.
7886 LValue ArrayElt = Subobject;
7887 ArrayElt.addArray(Info, E, CAT);
7888 for (unsigned I = 0; I != N; ++I)
7889 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7890 CAT->getElementType()) ||
7891 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7892 CAT->getElementType(), 1))
7893 return false;
7894
7895 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007896 }
Richard Smith027bf112011-11-17 22:56:20 +00007897
Richard Smith9543c5e2013-04-22 14:44:29 +00007898 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00007899 return Error(E);
7900
Richard Smithb8348f52016-05-12 22:16:28 +00007901 return RecordExprEvaluator(Info, Subobject, *Value)
7902 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00007903}
7904
Richard Smithf3e9e432011-11-07 09:22:26 +00007905//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007906// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007907//
7908// As a GNU extension, we support casting pointers to sufficiently-wide integer
7909// types and back in constant folding. Integer values are thus represented
7910// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00007911//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007912
7913namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007914class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007915 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00007916 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007917public:
Richard Smith2e312c82012-03-03 22:46:17 +00007918 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007919 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007920
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007921 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007922 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007923 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007924 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007925 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007926 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007927 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007928 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007929 return true;
7930 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007931 bool Success(const llvm::APSInt &SI, const Expr *E) {
7932 return Success(SI, E, Result);
7933 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007934
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007935 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007936 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007937 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007938 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007939 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007940 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007941 Result.getInt().setIsUnsigned(
7942 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007943 return true;
7944 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007945 bool Success(const llvm::APInt &I, const Expr *E) {
7946 return Success(I, E, Result);
7947 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007948
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007949 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007950 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007951 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007952 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007953 return true;
7954 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007955 bool Success(uint64_t Value, const Expr *E) {
7956 return Success(Value, E, Result);
7957 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007958
Ken Dyckdbc01912011-03-11 02:13:43 +00007959 bool Success(CharUnits Size, const Expr *E) {
7960 return Success(Size.getQuantity(), E);
7961 }
7962
Richard Smith2e312c82012-03-03 22:46:17 +00007963 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007964 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007965 Result = V;
7966 return true;
7967 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007968 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007969 }
Mike Stump11289f42009-09-09 15:08:12 +00007970
Richard Smithfddd3842011-12-30 21:15:51 +00007971 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007972
Peter Collingbournee9200682011-05-13 03:29:01 +00007973 //===--------------------------------------------------------------------===//
7974 // Visitor Methods
7975 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007976
Fangrui Song407659a2018-11-30 23:41:18 +00007977 bool VisitConstantExpr(const ConstantExpr *E);
7978
Chris Lattner7174bf32008-07-12 00:38:25 +00007979 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007980 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007981 }
7982 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007983 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007984 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007985
7986 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7987 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007988 if (CheckReferencedDecl(E, E->getDecl()))
7989 return true;
7990
7991 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007992 }
7993 bool VisitMemberExpr(const MemberExpr *E) {
7994 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007995 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007996 return true;
7997 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007998
7999 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008000 }
8001
Peter Collingbournee9200682011-05-13 03:29:01 +00008002 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00008003 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00008004 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00008005 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00008006 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00008007
Peter Collingbournee9200682011-05-13 03:29:01 +00008008 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008009 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00008010
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008011 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008012 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008013 }
Mike Stump11289f42009-09-09 15:08:12 +00008014
Ted Kremeneke65b0862012-03-06 20:05:56 +00008015 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8016 return Success(E->getValue(), E);
8017 }
Richard Smith410306b2016-12-12 02:53:20 +00008018
8019 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8020 if (Info.ArrayInitIndex == uint64_t(-1)) {
8021 // We were asked to evaluate this subexpression independent of the
8022 // enclosing ArrayInitLoopExpr. We can't do that.
8023 Info.FFDiag(E);
8024 return false;
8025 }
8026 return Success(Info.ArrayInitIndex, E);
8027 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008028
Richard Smith4ce706a2011-10-11 21:43:33 +00008029 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00008030 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00008031 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008032 }
8033
Douglas Gregor29c42f22012-02-24 07:38:34 +00008034 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8035 return Success(E->getValue(), E);
8036 }
8037
John Wiegley6242b6a2011-04-28 00:16:57 +00008038 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
8039 return Success(E->getValue(), E);
8040 }
8041
John Wiegleyf9f65842011-04-25 06:54:41 +00008042 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
8043 return Success(E->getValue(), E);
8044 }
8045
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008046 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008047 bool VisitUnaryImag(const UnaryOperator *E);
8048
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008049 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008050 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Eric Fiselier708afb52019-05-16 21:04:15 +00008051 bool VisitSourceLocExpr(const SourceLocExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008052 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00008053};
Leonard Chandb01c3a2018-06-20 17:19:40 +00008054
8055class FixedPointExprEvaluator
8056 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
8057 APValue &Result;
8058
8059 public:
8060 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
8061 : ExprEvaluatorBaseTy(info), Result(result) {}
8062
Leonard Chandb01c3a2018-06-20 17:19:40 +00008063 bool Success(const llvm::APInt &I, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008064 return Success(
8065 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008066 }
8067
Leonard Chandb01c3a2018-06-20 17:19:40 +00008068 bool Success(uint64_t Value, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008069 return Success(
8070 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008071 }
8072
8073 bool Success(const APValue &V, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008074 return Success(V.getFixedPoint(), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008075 }
8076
Leonard Chand3f3e162019-01-18 21:04:25 +00008077 bool Success(const APFixedPoint &V, const Expr *E) {
8078 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
8079 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8080 "Invalid evaluation result.");
8081 Result = APValue(V);
8082 return true;
8083 }
Leonard Chandb01c3a2018-06-20 17:19:40 +00008084
8085 //===--------------------------------------------------------------------===//
8086 // Visitor Methods
8087 //===--------------------------------------------------------------------===//
8088
8089 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
8090 return Success(E->getValue(), E);
8091 }
8092
Leonard Chand3f3e162019-01-18 21:04:25 +00008093 bool VisitCastExpr(const CastExpr *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008094 bool VisitUnaryOperator(const UnaryOperator *E);
Leonard Chand3f3e162019-01-18 21:04:25 +00008095 bool VisitBinaryOperator(const BinaryOperator *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008096};
Chris Lattner05706e882008-07-11 18:11:29 +00008097} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008098
Richard Smith11562c52011-10-28 17:51:58 +00008099/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
8100/// produce either the integer value or a pointer.
8101///
8102/// GCC has a heinous extension which folds casts between pointer types and
8103/// pointer-sized integral types. We support this by allowing the evaluation of
8104/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
8105/// Some simple arithmetic on such values is supported (they are treated much
8106/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00008107static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00008108 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008109 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008110 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00008111}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008112
Richard Smithf57d8cb2011-12-09 22:58:01 +00008113static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00008114 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008115 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00008116 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008117 if (!Val.isInt()) {
8118 // FIXME: It would be better to produce the diagnostic for casting
8119 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00008120 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008121 return false;
8122 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008123 Result = Val.getInt();
8124 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008125}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008126
Eric Fiselier708afb52019-05-16 21:04:15 +00008127bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
8128 APValue Evaluated = E->EvaluateInContext(
8129 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8130 return Success(Evaluated, E);
8131}
8132
Leonard Chand3f3e162019-01-18 21:04:25 +00008133static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
8134 EvalInfo &Info) {
8135 if (E->getType()->isFixedPointType()) {
8136 APValue Val;
8137 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
8138 return false;
8139 if (!Val.isFixedPoint())
8140 return false;
8141
8142 Result = Val.getFixedPoint();
8143 return true;
8144 }
8145 return false;
8146}
8147
8148static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
8149 EvalInfo &Info) {
8150 if (E->getType()->isIntegerType()) {
8151 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
8152 APSInt Val;
8153 if (!EvaluateInteger(E, Val, Info))
8154 return false;
8155 Result = APFixedPoint(Val, FXSema);
8156 return true;
8157 } else if (E->getType()->isFixedPointType()) {
8158 return EvaluateFixedPoint(E, Result, Info);
8159 }
8160 return false;
8161}
8162
Richard Smithf57d8cb2011-12-09 22:58:01 +00008163/// Check whether the given declaration can be directly converted to an integral
8164/// rvalue. If not, no diagnostic is produced; there are other things we can
8165/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008166bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00008167 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00008168 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008169 // Check for signedness/width mismatches between E type and ECD value.
8170 bool SameSign = (ECD->getInitVal().isSigned()
8171 == E->getType()->isSignedIntegerOrEnumerationType());
8172 bool SameWidth = (ECD->getInitVal().getBitWidth()
8173 == Info.Ctx.getIntWidth(E->getType()));
8174 if (SameSign && SameWidth)
8175 return Success(ECD->getInitVal(), E);
8176 else {
8177 // Get rid of mismatch (otherwise Success assertions will fail)
8178 // by computing a new value matching the type of E.
8179 llvm::APSInt Val = ECD->getInitVal();
8180 if (!SameSign)
8181 Val.setIsSigned(!ECD->getInitVal().isSigned());
8182 if (!SameWidth)
8183 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
8184 return Success(Val, E);
8185 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00008186 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008187 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00008188}
8189
Richard Smith08b682b2018-05-23 21:18:00 +00008190/// Values returned by __builtin_classify_type, chosen to match the values
8191/// produced by GCC's builtin.
8192enum class GCCTypeClass {
8193 None = -1,
8194 Void = 0,
8195 Integer = 1,
8196 // GCC reserves 2 for character types, but instead classifies them as
8197 // integers.
8198 Enum = 3,
8199 Bool = 4,
8200 Pointer = 5,
8201 // GCC reserves 6 for references, but appears to never use it (because
8202 // expressions never have reference type, presumably).
8203 PointerToDataMember = 7,
8204 RealFloat = 8,
8205 Complex = 9,
8206 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
8207 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
8208 // GCC claims to reserve 11 for pointers to member functions, but *actually*
8209 // uses 12 for that purpose, same as for a class or struct. Maybe it
8210 // internally implements a pointer to member as a struct? Who knows.
8211 PointerToMemberFunction = 12, // Not a bug, see above.
8212 ClassOrStruct = 12,
8213 Union = 13,
8214 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
8215 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
8216 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
8217 // literals.
8218};
8219
Chris Lattner86ee2862008-10-06 06:40:35 +00008220/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8221/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00008222static GCCTypeClass
8223EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
8224 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00008225
Richard Smith08b682b2018-05-23 21:18:00 +00008226 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008227 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
8228
8229 switch (CanTy->getTypeClass()) {
8230#define TYPE(ID, BASE)
8231#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
8232#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
8233#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
8234#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00008235 case Type::Auto:
8236 case Type::DeducedTemplateSpecialization:
8237 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008238
8239 case Type::Builtin:
8240 switch (BT->getKind()) {
8241#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00008242#define SIGNED_TYPE(ID, SINGLETON_ID) \
8243 case BuiltinType::ID: return GCCTypeClass::Integer;
8244#define FLOATING_TYPE(ID, SINGLETON_ID) \
8245 case BuiltinType::ID: return GCCTypeClass::RealFloat;
8246#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
8247 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008248#include "clang/AST/BuiltinTypes.def"
8249 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00008250 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008251
8252 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00008253 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008254
Richard Smith08b682b2018-05-23 21:18:00 +00008255 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008256 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00008257 case BuiltinType::WChar_U:
8258 case BuiltinType::Char8:
8259 case BuiltinType::Char16:
8260 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008261 case BuiltinType::UShort:
8262 case BuiltinType::UInt:
8263 case BuiltinType::ULong:
8264 case BuiltinType::ULongLong:
8265 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00008266 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008267
Leonard Chanf921d852018-06-04 16:07:52 +00008268 case BuiltinType::UShortAccum:
8269 case BuiltinType::UAccum:
8270 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00008271 case BuiltinType::UShortFract:
8272 case BuiltinType::UFract:
8273 case BuiltinType::ULongFract:
8274 case BuiltinType::SatUShortAccum:
8275 case BuiltinType::SatUAccum:
8276 case BuiltinType::SatULongAccum:
8277 case BuiltinType::SatUShortFract:
8278 case BuiltinType::SatUFract:
8279 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00008280 return GCCTypeClass::None;
8281
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008282 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008283
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008284 case BuiltinType::ObjCId:
8285 case BuiltinType::ObjCClass:
8286 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00008287#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8288 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00008289#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00008290#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8291 case BuiltinType::Id:
8292#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008293 case BuiltinType::OCLSampler:
8294 case BuiltinType::OCLEvent:
8295 case BuiltinType::OCLClkEvent:
8296 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008297 case BuiltinType::OCLReserveID:
Richard Smith08b682b2018-05-23 21:18:00 +00008298 return GCCTypeClass::None;
8299
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008300 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00008301 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008302 };
Richard Smith08b682b2018-05-23 21:18:00 +00008303 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008304
8305 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00008306 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008307
8308 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008309 case Type::ConstantArray:
8310 case Type::VariableArray:
8311 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00008312 case Type::FunctionNoProto:
8313 case Type::FunctionProto:
8314 return GCCTypeClass::Pointer;
8315
8316 case Type::MemberPointer:
8317 return CanTy->isMemberDataPointerType()
8318 ? GCCTypeClass::PointerToDataMember
8319 : GCCTypeClass::PointerToMemberFunction;
8320
8321 case Type::Complex:
8322 return GCCTypeClass::Complex;
8323
8324 case Type::Record:
8325 return CanTy->isUnionType() ? GCCTypeClass::Union
8326 : GCCTypeClass::ClassOrStruct;
8327
8328 case Type::Atomic:
8329 // GCC classifies _Atomic T the same as T.
8330 return EvaluateBuiltinClassifyType(
8331 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008332
8333 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008334 case Type::Vector:
8335 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008336 case Type::ObjCObject:
8337 case Type::ObjCInterface:
8338 case Type::ObjCObjectPointer:
8339 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00008340 // GCC classifies vectors as None. We follow its lead and classify all
8341 // other types that don't fit into the regular classification the same way.
8342 return GCCTypeClass::None;
8343
8344 case Type::LValueReference:
8345 case Type::RValueReference:
8346 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008347 }
8348
Richard Smith08b682b2018-05-23 21:18:00 +00008349 llvm_unreachable("unexpected type class");
8350}
8351
8352/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8353/// as GCC.
8354static GCCTypeClass
8355EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
8356 // If no argument was supplied, default to None. This isn't
8357 // ideal, however it is what gcc does.
8358 if (E->getNumArgs() == 0)
8359 return GCCTypeClass::None;
8360
8361 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
8362 // being an ICE, but still folds it to a constant using the type of the first
8363 // argument.
8364 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00008365}
8366
Richard Smith5fab0c92011-12-28 19:48:30 +00008367/// EvaluateBuiltinConstantPForLValue - Determine the result of
Richard Smith31cfb312019-04-27 02:58:17 +00008368/// __builtin_constant_p when applied to the given pointer.
Richard Smith5fab0c92011-12-28 19:48:30 +00008369///
Richard Smith31cfb312019-04-27 02:58:17 +00008370/// A pointer is only "constant" if it is null (or a pointer cast to integer)
8371/// or it points to the first character of a string literal.
8372static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
8373 APValue::LValueBase Base = LV.getLValueBase();
8374 if (Base.isNull()) {
8375 // A null base is acceptable.
8376 return true;
8377 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
8378 if (!isa<StringLiteral>(E))
8379 return false;
8380 return LV.getLValueOffset().isZero();
Richard Smithee0ce3022019-05-17 07:06:46 +00008381 } else if (Base.is<TypeInfoLValue>()) {
8382 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
8383 // evaluate to true.
8384 return true;
Richard Smith31cfb312019-04-27 02:58:17 +00008385 } else {
8386 // Any other base is not constant enough for GCC.
8387 return false;
8388 }
Richard Smith5fab0c92011-12-28 19:48:30 +00008389}
8390
8391/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
8392/// GCC as we can manage.
Richard Smith31cfb312019-04-27 02:58:17 +00008393static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
Richard Smith37be3362019-05-04 04:00:45 +00008394 // This evaluation is not permitted to have side-effects, so evaluate it in
8395 // a speculative evaluation context.
8396 SpeculativeEvaluationRAII SpeculativeEval(Info);
8397
Richard Smith31cfb312019-04-27 02:58:17 +00008398 // Constant-folding is always enabled for the operand of __builtin_constant_p
8399 // (even when the enclosing evaluation context otherwise requires a strict
8400 // language-specific constant expression).
8401 FoldConstant Fold(Info, true);
8402
Richard Smith5fab0c92011-12-28 19:48:30 +00008403 QualType ArgType = Arg->getType();
8404
8405 // __builtin_constant_p always has one operand. The rules which gcc follows
8406 // are not precisely documented, but are as follows:
8407 //
8408 // - If the operand is of integral, floating, complex or enumeration type,
8409 // and can be folded to a known value of that type, it returns 1.
Richard Smith31cfb312019-04-27 02:58:17 +00008410 // - If the operand can be folded to a pointer to the first character
8411 // of a string literal (or such a pointer cast to an integral type)
8412 // or to a null pointer or an integer cast to a pointer, it returns 1.
Richard Smith5fab0c92011-12-28 19:48:30 +00008413 //
8414 // Otherwise, it returns 0.
8415 //
8416 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
Richard Smith31cfb312019-04-27 02:58:17 +00008417 // its support for this did not work prior to GCC 9 and is not yet well
8418 // understood.
8419 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
8420 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
8421 ArgType->isNullPtrType()) {
8422 APValue V;
8423 if (!::EvaluateAsRValue(Info, Arg, V)) {
8424 Fold.keepDiagnostics();
Richard Smith5fab0c92011-12-28 19:48:30 +00008425 return false;
Richard Smith31cfb312019-04-27 02:58:17 +00008426 }
Richard Smith5fab0c92011-12-28 19:48:30 +00008427
Richard Smith31cfb312019-04-27 02:58:17 +00008428 // For a pointer (possibly cast to integer), there are special rules.
Richard Smith0c6124b2015-12-03 01:36:22 +00008429 if (V.getKind() == APValue::LValue)
8430 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith31cfb312019-04-27 02:58:17 +00008431
8432 // Otherwise, any constant value is good enough.
Richard Smithe637cbe2019-05-21 23:15:18 +00008433 return V.hasValue();
Richard Smith5fab0c92011-12-28 19:48:30 +00008434 }
8435
8436 // Anything else isn't considered to be sufficiently constant.
8437 return false;
8438}
8439
John McCall95007602010-05-10 23:27:23 +00008440/// Retrieves the "underlying object type" of the given expression,
8441/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00008442static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00008443 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
8444 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00008445 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00008446 } else if (const Expr *E = B.get<const Expr*>()) {
8447 if (isa<CompoundLiteralExpr>(E))
8448 return E->getType();
Richard Smithee0ce3022019-05-17 07:06:46 +00008449 } else if (B.is<TypeInfoLValue>()) {
8450 return B.getTypeInfoType();
John McCall95007602010-05-10 23:27:23 +00008451 }
8452
8453 return QualType();
8454}
8455
George Burgess IV3a03fab2015-09-04 21:28:13 +00008456/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00008457/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00008458/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00008459/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
8460///
8461/// Always returns an RValue with a pointer representation.
8462static const Expr *ignorePointerCastsAndParens(const Expr *E) {
8463 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8464
8465 auto *NoParens = E->IgnoreParens();
8466 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00008467 if (Cast == nullptr)
8468 return NoParens;
8469
8470 // We only conservatively allow a few kinds of casts, because this code is
8471 // inherently a simple solution that seeks to support the common case.
8472 auto CastKind = Cast->getCastKind();
8473 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
8474 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00008475 return NoParens;
8476
8477 auto *SubExpr = Cast->getSubExpr();
8478 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
8479 return NoParens;
8480 return ignorePointerCastsAndParens(SubExpr);
8481}
8482
George Burgess IVa51c4072015-10-16 01:49:01 +00008483/// Checks to see if the given LValue's Designator is at the end of the LValue's
8484/// record layout. e.g.
8485/// struct { struct { int a, b; } fst, snd; } obj;
8486/// obj.fst // no
8487/// obj.snd // yes
8488/// obj.fst.a // no
8489/// obj.fst.b // no
8490/// obj.snd.a // no
8491/// obj.snd.b // yes
8492///
8493/// Please note: this function is specialized for how __builtin_object_size
8494/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00008495///
Richard Smith6f4f0f12017-10-20 22:56:25 +00008496/// If this encounters an invalid RecordDecl or otherwise cannot determine the
8497/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00008498static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
8499 assert(!LVal.Designator.Invalid);
8500
George Burgess IV4168d752016-06-27 19:40:41 +00008501 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
8502 const RecordDecl *Parent = FD->getParent();
8503 Invalid = Parent->isInvalidDecl();
8504 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00008505 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00008506 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00008507 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
8508 };
8509
8510 auto &Base = LVal.getLValueBase();
8511 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
8512 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00008513 bool Invalid;
8514 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
8515 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00008516 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00008517 for (auto *FD : IFD->chain()) {
8518 bool Invalid;
8519 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
8520 return Invalid;
8521 }
George Burgess IVa51c4072015-10-16 01:49:01 +00008522 }
8523 }
8524
George Burgess IVe3763372016-12-22 02:50:20 +00008525 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00008526 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00008527 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00008528 // If we don't know the array bound, conservatively assume we're looking at
8529 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00008530 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00008531 if (BaseType->isIncompleteArrayType())
8532 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
8533 else
8534 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00008535 }
8536
8537 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
8538 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00008539 if (BaseType->isArrayType()) {
8540 // Because __builtin_object_size treats arrays as objects, we can ignore
8541 // the index iff this is the last array in the Designator.
8542 if (I + 1 == E)
8543 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00008544 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
Richard Smith5b5e27a2019-05-10 20:05:31 +00008545 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00008546 if (Index + 1 != CAT->getSize())
8547 return false;
8548 BaseType = CAT->getElementType();
8549 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00008550 const auto *CT = BaseType->castAs<ComplexType>();
Richard Smith5b5e27a2019-05-10 20:05:31 +00008551 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00008552 if (Index != 1)
8553 return false;
8554 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00008555 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00008556 bool Invalid;
8557 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
8558 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00008559 BaseType = FD->getType();
8560 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00008561 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00008562 return false;
8563 }
8564 }
8565 return true;
8566}
8567
George Burgess IVe3763372016-12-22 02:50:20 +00008568/// Tests to see if the LValue has a user-specified designator (that isn't
8569/// necessarily valid). Note that this always returns 'true' if the LValue has
8570/// an unsized array as its first designator entry, because there's currently no
8571/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00008572static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00008573 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00008574 return false;
8575
George Burgess IVe3763372016-12-22 02:50:20 +00008576 if (!LVal.Designator.Entries.empty())
8577 return LVal.Designator.isMostDerivedAnUnsizedArray();
8578
George Burgess IVa51c4072015-10-16 01:49:01 +00008579 if (!LVal.InvalidBase)
8580 return true;
8581
George Burgess IVe3763372016-12-22 02:50:20 +00008582 // If `E` is a MemberExpr, then the first part of the designator is hiding in
8583 // the LValueBase.
8584 const auto *E = LVal.Base.dyn_cast<const Expr *>();
8585 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00008586}
8587
George Burgess IVe3763372016-12-22 02:50:20 +00008588/// Attempts to detect a user writing into a piece of memory that's impossible
8589/// to figure out the size of by just using types.
8590static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
8591 const SubobjectDesignator &Designator = LVal.Designator;
8592 // Notes:
8593 // - Users can only write off of the end when we have an invalid base. Invalid
8594 // bases imply we don't know where the memory came from.
8595 // - We used to be a bit more aggressive here; we'd only be conservative if
8596 // the array at the end was flexible, or if it had 0 or 1 elements. This
8597 // broke some common standard library extensions (PR30346), but was
8598 // otherwise seemingly fine. It may be useful to reintroduce this behavior
8599 // with some sort of whitelist. OTOH, it seems that GCC is always
8600 // conservative with the last element in structs (if it's an array), so our
8601 // current behavior is more compatible than a whitelisting approach would
8602 // be.
8603 return LVal.InvalidBase &&
8604 Designator.Entries.size() == Designator.MostDerivedPathLength &&
8605 Designator.MostDerivedIsArrayElement &&
8606 isDesignatorAtObjectEnd(Ctx, LVal);
8607}
8608
8609/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
8610/// Fails if the conversion would cause loss of precision.
8611static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
8612 CharUnits &Result) {
8613 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
8614 if (Int.ugt(CharUnitsMax))
8615 return false;
8616 Result = CharUnits::fromQuantity(Int.getZExtValue());
8617 return true;
8618}
8619
8620/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
8621/// determine how many bytes exist from the beginning of the object to either
8622/// the end of the current subobject, or the end of the object itself, depending
8623/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00008624///
George Burgess IVe3763372016-12-22 02:50:20 +00008625/// If this returns false, the value of Result is undefined.
8626static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
8627 unsigned Type, const LValue &LVal,
8628 CharUnits &EndOffset) {
8629 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008630
George Burgess IV7fb7e362017-01-03 23:35:19 +00008631 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
8632 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
8633 return false;
8634 return HandleSizeof(Info, ExprLoc, Ty, Result);
8635 };
8636
George Burgess IVe3763372016-12-22 02:50:20 +00008637 // We want to evaluate the size of the entire object. This is a valid fallback
8638 // for when Type=1 and the designator is invalid, because we're asked for an
8639 // upper-bound.
8640 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
8641 // Type=3 wants a lower bound, so we can't fall back to this.
8642 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00008643 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00008644
8645 llvm::APInt APEndOffset;
8646 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8647 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8648 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8649
8650 if (LVal.InvalidBase)
8651 return false;
8652
8653 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00008654 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00008655 }
8656
George Burgess IVe3763372016-12-22 02:50:20 +00008657 // We want to evaluate the size of a subobject.
8658 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008659
8660 // The following is a moderately common idiom in C:
8661 //
8662 // struct Foo { int a; char c[1]; };
8663 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8664 // strcpy(&F->c[0], Bar);
8665 //
George Burgess IVe3763372016-12-22 02:50:20 +00008666 // In order to not break too much legacy code, we need to support it.
8667 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8668 // If we can resolve this to an alloc_size call, we can hand that back,
8669 // because we know for certain how many bytes there are to write to.
8670 llvm::APInt APEndOffset;
8671 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8672 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8673 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8674
8675 // If we cannot determine the size of the initial allocation, then we can't
8676 // given an accurate upper-bound. However, we are still able to give
8677 // conservative lower-bounds for Type=3.
8678 if (Type == 1)
8679 return false;
8680 }
8681
8682 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00008683 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008684 return false;
8685
George Burgess IVe3763372016-12-22 02:50:20 +00008686 // According to the GCC documentation, we want the size of the subobject
8687 // denoted by the pointer. But that's not quite right -- what we actually
8688 // want is the size of the immediately-enclosing array, if there is one.
8689 int64_t ElemsRemaining;
8690 if (Designator.MostDerivedIsArrayElement &&
8691 Designator.Entries.size() == Designator.MostDerivedPathLength) {
8692 uint64_t ArraySize = Designator.getMostDerivedArraySize();
Richard Smith5b5e27a2019-05-10 20:05:31 +00008693 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00008694 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8695 } else {
8696 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8697 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008698
George Burgess IVe3763372016-12-22 02:50:20 +00008699 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8700 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008701}
8702
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008703/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00008704/// returns true and stores the result in @p Size.
8705///
8706/// If @p WasError is non-null, this will report whether the failure to evaluate
8707/// is to be treated as an Error in IntExprEvaluator.
8708static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8709 EvalInfo &Info, uint64_t &Size) {
8710 // Determine the denoted object.
8711 LValue LVal;
8712 {
8713 // The operand of __builtin_object_size is never evaluated for side-effects.
8714 // If there are any, but we can determine the pointed-to object anyway, then
8715 // ignore the side-effects.
8716 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00008717 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00008718
8719 if (E->isGLValue()) {
8720 // It's possible for us to be given GLValues if we're called via
8721 // Expr::tryEvaluateObjectSize.
8722 APValue RVal;
8723 if (!EvaluateAsRValue(Info, E, RVal))
8724 return false;
8725 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00008726 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8727 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00008728 return false;
8729 }
8730
8731 // If we point to before the start of the object, there are no accessible
8732 // bytes.
8733 if (LVal.getLValueOffset().isNegative()) {
8734 Size = 0;
8735 return true;
8736 }
8737
8738 CharUnits EndOffset;
8739 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8740 return false;
8741
8742 // If we've fallen outside of the end offset, just pretend there's nothing to
8743 // write to/read from.
8744 if (EndOffset <= LVal.getLValueOffset())
8745 Size = 0;
8746 else
8747 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8748 return true;
John McCall95007602010-05-10 23:27:23 +00008749}
8750
Fangrui Song407659a2018-11-30 23:41:18 +00008751bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
8752 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
8753 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
8754}
8755
Peter Collingbournee9200682011-05-13 03:29:01 +00008756bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00008757 if (unsigned BuiltinOp = E->getBuiltinCallee())
8758 return VisitBuiltinCallExpr(E, BuiltinOp);
8759
8760 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8761}
8762
8763bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8764 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00008765 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008766 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00008767 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00008768
Erik Pilkington9c3b5882019-01-30 20:34:53 +00008769 case Builtin::BI__builtin_dynamic_object_size:
Mike Stump722cedf2009-10-26 18:35:08 +00008770 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00008771 // The type was checked when we built the expression.
8772 unsigned Type =
8773 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8774 assert(Type <= 3 && "unexpected type");
8775
George Burgess IVe3763372016-12-22 02:50:20 +00008776 uint64_t Size;
8777 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8778 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00008779
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008780 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00008781 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00008782
Richard Smith01ade172012-05-23 04:13:20 +00008783 // Expression had no side effects, but we couldn't statically determine the
8784 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008785 switch (Info.EvalMode) {
8786 case EvalInfo::EM_ConstantExpression:
8787 case EvalInfo::EM_PotentialConstantExpression:
8788 case EvalInfo::EM_ConstantFold:
8789 case EvalInfo::EM_EvaluateForOverflow:
8790 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008791 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008792 return Error(E);
8793 case EvalInfo::EM_ConstantExpressionUnevaluated:
8794 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008795 // Reduce it to a constant now.
8796 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008797 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00008798
8799 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00008800 }
8801
Tim Northover314fbfa2018-11-02 13:14:11 +00008802 case Builtin::BI__builtin_os_log_format_buffer_size: {
8803 analyze_os_log::OSLogBufferLayout Layout;
8804 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
8805 return Success(Layout.size().getQuantity(), E);
8806 }
8807
Benjamin Kramera801f4a2012-10-06 14:42:22 +00008808 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00008809 case Builtin::BI__builtin_bswap32:
8810 case Builtin::BI__builtin_bswap64: {
8811 APSInt Val;
8812 if (!EvaluateInteger(E->getArg(0), Val, Info))
8813 return false;
8814
8815 return Success(Val.byteSwap(), E);
8816 }
8817
Richard Smith8889a3d2013-06-13 06:26:32 +00008818 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00008819 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00008820
Craig Topperf95a6d92018-08-08 22:31:12 +00008821 case Builtin::BI__builtin_clrsb:
8822 case Builtin::BI__builtin_clrsbl:
8823 case Builtin::BI__builtin_clrsbll: {
8824 APSInt Val;
8825 if (!EvaluateInteger(E->getArg(0), Val, Info))
8826 return false;
8827
8828 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8829 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008830
Richard Smith80b3c8e2013-06-13 05:04:16 +00008831 case Builtin::BI__builtin_clz:
8832 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008833 case Builtin::BI__builtin_clzll:
8834 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008835 APSInt Val;
8836 if (!EvaluateInteger(E->getArg(0), Val, Info))
8837 return false;
8838 if (!Val)
8839 return Error(E);
8840
8841 return Success(Val.countLeadingZeros(), E);
8842 }
8843
Fangrui Song407659a2018-11-30 23:41:18 +00008844 case Builtin::BI__builtin_constant_p: {
Richard Smith31cfb312019-04-27 02:58:17 +00008845 const Expr *Arg = E->getArg(0);
David Blaikie639b3d12019-05-03 18:11:31 +00008846 if (EvaluateBuiltinConstantP(Info, Arg))
Fangrui Song407659a2018-11-30 23:41:18 +00008847 return Success(true, E);
David Blaikie639b3d12019-05-03 18:11:31 +00008848 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
Richard Smithf7d30482019-05-02 23:21:28 +00008849 // Outside a constant context, eagerly evaluate to false in the presence
8850 // of side-effects in order to avoid -Wunsequenced false-positives in
8851 // a branch on __builtin_constant_p(expr).
Richard Smith31cfb312019-04-27 02:58:17 +00008852 return Success(false, E);
Fangrui Song407659a2018-11-30 23:41:18 +00008853 }
David Blaikie639b3d12019-05-03 18:11:31 +00008854 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8855 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00008856 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008857
Eric Fiselieradd16a82019-04-24 02:23:30 +00008858 case Builtin::BI__builtin_is_constant_evaluated:
8859 return Success(Info.InConstantContext, E);
8860
Richard Smith80b3c8e2013-06-13 05:04:16 +00008861 case Builtin::BI__builtin_ctz:
8862 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008863 case Builtin::BI__builtin_ctzll:
8864 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008865 APSInt Val;
8866 if (!EvaluateInteger(E->getArg(0), Val, Info))
8867 return false;
8868 if (!Val)
8869 return Error(E);
8870
8871 return Success(Val.countTrailingZeros(), E);
8872 }
8873
Richard Smith8889a3d2013-06-13 06:26:32 +00008874 case Builtin::BI__builtin_eh_return_data_regno: {
8875 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8876 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8877 return Success(Operand, E);
8878 }
8879
8880 case Builtin::BI__builtin_expect:
8881 return Visit(E->getArg(0));
8882
8883 case Builtin::BI__builtin_ffs:
8884 case Builtin::BI__builtin_ffsl:
8885 case Builtin::BI__builtin_ffsll: {
8886 APSInt Val;
8887 if (!EvaluateInteger(E->getArg(0), Val, Info))
8888 return false;
8889
8890 unsigned N = Val.countTrailingZeros();
8891 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8892 }
8893
8894 case Builtin::BI__builtin_fpclassify: {
8895 APFloat Val(0.0);
8896 if (!EvaluateFloat(E->getArg(5), Val, Info))
8897 return false;
8898 unsigned Arg;
8899 switch (Val.getCategory()) {
8900 case APFloat::fcNaN: Arg = 0; break;
8901 case APFloat::fcInfinity: Arg = 1; break;
8902 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8903 case APFloat::fcZero: Arg = 4; break;
8904 }
8905 return Visit(E->getArg(Arg));
8906 }
8907
8908 case Builtin::BI__builtin_isinf_sign: {
8909 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00008910 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00008911 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8912 }
8913
Richard Smithea3019d2013-10-15 19:07:14 +00008914 case Builtin::BI__builtin_isinf: {
8915 APFloat Val(0.0);
8916 return EvaluateFloat(E->getArg(0), Val, Info) &&
8917 Success(Val.isInfinity() ? 1 : 0, E);
8918 }
8919
8920 case Builtin::BI__builtin_isfinite: {
8921 APFloat Val(0.0);
8922 return EvaluateFloat(E->getArg(0), Val, Info) &&
8923 Success(Val.isFinite() ? 1 : 0, E);
8924 }
8925
8926 case Builtin::BI__builtin_isnan: {
8927 APFloat Val(0.0);
8928 return EvaluateFloat(E->getArg(0), Val, Info) &&
8929 Success(Val.isNaN() ? 1 : 0, E);
8930 }
8931
8932 case Builtin::BI__builtin_isnormal: {
8933 APFloat Val(0.0);
8934 return EvaluateFloat(E->getArg(0), Val, Info) &&
8935 Success(Val.isNormal() ? 1 : 0, E);
8936 }
8937
Richard Smith8889a3d2013-06-13 06:26:32 +00008938 case Builtin::BI__builtin_parity:
8939 case Builtin::BI__builtin_parityl:
8940 case Builtin::BI__builtin_parityll: {
8941 APSInt Val;
8942 if (!EvaluateInteger(E->getArg(0), Val, Info))
8943 return false;
8944
8945 return Success(Val.countPopulation() % 2, E);
8946 }
8947
Richard Smith80b3c8e2013-06-13 05:04:16 +00008948 case Builtin::BI__builtin_popcount:
8949 case Builtin::BI__builtin_popcountl:
8950 case Builtin::BI__builtin_popcountll: {
8951 APSInt Val;
8952 if (!EvaluateInteger(E->getArg(0), Val, Info))
8953 return false;
8954
8955 return Success(Val.countPopulation(), E);
8956 }
8957
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008958 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00008959 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00008960 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008961 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008962 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00008963 << /*isConstexpr*/0 << /*isConstructor*/0
8964 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00008965 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00008966 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008967 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008968 case Builtin::BI__builtin_strlen:
8969 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00008970 // As an extension, we support __builtin_strlen() as a constant expression,
8971 // and support folding strlen() to a constant.
8972 LValue String;
8973 if (!EvaluatePointer(E->getArg(0), String, Info))
8974 return false;
8975
Richard Smith8110c9d2016-11-29 19:45:17 +00008976 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8977
Richard Smithe6c19f22013-11-15 02:10:04 +00008978 // Fast path: if it's a string literal, search the string value.
8979 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8980 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008981 // The string literal may have embedded null characters. Find the first
8982 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00008983 StringRef Str = S->getBytes();
8984 int64_t Off = String.Offset.getQuantity();
8985 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008986 S->getCharByteWidth() == 1 &&
8987 // FIXME: Add fast-path for wchar_t too.
8988 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00008989 Str = Str.substr(Off);
8990
8991 StringRef::size_type Pos = Str.find(0);
8992 if (Pos != StringRef::npos)
8993 Str = Str.substr(0, Pos);
8994
8995 return Success(Str.size(), E);
8996 }
8997
8998 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008999 }
Richard Smithe6c19f22013-11-15 02:10:04 +00009000
9001 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00009002 for (uint64_t Strlen = 0; /**/; ++Strlen) {
9003 APValue Char;
9004 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9005 !Char.isInt())
9006 return false;
9007 if (!Char.getInt())
9008 return Success(Strlen, E);
9009 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9010 return false;
9011 }
9012 }
Eli Friedmana4c26022011-10-17 21:44:23 +00009013
Richard Smithe151bab2016-11-11 23:43:35 +00009014 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009015 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009016 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009017 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009018 case Builtin::BImemcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00009019 case Builtin::BIbcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009020 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009021 // A call to strlen is not a constant expression.
9022 if (Info.getLangOpts().CPlusPlus11)
9023 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9024 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00009025 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00009026 else
9027 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009028 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00009029 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009030 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009031 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009032 case Builtin::BI__builtin_wcsncmp:
9033 case Builtin::BI__builtin_memcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00009034 case Builtin::BI__builtin_bcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009035 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00009036 LValue String1, String2;
9037 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9038 !EvaluatePointer(E->getArg(1), String2, Info))
9039 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00009040
Richard Smithe151bab2016-11-11 23:43:35 +00009041 uint64_t MaxLength = uint64_t(-1);
9042 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00009043 BuiltinOp != Builtin::BIwcscmp &&
9044 BuiltinOp != Builtin::BI__builtin_strcmp &&
9045 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00009046 APSInt N;
9047 if (!EvaluateInteger(E->getArg(2), N, Info))
9048 return false;
9049 MaxLength = N.getExtValue();
9050 }
Hubert Tong147b7432018-12-12 16:53:43 +00009051
9052 // Empty substrings compare equal by definition.
9053 if (MaxLength == 0u)
9054 return Success(0, E);
9055
9056 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9057 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9058 String1.Designator.Invalid || String2.Designator.Invalid)
9059 return false;
9060
9061 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9062 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9063
9064 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
Clement Courbet8c3343d2019-02-14 12:00:34 +00009065 BuiltinOp == Builtin::BIbcmp ||
9066 BuiltinOp == Builtin::BI__builtin_memcmp ||
9067 BuiltinOp == Builtin::BI__builtin_bcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00009068
9069 assert(IsRawByte ||
9070 (Info.Ctx.hasSameUnqualifiedType(
9071 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9072 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9073
9074 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9075 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9076 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9077 Char1.isInt() && Char2.isInt();
9078 };
9079 const auto &AdvanceElems = [&] {
9080 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9081 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9082 };
9083
9084 if (IsRawByte) {
9085 uint64_t BytesRemaining = MaxLength;
9086 // Pointers to const void may point to objects of incomplete type.
9087 if (CharTy1->isIncompleteType()) {
9088 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9089 return false;
9090 }
9091 if (CharTy2->isIncompleteType()) {
9092 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9093 return false;
9094 }
9095 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9096 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9097 // Give up on comparing between elements with disparate widths.
9098 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9099 return false;
9100 uint64_t BytesPerElement = CharTy1Size.getQuantity();
9101 assert(BytesRemaining && "BytesRemaining should not be zero: the "
9102 "following loop considers at least one element");
9103 while (true) {
9104 APValue Char1, Char2;
9105 if (!ReadCurElems(Char1, Char2))
9106 return false;
9107 // We have compatible in-memory widths, but a possible type and
9108 // (for `bool`) internal representation mismatch.
9109 // Assuming two's complement representation, including 0 for `false` and
9110 // 1 for `true`, we can check an appropriate number of elements for
9111 // equality even if they are not byte-sized.
9112 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9113 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9114 if (Char1InMem.ne(Char2InMem)) {
9115 // If the elements are byte-sized, then we can produce a three-way
9116 // comparison result in a straightforward manner.
9117 if (BytesPerElement == 1u) {
9118 // memcmp always compares unsigned chars.
9119 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9120 }
9121 // The result is byte-order sensitive, and we have multibyte elements.
9122 // FIXME: We can compare the remaining bytes in the correct order.
9123 return false;
9124 }
9125 if (!AdvanceElems())
9126 return false;
9127 if (BytesRemaining <= BytesPerElement)
9128 break;
9129 BytesRemaining -= BytesPerElement;
9130 }
9131 // Enough elements are equal to account for the memcmp limit.
9132 return Success(0, E);
9133 }
9134
Clement Courbet8c3343d2019-02-14 12:00:34 +00009135 bool StopAtNull =
9136 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9137 BuiltinOp != Builtin::BIwmemcmp &&
9138 BuiltinOp != Builtin::BI__builtin_memcmp &&
9139 BuiltinOp != Builtin::BI__builtin_bcmp &&
9140 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00009141 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9142 BuiltinOp == Builtin::BIwcsncmp ||
9143 BuiltinOp == Builtin::BIwmemcmp ||
9144 BuiltinOp == Builtin::BI__builtin_wcscmp ||
9145 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9146 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00009147
Richard Smithe151bab2016-11-11 23:43:35 +00009148 for (; MaxLength; --MaxLength) {
9149 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +00009150 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +00009151 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00009152 if (Char1.getInt() != Char2.getInt()) {
9153 if (IsWide) // wmemcmp compares with wchar_t signedness.
9154 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9155 // memcmp always compares unsigned chars.
9156 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9157 }
Richard Smithe151bab2016-11-11 23:43:35 +00009158 if (StopAtNull && !Char1.getInt())
9159 return Success(0, E);
9160 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +00009161 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +00009162 return false;
9163 }
9164 // We hit the strncmp / memcmp limit.
9165 return Success(0, E);
9166 }
9167
Richard Smith01ba47d2012-04-13 00:45:38 +00009168 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00009169 case Builtin::BI__atomic_is_lock_free:
9170 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00009171 APSInt SizeVal;
9172 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9173 return false;
9174
9175 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9176 // of two less than the maximum inline atomic width, we know it is
9177 // lock-free. If the size isn't a power of two, or greater than the
9178 // maximum alignment where we promote atomics, we know it is not lock-free
9179 // (at least not in the sense of atomic_is_lock_free). Otherwise,
9180 // the answer can only be determined at runtime; for example, 16-byte
9181 // atomics have lock-free implementations on some, but not all,
9182 // x86-64 processors.
9183
9184 // Check power-of-two.
9185 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00009186 if (Size.isPowerOfTwo()) {
9187 // Check against inlining width.
9188 unsigned InlineWidthBits =
9189 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9190 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9191 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9192 Size == CharUnits::One() ||
9193 E->getArg(1)->isNullPointerConstant(Info.Ctx,
9194 Expr::NPC_NeverValueDependent))
9195 // OK, we will inline appropriately-aligned operations of this size,
9196 // and _Atomic(T) is appropriately-aligned.
9197 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00009198
Richard Smith01ba47d2012-04-13 00:45:38 +00009199 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9200 castAs<PointerType>()->getPointeeType();
9201 if (!PointeeType->isIncompleteType() &&
9202 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9203 // OK, we will inline operations on this object.
9204 return Success(1, E);
9205 }
9206 }
9207 }
Eli Friedmana4c26022011-10-17 21:44:23 +00009208
Richard Smith01ba47d2012-04-13 00:45:38 +00009209 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9210 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00009211 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00009212 case Builtin::BIomp_is_initial_device:
9213 // We can decide statically which value the runtime would return if called.
9214 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00009215 case Builtin::BI__builtin_add_overflow:
9216 case Builtin::BI__builtin_sub_overflow:
9217 case Builtin::BI__builtin_mul_overflow:
9218 case Builtin::BI__builtin_sadd_overflow:
9219 case Builtin::BI__builtin_uadd_overflow:
9220 case Builtin::BI__builtin_uaddl_overflow:
9221 case Builtin::BI__builtin_uaddll_overflow:
9222 case Builtin::BI__builtin_usub_overflow:
9223 case Builtin::BI__builtin_usubl_overflow:
9224 case Builtin::BI__builtin_usubll_overflow:
9225 case Builtin::BI__builtin_umul_overflow:
9226 case Builtin::BI__builtin_umull_overflow:
9227 case Builtin::BI__builtin_umulll_overflow:
9228 case Builtin::BI__builtin_saddl_overflow:
9229 case Builtin::BI__builtin_saddll_overflow:
9230 case Builtin::BI__builtin_ssub_overflow:
9231 case Builtin::BI__builtin_ssubl_overflow:
9232 case Builtin::BI__builtin_ssubll_overflow:
9233 case Builtin::BI__builtin_smul_overflow:
9234 case Builtin::BI__builtin_smull_overflow:
9235 case Builtin::BI__builtin_smulll_overflow: {
9236 LValue ResultLValue;
9237 APSInt LHS, RHS;
9238
9239 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9240 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9241 !EvaluateInteger(E->getArg(1), RHS, Info) ||
9242 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9243 return false;
9244
9245 APSInt Result;
9246 bool DidOverflow = false;
9247
9248 // If the types don't have to match, enlarge all 3 to the largest of them.
9249 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9250 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9251 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9252 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9253 ResultType->isSignedIntegerOrEnumerationType();
9254 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9255 ResultType->isSignedIntegerOrEnumerationType();
9256 uint64_t LHSSize = LHS.getBitWidth();
9257 uint64_t RHSSize = RHS.getBitWidth();
9258 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9259 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9260
9261 // Add an additional bit if the signedness isn't uniformly agreed to. We
9262 // could do this ONLY if there is a signed and an unsigned that both have
9263 // MaxBits, but the code to check that is pretty nasty. The issue will be
9264 // caught in the shrink-to-result later anyway.
9265 if (IsSigned && !AllSigned)
9266 ++MaxBits;
9267
9268 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
9269 !IsSigned);
9270 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
9271 !IsSigned);
9272 Result = APSInt(MaxBits, !IsSigned);
9273 }
9274
9275 // Find largest int.
9276 switch (BuiltinOp) {
9277 default:
9278 llvm_unreachable("Invalid value for BuiltinOp");
9279 case Builtin::BI__builtin_add_overflow:
9280 case Builtin::BI__builtin_sadd_overflow:
9281 case Builtin::BI__builtin_saddl_overflow:
9282 case Builtin::BI__builtin_saddll_overflow:
9283 case Builtin::BI__builtin_uadd_overflow:
9284 case Builtin::BI__builtin_uaddl_overflow:
9285 case Builtin::BI__builtin_uaddll_overflow:
9286 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
9287 : LHS.uadd_ov(RHS, DidOverflow);
9288 break;
9289 case Builtin::BI__builtin_sub_overflow:
9290 case Builtin::BI__builtin_ssub_overflow:
9291 case Builtin::BI__builtin_ssubl_overflow:
9292 case Builtin::BI__builtin_ssubll_overflow:
9293 case Builtin::BI__builtin_usub_overflow:
9294 case Builtin::BI__builtin_usubl_overflow:
9295 case Builtin::BI__builtin_usubll_overflow:
9296 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
9297 : LHS.usub_ov(RHS, DidOverflow);
9298 break;
9299 case Builtin::BI__builtin_mul_overflow:
9300 case Builtin::BI__builtin_smul_overflow:
9301 case Builtin::BI__builtin_smull_overflow:
9302 case Builtin::BI__builtin_smulll_overflow:
9303 case Builtin::BI__builtin_umul_overflow:
9304 case Builtin::BI__builtin_umull_overflow:
9305 case Builtin::BI__builtin_umulll_overflow:
9306 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
9307 : LHS.umul_ov(RHS, DidOverflow);
9308 break;
9309 }
9310
9311 // In the case where multiple sizes are allowed, truncate and see if
9312 // the values are the same.
9313 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9314 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9315 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9316 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
9317 // since it will give us the behavior of a TruncOrSelf in the case where
9318 // its parameter <= its size. We previously set Result to be at least the
9319 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
9320 // will work exactly like TruncOrSelf.
9321 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
9322 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
9323
9324 if (!APSInt::isSameValue(Temp, Result))
9325 DidOverflow = true;
9326 Result = Temp;
9327 }
9328
9329 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +00009330 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
9331 return false;
Erich Keane00958272018-06-13 20:43:27 +00009332 return Success(DidOverflow, E);
9333 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009334 }
Chris Lattner7174bf32008-07-12 00:38:25 +00009335}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009336
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009337/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +00009338/// object referred to by the lvalue.
9339static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
9340 const LValue &LV) {
9341 // A null pointer can be viewed as being "past the end" but we don't
9342 // choose to look at it that way here.
9343 if (!LV.getLValueBase())
9344 return false;
9345
9346 // If the designator is valid and refers to a subobject, we're not pointing
9347 // past the end.
9348 if (!LV.getLValueDesignator().Invalid &&
9349 !LV.getLValueDesignator().isOnePastTheEnd())
9350 return false;
9351
David Majnemerc378ca52015-08-29 08:32:55 +00009352 // A pointer to an incomplete type might be past-the-end if the type's size is
9353 // zero. We cannot tell because the type is incomplete.
9354 QualType Ty = getType(LV.getLValueBase());
9355 if (Ty->isIncompleteType())
9356 return true;
9357
Richard Smithd20f1e62014-10-21 23:01:04 +00009358 // We're a past-the-end pointer if we point to the byte after the object,
9359 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00009360 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00009361 return LV.getLValueOffset() == Size;
9362}
9363
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009364namespace {
Richard Smith11562c52011-10-28 17:51:58 +00009365
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009366/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009367///
9368/// We use a data recursive algorithm for binary operators so that we are able
9369/// to handle extreme cases of chained binary operators without causing stack
9370/// overflow.
9371class DataRecursiveIntBinOpEvaluator {
9372 struct EvalResult {
9373 APValue Val;
9374 bool Failed;
9375
9376 EvalResult() : Failed(false) { }
9377
9378 void swap(EvalResult &RHS) {
9379 Val.swap(RHS.Val);
9380 Failed = RHS.Failed;
9381 RHS.Failed = false;
9382 }
9383 };
9384
9385 struct Job {
9386 const Expr *E;
9387 EvalResult LHSResult; // meaningful only for binary operator expression.
9388 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00009389
David Blaikie73726062015-08-12 23:09:24 +00009390 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00009391 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00009392
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009393 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00009394 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009395 }
George Burgess IV8c892b52016-05-25 22:31:54 +00009396
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009397 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00009398 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009399 };
9400
9401 SmallVector<Job, 16> Queue;
9402
9403 IntExprEvaluator &IntEval;
9404 EvalInfo &Info;
9405 APValue &FinalResult;
9406
9407public:
9408 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
9409 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
9410
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009411 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009412 /// data recursively.
9413 /// We handle binary operators that are comma, logical, or that have operands
9414 /// with integral or enumeration type.
9415 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009416 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
9417 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +00009418 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009419 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00009420 }
9421
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009422 bool Traverse(const BinaryOperator *E) {
9423 enqueue(E);
9424 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00009425 while (!Queue.empty())
9426 process(PrevResult);
9427
9428 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009429
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009430 FinalResult.swap(PrevResult.Val);
9431 return true;
9432 }
9433
9434private:
9435 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
9436 return IntEval.Success(Value, E, Result);
9437 }
9438 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
9439 return IntEval.Success(Value, E, Result);
9440 }
9441 bool Error(const Expr *E) {
9442 return IntEval.Error(E);
9443 }
9444 bool Error(const Expr *E, diag::kind D) {
9445 return IntEval.Error(E, D);
9446 }
9447
9448 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
9449 return Info.CCEDiag(E, D);
9450 }
9451
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009452 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009453 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009454 bool &SuppressRHSDiags);
9455
9456 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
9457 const BinaryOperator *E, APValue &Result);
9458
9459 void EvaluateExpr(const Expr *E, EvalResult &Result) {
9460 Result.Failed = !Evaluate(Result.Val, Info, E);
9461 if (Result.Failed)
9462 Result.Val = APValue();
9463 }
9464
Richard Trieuba4d0872012-03-21 23:30:30 +00009465 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009466
9467 void enqueue(const Expr *E) {
9468 E = E->IgnoreParens();
9469 Queue.resize(Queue.size()+1);
9470 Queue.back().E = E;
9471 Queue.back().Kind = Job::AnyExprKind;
9472 }
9473};
9474
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009475}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009476
9477bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009478 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009479 bool &SuppressRHSDiags) {
9480 if (E->getOpcode() == BO_Comma) {
9481 // Ignore LHS but note if we could not evaluate it.
9482 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00009483 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009484 return true;
9485 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00009486
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009487 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00009488 bool LHSAsBool;
9489 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009490 // We were able to evaluate the LHS, see if we can get away with not
9491 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00009492 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
9493 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009494 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009495 }
9496 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00009497 LHSResult.Failed = true;
9498
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009499 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00009500 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00009501 if (!Info.noteSideEffect())
9502 return false;
9503
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009504 // We can't evaluate the LHS; however, sometimes the result
9505 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9506 // Don't ignore RHS and suppress diagnostics from this arm.
9507 SuppressRHSDiags = true;
9508 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00009509
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009510 return true;
9511 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00009512
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009513 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9514 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00009515
George Burgess IVa145e252016-05-25 22:38:36 +00009516 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009517 return false; // Ignore RHS;
9518
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009519 return true;
9520}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009521
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00009522static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
9523 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00009524 // Compute the new offset in the appropriate width, wrapping at 64 bits.
9525 // FIXME: When compiling for a 32-bit target, we should use 32-bit
9526 // offsets.
9527 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
9528 CharUnits &Offset = LVal.getLValueOffset();
9529 uint64_t Offset64 = Offset.getQuantity();
9530 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
9531 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
9532 : Offset64 + Index64);
9533}
9534
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009535bool DataRecursiveIntBinOpEvaluator::
9536 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
9537 const BinaryOperator *E, APValue &Result) {
9538 if (E->getOpcode() == BO_Comma) {
9539 if (RHSResult.Failed)
9540 return false;
9541 Result = RHSResult.Val;
9542 return true;
9543 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009544
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009545 if (E->isLogicalOp()) {
9546 bool lhsResult, rhsResult;
9547 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
9548 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +00009549
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009550 if (LHSIsOK) {
9551 if (RHSIsOK) {
9552 if (E->getOpcode() == BO_LOr)
9553 return Success(lhsResult || rhsResult, E, Result);
9554 else
9555 return Success(lhsResult && rhsResult, E, Result);
9556 }
9557 } else {
9558 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009559 // We can't evaluate the LHS; however, sometimes the result
9560 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9561 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009562 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009563 }
9564 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009565
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009566 return false;
9567 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009568
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009569 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9570 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +00009571
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009572 if (LHSResult.Failed || RHSResult.Failed)
9573 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009574
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009575 const APValue &LHSVal = LHSResult.Val;
9576 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +00009577
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009578 // Handle cases like (unsigned long)&a + 4.
9579 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
9580 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00009581 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009582 return true;
9583 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009584
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009585 // Handle cases like 4 + (unsigned long)&a
9586 if (E->getOpcode() == BO_Add &&
9587 RHSVal.isLValue() && LHSVal.isInt()) {
9588 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00009589 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009590 return true;
9591 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009592
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009593 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
9594 // Handle (intptr_t)&&A - (intptr_t)&&B.
9595 if (!LHSVal.getLValueOffset().isZero() ||
9596 !RHSVal.getLValueOffset().isZero())
9597 return false;
9598 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
9599 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
9600 if (!LHSExpr || !RHSExpr)
9601 return false;
9602 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9603 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9604 if (!LHSAddrExpr || !RHSAddrExpr)
9605 return false;
9606 // Make sure both labels come from the same function.
9607 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9608 RHSAddrExpr->getLabel()->getDeclContext())
9609 return false;
9610 Result = APValue(LHSAddrExpr, RHSAddrExpr);
9611 return true;
9612 }
Richard Smith43e77732013-05-07 04:50:00 +00009613
9614 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009615 if (!LHSVal.isInt() || !RHSVal.isInt())
9616 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00009617
9618 // Set up the width and signedness manually, in case it can't be deduced
9619 // from the operation we're performing.
9620 // FIXME: Don't do this in the cases where we can deduce it.
9621 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
9622 E->getType()->isUnsignedIntegerOrEnumerationType());
9623 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
9624 RHSVal.getInt(), Value))
9625 return false;
9626 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009627}
9628
Richard Trieuba4d0872012-03-21 23:30:30 +00009629void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009630 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +00009631
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009632 switch (job.Kind) {
9633 case Job::AnyExprKind: {
9634 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
9635 if (shouldEnqueue(Bop)) {
9636 job.Kind = Job::BinOpKind;
9637 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009638 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009639 }
9640 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009641
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009642 EvaluateExpr(job.E, Result);
9643 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009644 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009645 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009646
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009647 case Job::BinOpKind: {
9648 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009649 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009650 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009651 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009652 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009653 }
9654 if (SuppressRHSDiags)
9655 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009656 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009657 job.Kind = Job::BinOpVisitedLHSKind;
9658 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009659 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009660 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009661
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009662 case Job::BinOpVisitedLHSKind: {
9663 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9664 EvalResult RHS;
9665 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00009666 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009667 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009668 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009669 }
9670 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009671
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009672 llvm_unreachable("Invalid Job::Kind!");
9673}
9674
George Burgess IV8c892b52016-05-25 22:31:54 +00009675namespace {
9676/// Used when we determine that we should fail, but can keep evaluating prior to
9677/// noting that we had a failure.
9678class DelayedNoteFailureRAII {
9679 EvalInfo &Info;
9680 bool NoteFailure;
9681
9682public:
9683 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
9684 : Info(Info), NoteFailure(NoteFailure) {}
9685 ~DelayedNoteFailureRAII() {
9686 if (NoteFailure) {
9687 bool ContinueAfterFailure = Info.noteFailure();
9688 (void)ContinueAfterFailure;
9689 assert(ContinueAfterFailure &&
9690 "Shouldn't have kept evaluating on failure.");
9691 }
9692 }
9693};
9694}
9695
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009696template <class SuccessCB, class AfterCB>
9697static bool
9698EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
9699 SuccessCB &&Success, AfterCB &&DoAfter) {
9700 assert(E->isComparisonOp() && "expected comparison operator");
9701 assert((E->getOpcode() == BO_Cmp ||
9702 E->getType()->isIntegralOrEnumerationType()) &&
9703 "unsupported binary expression evaluation");
9704 auto Error = [&](const Expr *E) {
9705 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9706 return false;
9707 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009708
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009709 using CCR = ComparisonCategoryResult;
9710 bool IsRelational = E->isRelationalOp();
9711 bool IsEquality = E->isEqualityOp();
9712 if (E->getOpcode() == BO_Cmp) {
9713 const ComparisonCategoryInfo &CmpInfo =
9714 Info.Ctx.CompCategories.getInfoForType(E->getType());
9715 IsRelational = CmpInfo.isOrdered();
9716 IsEquality = CmpInfo.isEquality();
9717 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00009718
Anders Carlssonacc79812008-11-16 07:17:21 +00009719 QualType LHSTy = E->getLHS()->getType();
9720 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009721
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009722 if (LHSTy->isIntegralOrEnumerationType() &&
9723 RHSTy->isIntegralOrEnumerationType()) {
9724 APSInt LHS, RHS;
9725 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
9726 if (!LHSOK && !Info.noteFailure())
9727 return false;
9728 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
9729 return false;
9730 if (LHS < RHS)
9731 return Success(CCR::Less, E);
9732 if (LHS > RHS)
9733 return Success(CCR::Greater, E);
9734 return Success(CCR::Equal, E);
9735 }
9736
Leonard Chance1d4f12019-02-21 20:50:09 +00009737 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
9738 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
9739 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
9740
9741 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
9742 if (!LHSOK && !Info.noteFailure())
9743 return false;
9744 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
9745 return false;
9746 if (LHSFX < RHSFX)
9747 return Success(CCR::Less, E);
9748 if (LHSFX > RHSFX)
9749 return Success(CCR::Greater, E);
9750 return Success(CCR::Equal, E);
9751 }
9752
Chandler Carruthb29a7432014-10-11 11:03:30 +00009753 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009754 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00009755 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00009756 if (E->isAssignmentOp()) {
9757 LValue LV;
9758 EvaluateLValue(E->getLHS(), LV, Info);
9759 LHSOK = false;
9760 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00009761 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
9762 if (LHSOK) {
9763 LHS.makeComplexFloat();
9764 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
9765 }
9766 } else {
9767 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
9768 }
George Burgess IVa145e252016-05-25 22:38:36 +00009769 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009770 return false;
9771
Chandler Carruthb29a7432014-10-11 11:03:30 +00009772 if (E->getRHS()->getType()->isRealFloatingType()) {
9773 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
9774 return false;
9775 RHS.makeComplexFloat();
9776 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
9777 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009778 return false;
9779
9780 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00009781 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009782 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00009783 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009784 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009785 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9786 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009787 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009788 assert(IsEquality && "invalid complex comparison");
9789 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
9790 LHS.getComplexIntImag() == RHS.getComplexIntImag();
9791 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009792 }
9793 }
Mike Stump11289f42009-09-09 15:08:12 +00009794
Anders Carlssonacc79812008-11-16 07:17:21 +00009795 if (LHSTy->isRealFloatingType() &&
9796 RHSTy->isRealFloatingType()) {
9797 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00009798
Richard Smith253c2a32012-01-27 01:14:48 +00009799 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009800 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00009801 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009802
Richard Smith253c2a32012-01-27 01:14:48 +00009803 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00009804 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009805
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009806 assert(E->isComparisonOp() && "Invalid binary operator!");
9807 auto GetCmpRes = [&]() {
9808 switch (LHS.compare(RHS)) {
9809 case APFloat::cmpEqual:
9810 return CCR::Equal;
9811 case APFloat::cmpLessThan:
9812 return CCR::Less;
9813 case APFloat::cmpGreaterThan:
9814 return CCR::Greater;
9815 case APFloat::cmpUnordered:
9816 return CCR::Unordered;
9817 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +00009818 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009819 };
9820 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +00009821 }
Mike Stump11289f42009-09-09 15:08:12 +00009822
Eli Friedmana38da572009-04-28 19:17:36 +00009823 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009824 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +00009825
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009826 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9827 if (!LHSOK && !Info.noteFailure())
9828 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009829
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009830 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9831 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009832
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009833 // Reject differing bases from the normal codepath; we special-case
9834 // comparisons to null.
9835 if (!HasSameBase(LHSValue, RHSValue)) {
9836 // Inequalities and subtractions between unrelated pointers have
9837 // unspecified or undefined behavior.
9838 if (!IsEquality)
9839 return Error(E);
9840 // A constant address may compare equal to the address of a symbol.
9841 // The one exception is that address of an object cannot compare equal
9842 // to a null pointer constant.
9843 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9844 (!RHSValue.Base && !RHSValue.Offset.isZero()))
9845 return Error(E);
9846 // It's implementation-defined whether distinct literals will have
9847 // distinct addresses. In clang, the result of such a comparison is
9848 // unspecified, so it is not a constant expression. However, we do know
9849 // that the address of a literal will be non-null.
9850 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9851 LHSValue.Base && RHSValue.Base)
9852 return Error(E);
9853 // We can't tell whether weak symbols will end up pointing to the same
9854 // object.
9855 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9856 return Error(E);
9857 // We can't compare the address of the start of one object with the
9858 // past-the-end address of another object, per C++ DR1652.
9859 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9860 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9861 (RHSValue.Base && RHSValue.Offset.isZero() &&
9862 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9863 return Error(E);
9864 // We can't tell whether an object is at the same address as another
9865 // zero sized object.
9866 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9867 (LHSValue.Base && isZeroSized(RHSValue)))
9868 return Error(E);
9869 return Success(CCR::Nonequal, E);
9870 }
Eli Friedman64004332009-03-23 04:38:34 +00009871
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009872 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9873 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +00009874
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009875 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9876 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +00009877
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009878 // C++11 [expr.rel]p3:
9879 // Pointers to void (after pointer conversions) can be compared, with a
9880 // result defined as follows: If both pointers represent the same
9881 // address or are both the null pointer value, the result is true if the
9882 // operator is <= or >= and false otherwise; otherwise the result is
9883 // unspecified.
9884 // We interpret this as applying to pointers to *cv* void.
9885 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9886 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +00009887
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009888 // C++11 [expr.rel]p2:
9889 // - If two pointers point to non-static data members of the same object,
9890 // or to subobjects or array elements fo such members, recursively, the
9891 // pointer to the later declared member compares greater provided the
9892 // two members have the same access control and provided their class is
9893 // not a union.
9894 // [...]
9895 // - Otherwise pointer comparisons are unspecified.
9896 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9897 bool WasArrayIndex;
9898 unsigned Mismatch = FindDesignatorMismatch(
9899 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9900 // At the point where the designators diverge, the comparison has a
9901 // specified value if:
9902 // - we are comparing array indices
9903 // - we are comparing fields of a union, or fields with the same access
9904 // Otherwise, the result is unspecified and thus the comparison is not a
9905 // constant expression.
9906 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9907 Mismatch < RHSDesignator.Entries.size()) {
9908 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9909 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9910 if (!LF && !RF)
9911 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9912 else if (!LF)
9913 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009914 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9915 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009916 else if (!RF)
9917 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009918 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9919 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009920 else if (!LF->getParent()->isUnion() &&
9921 LF->getAccess() != RF->getAccess())
9922 Info.CCEDiag(E,
9923 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009924 << LF << LF->getAccess() << RF << RF->getAccess()
9925 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +00009926 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009927 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009928
9929 // The comparison here must be unsigned, and performed with the same
9930 // width as the pointer.
9931 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9932 uint64_t CompareLHS = LHSOffset.getQuantity();
9933 uint64_t CompareRHS = RHSOffset.getQuantity();
9934 assert(PtrSize <= 64 && "Unexpected pointer width");
9935 uint64_t Mask = ~0ULL >> (64 - PtrSize);
9936 CompareLHS &= Mask;
9937 CompareRHS &= Mask;
9938
9939 // If there is a base and this is a relational operator, we can only
9940 // compare pointers within the object in question; otherwise, the result
9941 // depends on where the object is located in memory.
9942 if (!LHSValue.Base.isNull() && IsRelational) {
9943 QualType BaseTy = getType(LHSValue.Base);
9944 if (BaseTy->isIncompleteType())
9945 return Error(E);
9946 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9947 uint64_t OffsetLimit = Size.getQuantity();
9948 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9949 return Error(E);
9950 }
9951
9952 if (CompareLHS < CompareRHS)
9953 return Success(CCR::Less, E);
9954 if (CompareLHS > CompareRHS)
9955 return Success(CCR::Greater, E);
9956 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009957 }
Richard Smith7bb00672012-02-01 01:42:44 +00009958
9959 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009960 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +00009961 assert(RHSTy->isMemberPointerType() && "invalid comparison");
9962
9963 MemberPtr LHSValue, RHSValue;
9964
9965 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009966 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00009967 return false;
9968
9969 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9970 return false;
9971
9972 // C++11 [expr.eq]p2:
9973 // If both operands are null, they compare equal. Otherwise if only one is
9974 // null, they compare unequal.
9975 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9976 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009977 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009978 }
9979
9980 // Otherwise if either is a pointer to a virtual member function, the
9981 // result is unspecified.
9982 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9983 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009984 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009985 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9986 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009987 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009988
9989 // Otherwise they compare equal if and only if they would refer to the
9990 // same member of the same most derived object or the same subobject if
9991 // they were dereferenced with a hypothetical object of the associated
9992 // class type.
9993 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009994 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009995 }
9996
Richard Smithab44d9b2012-02-14 22:35:28 +00009997 if (LHSTy->isNullPtrType()) {
9998 assert(E->isComparisonOp() && "unexpected nullptr operation");
9999 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10000 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10001 // are compared, the result is true of the operator is <=, >= or ==, and
10002 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010003 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +000010004 }
10005
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010006 return DoAfter();
10007}
10008
10009bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10010 if (!CheckLiteralType(Info, E))
10011 return false;
10012
10013 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10014 const BinaryOperator *E) {
10015 // Evaluation succeeded. Lookup the information for the comparison category
10016 // type and fetch the VarDecl for the result.
10017 const ComparisonCategoryInfo &CmpInfo =
10018 Info.Ctx.CompCategories.getInfoForType(E->getType());
10019 const VarDecl *VD =
10020 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10021 // Check and evaluate the result as a constant expression.
10022 LValue LV;
10023 LV.set(VD);
10024 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10025 return false;
10026 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10027 };
10028 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10029 return ExprEvaluatorBaseTy::VisitBinCmp(E);
10030 });
10031}
10032
10033bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10034 // We don't call noteFailure immediately because the assignment happens after
10035 // we evaluate LHS and RHS.
10036 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10037 return Error(E);
10038
10039 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10040 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10041 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10042
10043 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10044 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010045 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010046
10047 if (E->isComparisonOp()) {
10048 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10049 // comparisons and then translating the result.
10050 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10051 const BinaryOperator *E) {
10052 using CCR = ComparisonCategoryResult;
10053 bool IsEqual = ResKind == CCR::Equal,
10054 IsLess = ResKind == CCR::Less,
10055 IsGreater = ResKind == CCR::Greater;
10056 auto Op = E->getOpcode();
10057 switch (Op) {
10058 default:
10059 llvm_unreachable("unsupported binary operator");
10060 case BO_EQ:
10061 case BO_NE:
10062 return Success(IsEqual == (Op == BO_EQ), E);
10063 case BO_LT: return Success(IsLess, E);
10064 case BO_GT: return Success(IsGreater, E);
10065 case BO_LE: return Success(IsEqual || IsLess, E);
10066 case BO_GE: return Success(IsEqual || IsGreater, E);
10067 }
10068 };
10069 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10070 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10071 });
10072 }
10073
10074 QualType LHSTy = E->getLHS()->getType();
10075 QualType RHSTy = E->getRHS()->getType();
10076
10077 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10078 E->getOpcode() == BO_Sub) {
10079 LValue LHSValue, RHSValue;
10080
10081 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10082 if (!LHSOK && !Info.noteFailure())
10083 return false;
10084
10085 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10086 return false;
10087
10088 // Reject differing bases from the normal codepath; we special-case
10089 // comparisons to null.
10090 if (!HasSameBase(LHSValue, RHSValue)) {
10091 // Handle &&A - &&B.
10092 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10093 return Error(E);
10094 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10095 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10096 if (!LHSExpr || !RHSExpr)
10097 return Error(E);
10098 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10099 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10100 if (!LHSAddrExpr || !RHSAddrExpr)
10101 return Error(E);
10102 // Make sure both labels come from the same function.
10103 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10104 RHSAddrExpr->getLabel()->getDeclContext())
10105 return Error(E);
10106 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10107 }
10108 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10109 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10110
10111 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10112 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10113
10114 // C++11 [expr.add]p6:
10115 // Unless both pointers point to elements of the same array object, or
10116 // one past the last element of the array object, the behavior is
10117 // undefined.
10118 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10119 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10120 RHSDesignator))
10121 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10122
10123 QualType Type = E->getLHS()->getType();
10124 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10125
10126 CharUnits ElementSize;
10127 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10128 return false;
10129
10130 // As an extension, a type may have zero size (empty struct or union in
10131 // C, array of zero length). Pointer subtraction in such cases has
10132 // undefined behavior, so is not constant.
10133 if (ElementSize.isZero()) {
10134 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10135 << ElementType;
10136 return false;
10137 }
10138
10139 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10140 // and produce incorrect results when it overflows. Such behavior
10141 // appears to be non-conforming, but is common, so perhaps we should
10142 // assume the standard intended for such cases to be undefined behavior
10143 // and check for them.
10144
10145 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10146 // overflow in the final conversion to ptrdiff_t.
10147 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10148 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10149 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10150 false);
10151 APSInt TrueResult = (LHS - RHS) / ElemSize;
10152 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
10153
10154 if (Result.extend(65) != TrueResult &&
10155 !HandleOverflow(Info, E, TrueResult, E->getType()))
10156 return false;
10157 return Success(Result, E);
10158 }
10159
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010160 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +000010161}
10162
Peter Collingbournee190dee2011-03-11 19:24:49 +000010163/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10164/// a result as the expression's type.
10165bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10166 const UnaryExprOrTypeTraitExpr *E) {
10167 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +000010168 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +000010169 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +000010170 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +000010171 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10172 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000010173 else
Richard Smith6822bd72018-10-26 19:26:45 +000010174 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10175 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000010176 }
Eli Friedman64004332009-03-23 04:38:34 +000010177
Peter Collingbournee190dee2011-03-11 19:24:49 +000010178 case UETT_VecStep: {
10179 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +000010180
Peter Collingbournee190dee2011-03-11 19:24:49 +000010181 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +000010182 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +000010183
Peter Collingbournee190dee2011-03-11 19:24:49 +000010184 // The vec_step built-in functions that take a 3-component
10185 // vector return 4. (OpenCL 1.1 spec 6.11.12)
10186 if (n == 3)
10187 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +000010188
Peter Collingbournee190dee2011-03-11 19:24:49 +000010189 return Success(n, E);
10190 } else
10191 return Success(1, E);
10192 }
10193
10194 case UETT_SizeOf: {
10195 QualType SrcTy = E->getTypeOfArgument();
10196 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10197 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +000010198 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10199 SrcTy = Ref->getPointeeType();
10200
Richard Smithd62306a2011-11-10 06:34:14 +000010201 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +000010202 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +000010203 return false;
Richard Smithd62306a2011-11-10 06:34:14 +000010204 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000010205 }
Alexey Bataev00396512015-07-02 03:40:19 +000010206 case UETT_OpenMPRequiredSimdAlign:
10207 assert(E->isArgumentType());
10208 return Success(
10209 Info.Ctx.toCharUnitsFromBits(
10210 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10211 .getQuantity(),
10212 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000010213 }
10214
10215 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +000010216}
10217
Peter Collingbournee9200682011-05-13 03:29:01 +000010218bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +000010219 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +000010220 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +000010221 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010222 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +000010223 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +000010224 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +000010225 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +000010226 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +000010227 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +000010228 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +000010229 APSInt IdxResult;
10230 if (!EvaluateInteger(Idx, IdxResult, Info))
10231 return false;
10232 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10233 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010234 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010235 CurrentType = AT->getElementType();
10236 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10237 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +000010238 break;
Douglas Gregor882211c2010-04-28 22:16:22 +000010239 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010240
James Y Knight7281c352015-12-29 22:31:18 +000010241 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +000010242 FieldDecl *MemberDecl = ON.getField();
10243 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000010244 if (!RT)
10245 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010246 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000010247 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +000010248 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +000010249 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +000010250 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +000010251 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +000010252 CurrentType = MemberDecl->getType().getNonReferenceType();
10253 break;
10254 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010255
James Y Knight7281c352015-12-29 22:31:18 +000010256 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +000010257 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +000010258
James Y Knight7281c352015-12-29 22:31:18 +000010259 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +000010260 CXXBaseSpecifier *BaseSpec = ON.getBase();
10261 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +000010262 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000010263
10264 // Find the layout of the class whose base we are looking into.
10265 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000010266 if (!RT)
10267 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000010268 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000010269 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +000010270 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10271
10272 // Find the base class itself.
10273 CurrentType = BaseSpec->getType();
10274 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10275 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010276 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +000010277
Douglas Gregord1702062010-04-29 00:18:15 +000010278 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +000010279 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +000010280 break;
10281 }
Douglas Gregor882211c2010-04-28 22:16:22 +000010282 }
10283 }
Peter Collingbournee9200682011-05-13 03:29:01 +000010284 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010285}
10286
Chris Lattnere13042c2008-07-11 19:10:17 +000010287bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010288 switch (E->getOpcode()) {
10289 default:
10290 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
10291 // See C99 6.6p3.
10292 return Error(E);
10293 case UO_Extension:
10294 // FIXME: Should extension allow i-c-e extension expressions in its scope?
10295 // If so, we could clear the diagnostic ID.
10296 return Visit(E->getSubExpr());
10297 case UO_Plus:
10298 // The result is just the value.
10299 return Visit(E->getSubExpr());
10300 case UO_Minus: {
10301 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +000010302 return false;
10303 if (!Result.isInt()) return Error(E);
10304 const APSInt &Value = Result.getInt();
10305 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
10306 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
10307 E->getType()))
10308 return false;
Richard Smithfe800032012-01-31 04:08:20 +000010309 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010310 }
10311 case UO_Not: {
10312 if (!Visit(E->getSubExpr()))
10313 return false;
10314 if (!Result.isInt()) return Error(E);
10315 return Success(~Result.getInt(), E);
10316 }
10317 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +000010318 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +000010319 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +000010320 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +000010321 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +000010322 }
Anders Carlsson9c181652008-07-08 14:35:21 +000010323 }
Anders Carlsson9c181652008-07-08 14:35:21 +000010324}
Mike Stump11289f42009-09-09 15:08:12 +000010325
Chris Lattner477c4be2008-07-12 01:15:53 +000010326/// HandleCast - This is used to evaluate implicit or explicit casts where the
10327/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +000010328bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
10329 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000010330 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +000010331 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000010332
Eli Friedmanc757de22011-03-25 00:43:55 +000010333 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +000010334 case CK_BaseToDerived:
10335 case CK_DerivedToBase:
10336 case CK_UncheckedDerivedToBase:
10337 case CK_Dynamic:
10338 case CK_ToUnion:
10339 case CK_ArrayToPointerDecay:
10340 case CK_FunctionToPointerDecay:
10341 case CK_NullToPointer:
10342 case CK_NullToMemberPointer:
10343 case CK_BaseToDerivedMemberPointer:
10344 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +000010345 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +000010346 case CK_ConstructorConversion:
10347 case CK_IntegralToPointer:
10348 case CK_ToVoid:
10349 case CK_VectorSplat:
10350 case CK_IntegralToFloating:
10351 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000010352 case CK_CPointerToObjCPointerCast:
10353 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000010354 case CK_AnyPointerToBlockPointerCast:
10355 case CK_ObjCObjectLValueCast:
10356 case CK_FloatingRealToComplex:
10357 case CK_FloatingComplexToReal:
10358 case CK_FloatingComplexCast:
10359 case CK_FloatingComplexToIntegralComplex:
10360 case CK_IntegralRealToComplex:
10361 case CK_IntegralComplexCast:
10362 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +000010363 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000010364 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000010365 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000010366 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000010367 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000010368 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +000010369 case CK_IntegralToFixedPoint:
Eli Friedmanc757de22011-03-25 00:43:55 +000010370 llvm_unreachable("invalid cast kind for integral value");
10371
Eli Friedman9faf2f92011-03-25 19:07:11 +000010372 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000010373 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000010374 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +000010375 case CK_ARCProduceObject:
10376 case CK_ARCConsumeObject:
10377 case CK_ARCReclaimReturnedObject:
10378 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000010379 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010380 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000010381
Richard Smith4ef685b2012-01-17 21:17:26 +000010382 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +000010383 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010384 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +000010385 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +000010386 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000010387
10388 case CK_MemberPointerToBoolean:
10389 case CK_PointerToBoolean:
10390 case CK_IntegralToBoolean:
10391 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +000010392 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +000010393 case CK_FloatingComplexToBoolean:
10394 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010395 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +000010396 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +000010397 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +000010398 uint64_t IntResult = BoolResult;
10399 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
10400 IntResult = (uint64_t)-1;
10401 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +000010402 }
10403
Leonard Chan8f7caae2019-03-06 00:28:43 +000010404 case CK_FixedPointToIntegral: {
10405 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
10406 if (!EvaluateFixedPoint(SubExpr, Src, Info))
10407 return false;
10408 bool Overflowed;
10409 llvm::APSInt Result = Src.convertToInt(
10410 Info.Ctx.getIntWidth(DestType),
10411 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
10412 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
10413 return false;
10414 return Success(Result, E);
10415 }
10416
Leonard Chanb4ba4672018-10-23 17:55:35 +000010417 case CK_FixedPointToBoolean: {
10418 // Unsigned padding does not affect this.
10419 APValue Val;
10420 if (!Evaluate(Val, Info, SubExpr))
10421 return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000010422 return Success(Val.getFixedPoint().getBoolValue(), E);
Leonard Chanb4ba4672018-10-23 17:55:35 +000010423 }
10424
Eli Friedmanc757de22011-03-25 00:43:55 +000010425 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +000010426 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +000010427 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +000010428
Eli Friedman742421e2009-02-20 01:15:07 +000010429 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +000010430 // Allow casts of address-of-label differences if they are no-ops
10431 // or narrowing. (The narrowing case isn't actually guaranteed to
10432 // be constant-evaluatable except in some narrow cases which are hard
10433 // to detect here. We let it through on the assumption the user knows
10434 // what they are doing.)
10435 if (Result.isAddrLabelDiff())
10436 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +000010437 // Only allow casts of lvalues if they are lossless.
10438 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
10439 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +000010440
Richard Smith911e1422012-01-30 22:27:01 +000010441 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
10442 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +000010443 }
Mike Stump11289f42009-09-09 15:08:12 +000010444
Eli Friedmanc757de22011-03-25 00:43:55 +000010445 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +000010446 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
10447
John McCall45d55e42010-05-07 21:00:08 +000010448 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +000010449 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +000010450 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +000010451
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000010452 if (LV.getLValueBase()) {
10453 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +000010454 // FIXME: Allow a larger integer size than the pointer size, and allow
10455 // narrowing back down to pointer width in subsequent integral casts.
10456 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000010457 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010458 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +000010459
Richard Smithcf74da72011-11-16 07:18:12 +000010460 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +000010461 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000010462 return true;
10463 }
10464
Hans Wennborgdd1ea8a2019-03-06 10:26:19 +000010465 APSInt AsInt;
10466 APValue V;
10467 LV.moveInto(V);
10468 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
10469 llvm_unreachable("Can't cast this!");
Yaxun Liu402804b2016-12-15 08:09:08 +000010470
Richard Smith911e1422012-01-30 22:27:01 +000010471 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +000010472 }
Eli Friedman9a156e52008-11-12 09:44:48 +000010473
Eli Friedmanc757de22011-03-25 00:43:55 +000010474 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +000010475 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000010476 if (!EvaluateComplex(SubExpr, C, Info))
10477 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +000010478 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000010479 }
Eli Friedmanc2b50172009-02-22 11:46:18 +000010480
Eli Friedmanc757de22011-03-25 00:43:55 +000010481 case CK_FloatingToIntegral: {
10482 APFloat F(0.0);
10483 if (!EvaluateFloat(SubExpr, F, Info))
10484 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +000010485
Richard Smith357362d2011-12-13 06:39:58 +000010486 APSInt Value;
10487 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
10488 return false;
10489 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +000010490 }
10491 }
Mike Stump11289f42009-09-09 15:08:12 +000010492
Eli Friedmanc757de22011-03-25 00:43:55 +000010493 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +000010494}
Anders Carlssonb5ad0212008-07-08 14:30:00 +000010495
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010496bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
10497 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000010498 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010499 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
10500 return false;
10501 if (!LV.isComplexInt())
10502 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010503 return Success(LV.getComplexIntReal(), E);
10504 }
10505
10506 return Visit(E->getSubExpr());
10507}
10508
Eli Friedman4e7a2412009-02-27 04:45:43 +000010509bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010510 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +000010511 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010512 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
10513 return false;
10514 if (!LV.isComplexInt())
10515 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010516 return Success(LV.getComplexIntImag(), E);
10517 }
10518
Richard Smith4a678122011-10-24 18:44:57 +000010519 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +000010520 return Success(0, E);
10521}
10522
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010523bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
10524 return Success(E->getPackLength(), E);
10525}
10526
Sebastian Redl5f0180d2010-09-10 20:55:47 +000010527bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
10528 return Success(E->getValue(), E);
10529}
10530
Leonard Chandb01c3a2018-06-20 17:19:40 +000010531bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10532 switch (E->getOpcode()) {
10533 default:
10534 // Invalid unary operators
10535 return Error(E);
10536 case UO_Plus:
10537 // The result is just the value.
10538 return Visit(E->getSubExpr());
10539 case UO_Minus: {
10540 if (!Visit(E->getSubExpr())) return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000010541 if (!Result.isFixedPoint())
10542 return Error(E);
10543 bool Overflowed;
10544 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
10545 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
10546 return false;
10547 return Success(Negated, E);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010548 }
10549 case UO_LNot: {
10550 bool bres;
10551 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
10552 return false;
10553 return Success(!bres, E);
10554 }
10555 }
10556}
10557
Leonard Chand3f3e162019-01-18 21:04:25 +000010558bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
10559 const Expr *SubExpr = E->getSubExpr();
10560 QualType DestType = E->getType();
10561 assert(DestType->isFixedPointType() &&
10562 "Expected destination type to be a fixed point type");
10563 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
10564
10565 switch (E->getCastKind()) {
10566 case CK_FixedPointCast: {
10567 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
10568 if (!EvaluateFixedPoint(SubExpr, Src, Info))
10569 return false;
10570 bool Overflowed;
10571 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
10572 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
10573 return false;
10574 return Success(Result, E);
10575 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000010576 case CK_IntegralToFixedPoint: {
10577 APSInt Src;
10578 if (!EvaluateInteger(SubExpr, Src, Info))
10579 return false;
10580
10581 bool Overflowed;
10582 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
10583 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
10584
10585 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
10586 return false;
10587
10588 return Success(IntResult, E);
10589 }
Leonard Chand3f3e162019-01-18 21:04:25 +000010590 case CK_NoOp:
10591 case CK_LValueToRValue:
10592 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10593 default:
10594 return Error(E);
10595 }
10596}
10597
10598bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10599 const Expr *LHS = E->getLHS();
10600 const Expr *RHS = E->getRHS();
10601 FixedPointSemantics ResultFXSema =
10602 Info.Ctx.getFixedPointSemantics(E->getType());
10603
10604 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
10605 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
10606 return false;
10607 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
10608 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
10609 return false;
10610
10611 switch (E->getOpcode()) {
10612 case BO_Add: {
10613 bool AddOverflow, ConversionOverflow;
10614 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
10615 .convert(ResultFXSema, &ConversionOverflow);
10616 if ((AddOverflow || ConversionOverflow) &&
10617 !HandleOverflow(Info, E, Result, E->getType()))
10618 return false;
10619 return Success(Result, E);
10620 }
10621 default:
10622 return false;
10623 }
10624 llvm_unreachable("Should've exited before this");
10625}
10626
Chris Lattner05706e882008-07-11 18:11:29 +000010627//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +000010628// Float Evaluation
10629//===----------------------------------------------------------------------===//
10630
10631namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000010632class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010633 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +000010634 APFloat &Result;
10635public:
10636 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +000010637 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +000010638
Richard Smith2e312c82012-03-03 22:46:17 +000010639 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010640 Result = V.getFloat();
10641 return true;
10642 }
Eli Friedman24c01542008-08-22 00:06:13 +000010643
Richard Smithfddd3842011-12-30 21:15:51 +000010644 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +000010645 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
10646 return true;
10647 }
10648
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010649 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +000010650
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010651 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +000010652 bool VisitBinaryOperator(const BinaryOperator *E);
10653 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000010654 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +000010655
John McCallb1fb0d32010-05-07 22:08:54 +000010656 bool VisitUnaryReal(const UnaryOperator *E);
10657 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +000010658
Richard Smithfddd3842011-12-30 21:15:51 +000010659 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +000010660};
10661} // end anonymous namespace
10662
10663static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000010664 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010665 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +000010666}
10667
Jay Foad39c79802011-01-12 09:06:06 +000010668static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +000010669 QualType ResultTy,
10670 const Expr *Arg,
10671 bool SNaN,
10672 llvm::APFloat &Result) {
10673 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
10674 if (!S) return false;
10675
10676 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
10677
10678 llvm::APInt fill;
10679
10680 // Treat empty strings as if they were zero.
10681 if (S->getString().empty())
10682 fill = llvm::APInt(32, 0);
10683 else if (S->getString().getAsInteger(0, fill))
10684 return false;
10685
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +000010686 if (Context.getTargetInfo().isNan2008()) {
10687 if (SNaN)
10688 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10689 else
10690 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10691 } else {
10692 // Prior to IEEE 754-2008, architectures were allowed to choose whether
10693 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
10694 // a different encoding to what became a standard in 2008, and for pre-
10695 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
10696 // sNaN. This is now known as "legacy NaN" encoding.
10697 if (SNaN)
10698 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10699 else
10700 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10701 }
10702
John McCall16291492010-02-28 13:00:19 +000010703 return true;
10704}
10705
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010706bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000010707 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010708 default:
10709 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10710
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010711 case Builtin::BI__builtin_huge_val:
10712 case Builtin::BI__builtin_huge_valf:
10713 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010714 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010715 case Builtin::BI__builtin_inf:
10716 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010717 case Builtin::BI__builtin_infl:
10718 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010719 const llvm::fltSemantics &Sem =
10720 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000010721 Result = llvm::APFloat::getInf(Sem);
10722 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010723 }
Mike Stump11289f42009-09-09 15:08:12 +000010724
John McCall16291492010-02-28 13:00:19 +000010725 case Builtin::BI__builtin_nans:
10726 case Builtin::BI__builtin_nansf:
10727 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010728 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010729 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10730 true, Result))
10731 return Error(E);
10732 return true;
John McCall16291492010-02-28 13:00:19 +000010733
Chris Lattner0b7282e2008-10-06 06:31:58 +000010734 case Builtin::BI__builtin_nan:
10735 case Builtin::BI__builtin_nanf:
10736 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010737 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000010738 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000010739 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000010740 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10741 false, Result))
10742 return Error(E);
10743 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010744
10745 case Builtin::BI__builtin_fabs:
10746 case Builtin::BI__builtin_fabsf:
10747 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010748 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010749 if (!EvaluateFloat(E->getArg(0), Result, Info))
10750 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010751
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010752 if (Result.isNegative())
10753 Result.changeSign();
10754 return true;
10755
Richard Smith8889a3d2013-06-13 06:26:32 +000010756 // FIXME: Builtin::BI__builtin_powi
10757 // FIXME: Builtin::BI__builtin_powif
10758 // FIXME: Builtin::BI__builtin_powil
10759
Mike Stump11289f42009-09-09 15:08:12 +000010760 case Builtin::BI__builtin_copysign:
10761 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010762 case Builtin::BI__builtin_copysignl:
10763 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010764 APFloat RHS(0.);
10765 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
10766 !EvaluateFloat(E->getArg(1), RHS, Info))
10767 return false;
10768 Result.copySign(RHS);
10769 return true;
10770 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010771 }
10772}
10773
John McCallb1fb0d32010-05-07 22:08:54 +000010774bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000010775 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10776 ComplexValue CV;
10777 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10778 return false;
10779 Result = CV.FloatReal;
10780 return true;
10781 }
10782
10783 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000010784}
10785
10786bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000010787 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10788 ComplexValue CV;
10789 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10790 return false;
10791 Result = CV.FloatImag;
10792 return true;
10793 }
10794
Richard Smith4a678122011-10-24 18:44:57 +000010795 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000010796 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
10797 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000010798 return true;
10799}
10800
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010801bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010802 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010803 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000010804 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000010805 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000010806 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000010807 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
10808 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010809 Result.changeSign();
10810 return true;
10811 }
10812}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010813
Eli Friedman24c01542008-08-22 00:06:13 +000010814bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000010815 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10816 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000010817
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010818 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000010819 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010820 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000010821 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000010822 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
10823 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000010824}
10825
10826bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
10827 Result = E->getValue();
10828 return true;
10829}
10830
Peter Collingbournee9200682011-05-13 03:29:01 +000010831bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
10832 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000010833
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010834 switch (E->getCastKind()) {
10835 default:
Richard Smith11562c52011-10-28 17:51:58 +000010836 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010837
10838 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010839 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000010840 return EvaluateInteger(SubExpr, IntResult, Info) &&
10841 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
10842 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000010843 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010844
10845 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010846 if (!Visit(SubExpr))
10847 return false;
Richard Smith357362d2011-12-13 06:39:58 +000010848 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
10849 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000010850 }
John McCalld7646252010-11-14 08:17:51 +000010851
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010852 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000010853 ComplexValue V;
10854 if (!EvaluateComplex(SubExpr, V, Info))
10855 return false;
10856 Result = V.getComplexFloatReal();
10857 return true;
10858 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010859 }
Eli Friedman9a156e52008-11-12 09:44:48 +000010860}
10861
Eli Friedman24c01542008-08-22 00:06:13 +000010862//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010863// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000010864//===----------------------------------------------------------------------===//
10865
10866namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000010867class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010868 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000010869 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000010870
Anders Carlsson537969c2008-11-16 20:27:53 +000010871public:
John McCall93d91dc2010-05-07 17:22:02 +000010872 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000010873 : ExprEvaluatorBaseTy(info), Result(Result) {}
10874
Richard Smith2e312c82012-03-03 22:46:17 +000010875 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010876 Result.setFrom(V);
10877 return true;
10878 }
Mike Stump11289f42009-09-09 15:08:12 +000010879
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010880 bool ZeroInitialization(const Expr *E);
10881
Anders Carlsson537969c2008-11-16 20:27:53 +000010882 //===--------------------------------------------------------------------===//
10883 // Visitor Methods
10884 //===--------------------------------------------------------------------===//
10885
Peter Collingbournee9200682011-05-13 03:29:01 +000010886 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000010887 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000010888 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010889 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010890 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010891};
10892} // end anonymous namespace
10893
John McCall93d91dc2010-05-07 17:22:02 +000010894static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
10895 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000010896 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010897 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010898}
10899
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010900bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000010901 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010902 if (ElemTy->isRealFloatingType()) {
10903 Result.makeComplexFloat();
10904 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10905 Result.FloatReal = Zero;
10906 Result.FloatImag = Zero;
10907 } else {
10908 Result.makeComplexInt();
10909 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10910 Result.IntReal = Zero;
10911 Result.IntImag = Zero;
10912 }
10913 return true;
10914}
10915
Peter Collingbournee9200682011-05-13 03:29:01 +000010916bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10917 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010918
10919 if (SubExpr->getType()->isRealFloatingType()) {
10920 Result.makeComplexFloat();
10921 APFloat &Imag = Result.FloatImag;
10922 if (!EvaluateFloat(SubExpr, Imag, Info))
10923 return false;
10924
10925 Result.FloatReal = APFloat(Imag.getSemantics());
10926 return true;
10927 } else {
10928 assert(SubExpr->getType()->isIntegerType() &&
10929 "Unexpected imaginary literal.");
10930
10931 Result.makeComplexInt();
10932 APSInt &Imag = Result.IntImag;
10933 if (!EvaluateInteger(SubExpr, Imag, Info))
10934 return false;
10935
10936 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10937 return true;
10938 }
10939}
10940
Peter Collingbournee9200682011-05-13 03:29:01 +000010941bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010942
John McCallfcef3cf2010-12-14 17:51:41 +000010943 switch (E->getCastKind()) {
10944 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010945 case CK_BaseToDerived:
10946 case CK_DerivedToBase:
10947 case CK_UncheckedDerivedToBase:
10948 case CK_Dynamic:
10949 case CK_ToUnion:
10950 case CK_ArrayToPointerDecay:
10951 case CK_FunctionToPointerDecay:
10952 case CK_NullToPointer:
10953 case CK_NullToMemberPointer:
10954 case CK_BaseToDerivedMemberPointer:
10955 case CK_DerivedToBaseMemberPointer:
10956 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000010957 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000010958 case CK_ConstructorConversion:
10959 case CK_IntegralToPointer:
10960 case CK_PointerToIntegral:
10961 case CK_PointerToBoolean:
10962 case CK_ToVoid:
10963 case CK_VectorSplat:
10964 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000010965 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000010966 case CK_IntegralToBoolean:
10967 case CK_IntegralToFloating:
10968 case CK_FloatingToIntegral:
10969 case CK_FloatingToBoolean:
10970 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000010971 case CK_CPointerToObjCPointerCast:
10972 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010973 case CK_AnyPointerToBlockPointerCast:
10974 case CK_ObjCObjectLValueCast:
10975 case CK_FloatingComplexToReal:
10976 case CK_FloatingComplexToBoolean:
10977 case CK_IntegralComplexToReal:
10978 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000010979 case CK_ARCProduceObject:
10980 case CK_ARCConsumeObject:
10981 case CK_ARCReclaimReturnedObject:
10982 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000010983 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000010984 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000010985 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000010986 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000010987 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000010988 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000010989 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000010990 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +000010991 case CK_FixedPointToIntegral:
10992 case CK_IntegralToFixedPoint:
John McCallfcef3cf2010-12-14 17:51:41 +000010993 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000010994
John McCallfcef3cf2010-12-14 17:51:41 +000010995 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010996 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000010997 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +000010998 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010999
11000 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000011001 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011002 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011003 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000011004
11005 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011006 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000011007 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011008 return false;
11009
John McCallfcef3cf2010-12-14 17:51:41 +000011010 Result.makeComplexFloat();
11011 Result.FloatImag = APFloat(Real.getSemantics());
11012 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011013 }
11014
John McCallfcef3cf2010-12-14 17:51:41 +000011015 case CK_FloatingComplexCast: {
11016 if (!Visit(E->getSubExpr()))
11017 return false;
11018
11019 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11020 QualType From
11021 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11022
Richard Smith357362d2011-12-13 06:39:58 +000011023 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11024 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011025 }
11026
11027 case CK_FloatingComplexToIntegralComplex: {
11028 if (!Visit(E->getSubExpr()))
11029 return false;
11030
11031 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11032 QualType From
11033 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11034 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000011035 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11036 To, Result.IntReal) &&
11037 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11038 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011039 }
11040
11041 case CK_IntegralRealToComplex: {
11042 APSInt &Real = Result.IntReal;
11043 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11044 return false;
11045
11046 Result.makeComplexInt();
11047 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11048 return true;
11049 }
11050
11051 case CK_IntegralComplexCast: {
11052 if (!Visit(E->getSubExpr()))
11053 return false;
11054
11055 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11056 QualType From
11057 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11058
Richard Smith911e1422012-01-30 22:27:01 +000011059 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11060 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011061 return true;
11062 }
11063
11064 case CK_IntegralComplexToFloatingComplex: {
11065 if (!Visit(E->getSubExpr()))
11066 return false;
11067
Ted Kremenek28831752012-08-23 20:46:57 +000011068 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000011069 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000011070 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000011071 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000011072 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11073 To, Result.FloatReal) &&
11074 HandleIntToFloatCast(Info, E, From, Result.IntImag,
11075 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011076 }
11077 }
11078
11079 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011080}
11081
John McCall93d91dc2010-05-07 17:22:02 +000011082bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000011083 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000011084 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11085
Chandler Carrutha216cad2014-10-11 00:57:18 +000011086 // Track whether the LHS or RHS is real at the type system level. When this is
11087 // the case we can simplify our evaluation strategy.
11088 bool LHSReal = false, RHSReal = false;
11089
11090 bool LHSOK;
11091 if (E->getLHS()->getType()->isRealFloatingType()) {
11092 LHSReal = true;
11093 APFloat &Real = Result.FloatReal;
11094 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11095 if (LHSOK) {
11096 Result.makeComplexFloat();
11097 Result.FloatImag = APFloat(Real.getSemantics());
11098 }
11099 } else {
11100 LHSOK = Visit(E->getLHS());
11101 }
George Burgess IVa145e252016-05-25 22:38:36 +000011102 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000011103 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011104
John McCall93d91dc2010-05-07 17:22:02 +000011105 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011106 if (E->getRHS()->getType()->isRealFloatingType()) {
11107 RHSReal = true;
11108 APFloat &Real = RHS.FloatReal;
11109 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11110 return false;
11111 RHS.makeComplexFloat();
11112 RHS.FloatImag = APFloat(Real.getSemantics());
11113 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000011114 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011115
Chandler Carrutha216cad2014-10-11 00:57:18 +000011116 assert(!(LHSReal && RHSReal) &&
11117 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011118 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011119 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000011120 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011121 if (Result.isComplexFloat()) {
11122 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11123 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011124 if (LHSReal)
11125 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11126 else if (!RHSReal)
11127 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11128 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011129 } else {
11130 Result.getComplexIntReal() += RHS.getComplexIntReal();
11131 Result.getComplexIntImag() += RHS.getComplexIntImag();
11132 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011133 break;
John McCalle3027922010-08-25 11:45:40 +000011134 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011135 if (Result.isComplexFloat()) {
11136 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11137 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011138 if (LHSReal) {
11139 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11140 Result.getComplexFloatImag().changeSign();
11141 } else if (!RHSReal) {
11142 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11143 APFloat::rmNearestTiesToEven);
11144 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011145 } else {
11146 Result.getComplexIntReal() -= RHS.getComplexIntReal();
11147 Result.getComplexIntImag() -= RHS.getComplexIntImag();
11148 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011149 break;
John McCalle3027922010-08-25 11:45:40 +000011150 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011151 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000011152 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000011153 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000011154 // following naming scheme:
11155 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000011156 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011157 APFloat &A = LHS.getComplexFloatReal();
11158 APFloat &B = LHS.getComplexFloatImag();
11159 APFloat &C = RHS.getComplexFloatReal();
11160 APFloat &D = RHS.getComplexFloatImag();
11161 APFloat &ResR = Result.getComplexFloatReal();
11162 APFloat &ResI = Result.getComplexFloatImag();
11163 if (LHSReal) {
11164 assert(!RHSReal && "Cannot have two real operands for a complex op!");
11165 ResR = A * C;
11166 ResI = A * D;
11167 } else if (RHSReal) {
11168 ResR = C * A;
11169 ResI = C * B;
11170 } else {
11171 // In the fully general case, we need to handle NaNs and infinities
11172 // robustly.
11173 APFloat AC = A * C;
11174 APFloat BD = B * D;
11175 APFloat AD = A * D;
11176 APFloat BC = B * C;
11177 ResR = AC - BD;
11178 ResI = AD + BC;
11179 if (ResR.isNaN() && ResI.isNaN()) {
11180 bool Recalc = false;
11181 if (A.isInfinity() || B.isInfinity()) {
11182 A = APFloat::copySign(
11183 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11184 B = APFloat::copySign(
11185 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11186 if (C.isNaN())
11187 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11188 if (D.isNaN())
11189 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11190 Recalc = true;
11191 }
11192 if (C.isInfinity() || D.isInfinity()) {
11193 C = APFloat::copySign(
11194 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11195 D = APFloat::copySign(
11196 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11197 if (A.isNaN())
11198 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11199 if (B.isNaN())
11200 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11201 Recalc = true;
11202 }
11203 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11204 AD.isInfinity() || BC.isInfinity())) {
11205 if (A.isNaN())
11206 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11207 if (B.isNaN())
11208 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11209 if (C.isNaN())
11210 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11211 if (D.isNaN())
11212 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11213 Recalc = true;
11214 }
11215 if (Recalc) {
11216 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11217 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11218 }
11219 }
11220 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011221 } else {
John McCall93d91dc2010-05-07 17:22:02 +000011222 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000011223 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011224 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11225 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000011226 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011227 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11228 LHS.getComplexIntImag() * RHS.getComplexIntReal());
11229 }
11230 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011231 case BO_Div:
11232 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000011233 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000011234 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000011235 // following naming scheme:
11236 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011237 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011238 APFloat &A = LHS.getComplexFloatReal();
11239 APFloat &B = LHS.getComplexFloatImag();
11240 APFloat &C = RHS.getComplexFloatReal();
11241 APFloat &D = RHS.getComplexFloatImag();
11242 APFloat &ResR = Result.getComplexFloatReal();
11243 APFloat &ResI = Result.getComplexFloatImag();
11244 if (RHSReal) {
11245 ResR = A / C;
11246 ResI = B / C;
11247 } else {
11248 if (LHSReal) {
11249 // No real optimizations we can do here, stub out with zero.
11250 B = APFloat::getZero(A.getSemantics());
11251 }
11252 int DenomLogB = 0;
11253 APFloat MaxCD = maxnum(abs(C), abs(D));
11254 if (MaxCD.isFinite()) {
11255 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000011256 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11257 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011258 }
11259 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000011260 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11261 APFloat::rmNearestTiesToEven);
11262 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11263 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011264 if (ResR.isNaN() && ResI.isNaN()) {
11265 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11266 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11267 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11268 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11269 D.isFinite()) {
11270 A = APFloat::copySign(
11271 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11272 B = APFloat::copySign(
11273 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11274 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11275 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11276 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11277 C = APFloat::copySign(
11278 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11279 D = APFloat::copySign(
11280 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11281 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
11282 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
11283 }
11284 }
11285 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011286 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011287 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
11288 return Error(E, diag::note_expr_divide_by_zero);
11289
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011290 ComplexValue LHS = Result;
11291 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
11292 RHS.getComplexIntImag() * RHS.getComplexIntImag();
11293 Result.getComplexIntReal() =
11294 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
11295 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
11296 Result.getComplexIntImag() =
11297 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
11298 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
11299 }
11300 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011301 }
11302
John McCall93d91dc2010-05-07 17:22:02 +000011303 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011304}
11305
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011306bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11307 // Get the operand value into 'Result'.
11308 if (!Visit(E->getSubExpr()))
11309 return false;
11310
11311 switch (E->getOpcode()) {
11312 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011313 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011314 case UO_Extension:
11315 return true;
11316 case UO_Plus:
11317 // The result is always just the subexpr.
11318 return true;
11319 case UO_Minus:
11320 if (Result.isComplexFloat()) {
11321 Result.getComplexFloatReal().changeSign();
11322 Result.getComplexFloatImag().changeSign();
11323 }
11324 else {
11325 Result.getComplexIntReal() = -Result.getComplexIntReal();
11326 Result.getComplexIntImag() = -Result.getComplexIntImag();
11327 }
11328 return true;
11329 case UO_Not:
11330 if (Result.isComplexFloat())
11331 Result.getComplexFloatImag().changeSign();
11332 else
11333 Result.getComplexIntImag() = -Result.getComplexIntImag();
11334 return true;
11335 }
11336}
11337
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011338bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11339 if (E->getNumInits() == 2) {
11340 if (E->getType()->isComplexType()) {
11341 Result.makeComplexFloat();
11342 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
11343 return false;
11344 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
11345 return false;
11346 } else {
11347 Result.makeComplexInt();
11348 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
11349 return false;
11350 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
11351 return false;
11352 }
11353 return true;
11354 }
11355 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
11356}
11357
Anders Carlsson537969c2008-11-16 20:27:53 +000011358//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000011359// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
11360// implicit conversion.
11361//===----------------------------------------------------------------------===//
11362
11363namespace {
11364class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000011365 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000011366 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000011367 APValue &Result;
11368public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000011369 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
11370 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000011371
11372 bool Success(const APValue &V, const Expr *E) {
11373 Result = V;
11374 return true;
11375 }
11376
11377 bool ZeroInitialization(const Expr *E) {
11378 ImplicitValueInitExpr VIE(
11379 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000011380 // For atomic-qualified class (and array) types in C++, initialize the
11381 // _Atomic-wrapped subobject directly, in-place.
11382 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
11383 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000011384 }
11385
11386 bool VisitCastExpr(const CastExpr *E) {
11387 switch (E->getCastKind()) {
11388 default:
11389 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11390 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000011391 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
11392 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000011393 }
11394 }
11395};
11396} // end anonymous namespace
11397
Richard Smith64cb9ca2017-02-22 22:09:50 +000011398static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
11399 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000011400 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000011401 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000011402}
11403
11404//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000011405// Void expression evaluation, primarily for a cast to void on the LHS of a
11406// comma operator
11407//===----------------------------------------------------------------------===//
11408
11409namespace {
11410class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000011411 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000011412public:
11413 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
11414
Richard Smith2e312c82012-03-03 22:46:17 +000011415 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000011416
Richard Smith7cd577b2017-08-17 19:35:50 +000011417 bool ZeroInitialization(const Expr *E) { return true; }
11418
Richard Smith42d3af92011-12-07 00:43:50 +000011419 bool VisitCastExpr(const CastExpr *E) {
11420 switch (E->getCastKind()) {
11421 default:
11422 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11423 case CK_ToVoid:
11424 VisitIgnoredValue(E->getSubExpr());
11425 return true;
11426 }
11427 }
Hal Finkela8443c32014-07-17 14:49:58 +000011428
11429 bool VisitCallExpr(const CallExpr *E) {
11430 switch (E->getBuiltinCallee()) {
11431 default:
11432 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11433 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000011434 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000011435 // The argument is not evaluated!
11436 return true;
11437 }
11438 }
Richard Smith42d3af92011-12-07 00:43:50 +000011439};
11440} // end anonymous namespace
11441
11442static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
11443 assert(E->isRValue() && E->getType()->isVoidType());
11444 return VoidExprEvaluator(Info).Visit(E);
11445}
11446
11447//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000011448// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000011449//===----------------------------------------------------------------------===//
11450
Richard Smith2e312c82012-03-03 22:46:17 +000011451static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000011452 // In C, function designators are not lvalues, but we evaluate them as if they
11453 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000011454 QualType T = E->getType();
11455 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000011456 LValue LV;
11457 if (!EvaluateLValue(E, LV, Info))
11458 return false;
11459 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000011460 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000011461 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000011462 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011463 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000011464 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011465 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011466 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000011467 LValue LV;
11468 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011469 return false;
Richard Smith725810a2011-10-16 21:26:27 +000011470 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000011471 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000011472 llvm::APFloat F(0.0);
11473 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011474 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000011475 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000011476 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000011477 ComplexValue C;
11478 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011479 return false;
Richard Smith725810a2011-10-16 21:26:27 +000011480 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000011481 } else if (T->isFixedPointType()) {
11482 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011483 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000011484 MemberPtr P;
11485 if (!EvaluateMemberPointer(E, P, Info))
11486 return false;
11487 P.moveInto(Result);
11488 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000011489 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000011490 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011491 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000011492 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000011493 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000011494 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000011495 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000011496 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011497 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000011498 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000011499 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000011500 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000011501 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011502 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000011503 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000011504 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000011505 if (!EvaluateVoid(E, Info))
11506 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011507 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000011508 QualType Unqual = T.getAtomicUnqualifiedType();
11509 if (Unqual->isArrayType() || Unqual->isRecordType()) {
11510 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011511 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000011512 if (!EvaluateAtomic(E, &LV, Value, Info))
11513 return false;
11514 } else {
11515 if (!EvaluateAtomic(E, nullptr, Result, Info))
11516 return false;
11517 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011518 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000011519 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000011520 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011521 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000011522 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000011523 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011524 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011525
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000011526 return true;
11527}
11528
Richard Smithb228a862012-02-15 02:18:13 +000011529/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
11530/// cases, the in-place evaluation is essential, since later initializers for
11531/// an object can indirectly refer to subobjects which were initialized earlier.
11532static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000011533 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000011534 assert(!E->isValueDependent());
11535
Richard Smith7525ff62013-05-09 07:14:00 +000011536 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000011537 return false;
11538
11539 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000011540 // Evaluate arrays and record types in-place, so that later initializers can
11541 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000011542 QualType T = E->getType();
11543 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000011544 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000011545 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000011546 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000011547 else if (T->isAtomicType()) {
11548 QualType Unqual = T.getAtomicUnqualifiedType();
11549 if (Unqual->isArrayType() || Unqual->isRecordType())
11550 return EvaluateAtomic(E, &This, Result, Info);
11551 }
Richard Smithed5165f2011-11-04 05:33:44 +000011552 }
11553
11554 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000011555 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000011556}
11557
Richard Smithf57d8cb2011-12-09 22:58:01 +000011558/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
11559/// lvalue-to-rvalue cast if it is an lvalue.
11560static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000011561 if (E->getType().isNull())
11562 return false;
11563
Nick Lewyckyc190f962017-05-02 01:06:16 +000011564 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000011565 return false;
11566
Richard Smith2e312c82012-03-03 22:46:17 +000011567 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011568 return false;
11569
11570 if (E->isGLValue()) {
11571 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000011572 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000011573 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011574 return false;
11575 }
11576
Richard Smith2e312c82012-03-03 22:46:17 +000011577 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000011578 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011579}
Richard Smith11562c52011-10-28 17:51:58 +000011580
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011581static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000011582 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011583 // Fast-path evaluations of integer literals, since we sometimes see files
11584 // containing vast quantities of these.
11585 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
11586 Result.Val = APValue(APSInt(L->getValue(),
11587 L->getType()->isUnsignedIntegerType()));
11588 IsConst = true;
11589 return true;
11590 }
James Dennett0492ef02014-03-14 17:44:10 +000011591
11592 // This case should be rare, but we need to check it before we check on
11593 // the type below.
11594 if (Exp->getType().isNull()) {
11595 IsConst = false;
11596 return true;
11597 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011598
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011599 // FIXME: Evaluating values of large array and record types can cause
11600 // performance problems. Only do so in C++11 for now.
11601 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
11602 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000011603 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011604 IsConst = false;
11605 return true;
11606 }
11607 return false;
11608}
11609
Fangrui Song407659a2018-11-30 23:41:18 +000011610static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
11611 Expr::SideEffectsKind SEK) {
11612 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
11613 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
11614}
11615
11616static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
11617 const ASTContext &Ctx, EvalInfo &Info) {
11618 bool IsConst;
11619 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
11620 return IsConst;
11621
11622 return EvaluateAsRValue(Info, E, Result.Val);
11623}
11624
11625static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
11626 const ASTContext &Ctx,
11627 Expr::SideEffectsKind AllowSideEffects,
11628 EvalInfo &Info) {
11629 if (!E->getType()->isIntegralOrEnumerationType())
11630 return false;
11631
11632 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
11633 !ExprResult.Val.isInt() ||
11634 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11635 return false;
11636
11637 return true;
11638}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011639
Leonard Chand3f3e162019-01-18 21:04:25 +000011640static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
11641 const ASTContext &Ctx,
11642 Expr::SideEffectsKind AllowSideEffects,
11643 EvalInfo &Info) {
11644 if (!E->getType()->isFixedPointType())
11645 return false;
11646
11647 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
11648 return false;
11649
11650 if (!ExprResult.Val.isFixedPoint() ||
11651 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11652 return false;
11653
11654 return true;
11655}
11656
Richard Smith7b553f12011-10-29 00:50:52 +000011657/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000011658/// any crazy technique (that has nothing to do with language standards) that
11659/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000011660/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
11661/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000011662bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
11663 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011664 assert(!isValueDependent() &&
11665 "Expression evaluator can't be called on a dependent expression.");
Richard Smith6d4c6582013-11-05 22:18:15 +000011666 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000011667 Info.InConstantContext = InConstantContext;
11668 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000011669}
11670
Jay Foad39c79802011-01-12 09:06:06 +000011671bool Expr::EvaluateAsBooleanCondition(bool &Result,
11672 const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011673 assert(!isValueDependent() &&
11674 "Expression evaluator can't be called on a dependent expression.");
Richard Smith11562c52011-10-28 17:51:58 +000011675 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000011676 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000011677 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000011678}
11679
Fangrui Song407659a2018-11-30 23:41:18 +000011680bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Richard Smith5fab0c92011-12-28 19:48:30 +000011681 SideEffectsKind AllowSideEffects) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011682 assert(!isValueDependent() &&
11683 "Expression evaluator can't be called on a dependent expression.");
Fangrui Song407659a2018-11-30 23:41:18 +000011684 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11685 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000011686}
11687
Leonard Chand3f3e162019-01-18 21:04:25 +000011688bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
11689 SideEffectsKind AllowSideEffects) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011690 assert(!isValueDependent() &&
11691 "Expression evaluator can't be called on a dependent expression.");
Leonard Chand3f3e162019-01-18 21:04:25 +000011692 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11693 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
11694}
11695
Richard Trieube234c32016-04-21 21:04:55 +000011696bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
11697 SideEffectsKind AllowSideEffects) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011698 assert(!isValueDependent() &&
11699 "Expression evaluator can't be called on a dependent expression.");
11700
Richard Trieube234c32016-04-21 21:04:55 +000011701 if (!getType()->isRealFloatingType())
11702 return false;
11703
11704 EvalResult ExprResult;
11705 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000011706 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000011707 return false;
11708
11709 Result = ExprResult.Val.getFloat();
11710 return true;
11711}
11712
Jay Foad39c79802011-01-12 09:06:06 +000011713bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011714 assert(!isValueDependent() &&
11715 "Expression evaluator can't be called on a dependent expression.");
11716
Richard Smith6d4c6582013-11-05 22:18:15 +000011717 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000011718
John McCall45d55e42010-05-07 21:00:08 +000011719 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000011720 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
11721 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000011722 Ctx.getLValueReferenceType(getType()), LV,
11723 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000011724 return false;
11725
Richard Smith2e312c82012-03-03 22:46:17 +000011726 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000011727 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000011728}
11729
Reid Kleckner1a840d22018-05-10 18:57:35 +000011730bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
11731 const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011732 assert(!isValueDependent() &&
11733 "Expression evaluator can't be called on a dependent expression.");
11734
Reid Kleckner1a840d22018-05-10 18:57:35 +000011735 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
11736 EvalInfo Info(Ctx, Result, EM);
Eric Fiselier680e8652019-03-08 22:06:48 +000011737 Info.InConstantContext = true;
Eric Fiselieradd16a82019-04-24 02:23:30 +000011738
Reid Kleckner1a840d22018-05-10 18:57:35 +000011739 if (!::Evaluate(Result.Val, Info, this))
11740 return false;
11741
11742 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
11743 Usage);
11744}
11745
Richard Smithd0b4dd62011-12-19 06:19:21 +000011746bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
11747 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011748 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011749 assert(!isValueDependent() &&
11750 "Expression evaluator can't be called on a dependent expression.");
11751
Richard Smithdafff942012-01-14 04:30:29 +000011752 // FIXME: Evaluating initializers for large array and record types can cause
11753 // performance problems. Only do so in C++11 for now.
11754 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011755 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000011756 return false;
11757
Richard Smithd0b4dd62011-12-19 06:19:21 +000011758 Expr::EvalStatus EStatus;
11759 EStatus.Diag = &Notes;
11760
Richard Smith0c6124b2015-12-03 01:36:22 +000011761 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
11762 ? EvalInfo::EM_ConstantExpression
11763 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000011764 InitInfo.setEvaluatingDecl(VD, Value);
Fangrui Song407659a2018-11-30 23:41:18 +000011765 InitInfo.InConstantContext = true;
Richard Smithd0b4dd62011-12-19 06:19:21 +000011766
11767 LValue LVal;
11768 LVal.set(VD);
11769
Richard Smithfddd3842011-12-30 21:15:51 +000011770 // C++11 [basic.start.init]p2:
11771 // Variables with static storage duration or thread storage duration shall be
11772 // zero-initialized before any other initialization takes place.
11773 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011774 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000011775 !VD->getType()->isReferenceType()) {
11776 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000011777 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000011778 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000011779 return false;
11780 }
11781
Richard Smith7525ff62013-05-09 07:14:00 +000011782 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
11783 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000011784 EStatus.HasSideEffects)
11785 return false;
11786
11787 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
11788 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000011789}
11790
Richard Smith7b553f12011-10-29 00:50:52 +000011791/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
11792/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000011793bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011794 assert(!isValueDependent() &&
11795 "Expression evaluator can't be called on a dependent expression.");
11796
Anders Carlsson5b3638b2008-12-01 06:44:05 +000011797 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000011798 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000011799 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000011800}
Anders Carlsson59689ed2008-11-22 21:04:56 +000011801
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000011802APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011803 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011804 assert(!isValueDependent() &&
11805 "Expression evaluator can't be called on a dependent expression.");
11806
Fangrui Song407659a2018-11-30 23:41:18 +000011807 EvalResult EVResult;
11808 EVResult.Diag = Diag;
11809 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
11810 Info.InConstantContext = true;
11811
11812 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000011813 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000011814 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000011815 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000011816
Fangrui Song407659a2018-11-30 23:41:18 +000011817 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000011818}
John McCall864e3962010-05-07 05:32:02 +000011819
David Bolvansky3b6ae572018-10-18 20:49:06 +000011820APSInt Expr::EvaluateKnownConstIntCheckOverflow(
11821 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011822 assert(!isValueDependent() &&
11823 "Expression evaluator can't be called on a dependent expression.");
11824
Fangrui Song407659a2018-11-30 23:41:18 +000011825 EvalResult EVResult;
11826 EVResult.Diag = Diag;
11827 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11828 Info.InConstantContext = true;
11829
11830 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000011831 (void)Result;
11832 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000011833 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000011834
Fangrui Song407659a2018-11-30 23:41:18 +000011835 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000011836}
11837
Richard Smithe9ff7702013-11-05 22:23:30 +000011838void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000011839 assert(!isValueDependent() &&
11840 "Expression evaluator can't be called on a dependent expression.");
11841
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011842 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000011843 EvalResult EVResult;
11844 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
11845 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11846 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011847 }
11848}
11849
Richard Smithe6c01442013-06-05 00:46:14 +000011850bool Expr::EvalResult::isGlobalLValue() const {
11851 assert(Val.isLValue());
11852 return IsGlobalLValue(Val.getLValueBase());
11853}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000011854
11855
John McCall864e3962010-05-07 05:32:02 +000011856/// isIntegerConstantExpr - this recursive routine will test if an expression is
11857/// an integer constant expression.
11858
11859/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
11860/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000011861
11862// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000011863// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
11864// and a (possibly null) SourceLocation indicating the location of the problem.
11865//
John McCall864e3962010-05-07 05:32:02 +000011866// Note that to reduce code duplication, this helper does no evaluation
11867// itself; the caller checks whether the expression is evaluatable, and
11868// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000011869// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000011870
Dan Gohman28ade552010-07-26 21:25:24 +000011871namespace {
11872
Richard Smith9e575da2012-12-28 13:25:52 +000011873enum ICEKind {
11874 /// This expression is an ICE.
11875 IK_ICE,
11876 /// This expression is not an ICE, but if it isn't evaluated, it's
11877 /// a legal subexpression for an ICE. This return value is used to handle
11878 /// the comma operator in C99 mode, and non-constant subexpressions.
11879 IK_ICEIfUnevaluated,
11880 /// This expression is not an ICE, and is not a legal subexpression for one.
11881 IK_NotICE
11882};
11883
John McCall864e3962010-05-07 05:32:02 +000011884struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000011885 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000011886 SourceLocation Loc;
11887
Richard Smith9e575da2012-12-28 13:25:52 +000011888 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000011889};
11890
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011891}
Dan Gohman28ade552010-07-26 21:25:24 +000011892
Richard Smith9e575da2012-12-28 13:25:52 +000011893static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
11894
11895static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000011896
Craig Toppera31a8822013-08-22 07:09:37 +000011897static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000011898 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000011899 Expr::EvalStatus Status;
11900 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11901
11902 Info.InConstantContext = true;
11903 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000011904 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011905 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000011906
John McCall864e3962010-05-07 05:32:02 +000011907 return NoDiag();
11908}
11909
Craig Toppera31a8822013-08-22 07:09:37 +000011910static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000011911 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000011912 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011913 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011914
11915 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000011916#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000011917#define STMT(Node, Base) case Expr::Node##Class:
11918#define EXPR(Node, Base)
11919#include "clang/AST/StmtNodes.inc"
11920 case Expr::PredefinedExprClass:
11921 case Expr::FloatingLiteralClass:
11922 case Expr::ImaginaryLiteralClass:
11923 case Expr::StringLiteralClass:
11924 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011925 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000011926 case Expr::MemberExprClass:
11927 case Expr::CompoundAssignOperatorClass:
11928 case Expr::CompoundLiteralExprClass:
11929 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000011930 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000011931 case Expr::ArrayInitLoopExprClass:
11932 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000011933 case Expr::NoInitExprClass:
11934 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000011935 case Expr::ImplicitValueInitExprClass:
11936 case Expr::ParenListExprClass:
11937 case Expr::VAArgExprClass:
11938 case Expr::AddrLabelExprClass:
11939 case Expr::StmtExprClass:
11940 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000011941 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000011942 case Expr::CXXDynamicCastExprClass:
11943 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000011944 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000011945 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000011946 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011947 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000011948 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011949 case Expr::CXXThisExprClass:
11950 case Expr::CXXThrowExprClass:
11951 case Expr::CXXNewExprClass:
11952 case Expr::CXXDeleteExprClass:
11953 case Expr::CXXPseudoDestructorExprClass:
11954 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000011955 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000011956 case Expr::DependentScopeDeclRefExprClass:
11957 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000011958 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000011959 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000011960 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000011961 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000011962 case Expr::CXXTemporaryObjectExprClass:
11963 case Expr::CXXUnresolvedConstructExprClass:
11964 case Expr::CXXDependentScopeMemberExprClass:
11965 case Expr::UnresolvedMemberExprClass:
11966 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000011967 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011968 case Expr::ObjCArrayLiteralClass:
11969 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011970 case Expr::ObjCEncodeExprClass:
11971 case Expr::ObjCMessageExprClass:
11972 case Expr::ObjCSelectorExprClass:
11973 case Expr::ObjCProtocolExprClass:
11974 case Expr::ObjCIvarRefExprClass:
11975 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011976 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000011977 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000011978 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000011979 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000011980 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000011981 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000011982 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000011983 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000011984 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000011985 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000011986 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000011987 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000011988 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000011989 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000011990 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000011991 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000011992 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000011993 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011994 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000011995 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011996 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011997 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000011998
Richard Smithf137f932014-01-25 20:50:08 +000011999 case Expr::InitListExprClass: {
12000 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
12001 // form "T x = { a };" is equivalent to "T x = a;".
12002 // Unless we're initializing a reference, T is a scalar as it is known to be
12003 // of integral or enumeration type.
12004 if (E->isRValue())
12005 if (cast<InitListExpr>(E)->getNumInits() == 1)
12006 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012007 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000012008 }
12009
Douglas Gregor820ba7b2011-01-04 17:33:58 +000012010 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000012011 case Expr::GNUNullExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +000012012 case Expr::SourceLocExprClass:
John McCall864e3962010-05-07 05:32:02 +000012013 return NoDiag();
12014
John McCall7c454bb2011-07-15 05:09:51 +000012015 case Expr::SubstNonTypeTemplateParmExprClass:
12016 return
12017 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12018
Bill Wendling7c44da22018-10-31 03:48:47 +000012019 case Expr::ConstantExprClass:
12020 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12021
John McCall864e3962010-05-07 05:32:02 +000012022 case Expr::ParenExprClass:
12023 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000012024 case Expr::GenericSelectionExprClass:
12025 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012026 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000012027 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012028 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012029 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000012030 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000012031 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000012032 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000012033 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000012034 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000012035 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000012036 return NoDiag();
12037 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000012038 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000012039 // C99 6.6/3 allows function calls within unevaluated subexpressions of
12040 // constant expressions, but they can never be ICEs because an ICE cannot
12041 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000012042 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000012043 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000012044 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012045 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012046 }
Richard Smith6365c912012-02-24 22:12:32 +000012047 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000012048 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12049 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000012050 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012051 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000012052 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000012053 // Parameter variables are never constants. Without this check,
12054 // getAnyInitializer() can find a default argument, which leads
12055 // to chaos.
12056 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000012057 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000012058
12059 // C++ 7.1.5.1p2
12060 // A variable of non-volatile const-qualified integral or enumeration
12061 // type initialized by an ICE can be used in ICEs.
12062 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000012063 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000012064 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000012065
Richard Smithd0b4dd62011-12-19 06:19:21 +000012066 const VarDecl *VD;
12067 // Look for a declaration of this variable that has an initializer, and
12068 // check whether it is an ICE.
12069 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12070 return NoDiag();
12071 else
Richard Smith9e575da2012-12-28 13:25:52 +000012072 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000012073 }
12074 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012075 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000012076 }
John McCall864e3962010-05-07 05:32:02 +000012077 case Expr::UnaryOperatorClass: {
12078 const UnaryOperator *Exp = cast<UnaryOperator>(E);
12079 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000012080 case UO_PostInc:
12081 case UO_PostDec:
12082 case UO_PreInc:
12083 case UO_PreDec:
12084 case UO_AddrOf:
12085 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000012086 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000012087 // C99 6.6/3 allows increment and decrement within unevaluated
12088 // subexpressions of constant expressions, but they can never be ICEs
12089 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012090 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000012091 case UO_Extension:
12092 case UO_LNot:
12093 case UO_Plus:
12094 case UO_Minus:
12095 case UO_Not:
12096 case UO_Real:
12097 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000012098 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012099 }
Reid Klecknere540d972018-11-01 17:51:48 +000012100 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000012101 }
12102 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000012103 // Note that per C99, offsetof must be an ICE. And AFAIK, using
12104 // EvaluateAsRValue matches the proposed gcc behavior for cases like
12105 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
12106 // compliance: we should warn earlier for offsetof expressions with
12107 // array subscripts that aren't ICEs, and if the array subscripts
12108 // are ICEs, the value of the offsetof must be an integer constant.
12109 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000012110 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000012111 case Expr::UnaryExprOrTypeTraitExprClass: {
12112 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12113 if ((Exp->getKind() == UETT_SizeOf) &&
12114 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012115 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012116 return NoDiag();
12117 }
12118 case Expr::BinaryOperatorClass: {
12119 const BinaryOperator *Exp = cast<BinaryOperator>(E);
12120 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000012121 case BO_PtrMemD:
12122 case BO_PtrMemI:
12123 case BO_Assign:
12124 case BO_MulAssign:
12125 case BO_DivAssign:
12126 case BO_RemAssign:
12127 case BO_AddAssign:
12128 case BO_SubAssign:
12129 case BO_ShlAssign:
12130 case BO_ShrAssign:
12131 case BO_AndAssign:
12132 case BO_XorAssign:
12133 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000012134 // C99 6.6/3 allows assignments within unevaluated subexpressions of
12135 // constant expressions, but they can never be ICEs because an ICE cannot
12136 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012137 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012138
John McCalle3027922010-08-25 11:45:40 +000012139 case BO_Mul:
12140 case BO_Div:
12141 case BO_Rem:
12142 case BO_Add:
12143 case BO_Sub:
12144 case BO_Shl:
12145 case BO_Shr:
12146 case BO_LT:
12147 case BO_GT:
12148 case BO_LE:
12149 case BO_GE:
12150 case BO_EQ:
12151 case BO_NE:
12152 case BO_And:
12153 case BO_Xor:
12154 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000012155 case BO_Comma:
12156 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000012157 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12158 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000012159 if (Exp->getOpcode() == BO_Div ||
12160 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000012161 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000012162 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000012163 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000012164 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000012165 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012166 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012167 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000012168 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000012169 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012170 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012171 }
12172 }
12173 }
John McCalle3027922010-08-25 11:45:40 +000012174 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012175 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000012176 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12177 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000012178 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012179 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012180 } else {
12181 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012182 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012183 }
12184 }
Richard Smith9e575da2012-12-28 13:25:52 +000012185 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000012186 }
John McCalle3027922010-08-25 11:45:40 +000012187 case BO_LAnd:
12188 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000012189 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12190 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012191 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000012192 // Rare case where the RHS has a comma "side-effect"; we need
12193 // to actually check the condition to see whether the side
12194 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000012195 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000012196 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000012197 return RHSResult;
12198 return NoDiag();
12199 }
12200
Richard Smith9e575da2012-12-28 13:25:52 +000012201 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000012202 }
12203 }
Reid Klecknere540d972018-11-01 17:51:48 +000012204 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000012205 }
12206 case Expr::ImplicitCastExprClass:
12207 case Expr::CStyleCastExprClass:
12208 case Expr::CXXFunctionalCastExprClass:
12209 case Expr::CXXStaticCastExprClass:
12210 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000012211 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000012212 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000012213 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000012214 if (isa<ExplicitCastExpr>(E)) {
12215 if (const FloatingLiteral *FL
12216 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12217 unsigned DestWidth = Ctx.getIntWidth(E->getType());
12218 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12219 APSInt IgnoredVal(DestWidth, !DestSigned);
12220 bool Ignored;
12221 // If the value does not fit in the destination type, the behavior is
12222 // undefined, so we are not required to treat it as a constant
12223 // expression.
12224 if (FL->getValue().convertToInteger(IgnoredVal,
12225 llvm::APFloat::rmTowardZero,
12226 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012227 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000012228 return NoDiag();
12229 }
12230 }
Eli Friedman76d4e432011-09-29 21:49:34 +000012231 switch (cast<CastExpr>(E)->getCastKind()) {
12232 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000012233 case CK_AtomicToNonAtomic:
12234 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000012235 case CK_NoOp:
12236 case CK_IntegralToBoolean:
12237 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000012238 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000012239 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012240 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000012241 }
John McCall864e3962010-05-07 05:32:02 +000012242 }
John McCallc07a0c72011-02-17 10:25:35 +000012243 case Expr::BinaryConditionalOperatorClass: {
12244 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12245 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012246 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000012247 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012248 if (FalseResult.Kind == IK_NotICE) return FalseResult;
12249 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12250 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000012251 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000012252 return FalseResult;
12253 }
John McCall864e3962010-05-07 05:32:02 +000012254 case Expr::ConditionalOperatorClass: {
12255 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12256 // If the condition (ignoring parens) is a __builtin_constant_p call,
12257 // then only the true side is actually considered in an integer constant
12258 // expression, and it is fully evaluated. This is an important GNU
12259 // extension. See GCC PR38377 for discussion.
12260 if (const CallExpr *CallCE
12261 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000012262 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000012263 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000012264 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012265 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012266 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000012267
Richard Smithf57d8cb2011-12-09 22:58:01 +000012268 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12269 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000012270
Richard Smith9e575da2012-12-28 13:25:52 +000012271 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012272 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012273 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012274 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012275 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000012276 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012277 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000012278 return NoDiag();
12279 // Rare case where the diagnostics depend on which side is evaluated
12280 // Note that if we get here, CondResult is 0, and at least one of
12281 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000012282 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000012283 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000012284 return TrueResult;
12285 }
12286 case Expr::CXXDefaultArgExprClass:
12287 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000012288 case Expr::CXXDefaultInitExprClass:
12289 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012290 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000012291 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012292 }
12293 }
12294
David Blaikiee4d798f2012-01-20 21:50:17 +000012295 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000012296}
12297
Richard Smithf57d8cb2011-12-09 22:58:01 +000012298/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000012299static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000012300 const Expr *E,
12301 llvm::APSInt *Value,
12302 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000012303 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012304 if (Loc) *Loc = E->getExprLoc();
12305 return false;
12306 }
12307
Richard Smith66e05fe2012-01-18 05:21:49 +000012308 APValue Result;
12309 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000012310 return false;
12311
Richard Smith98710fc2014-11-13 23:03:19 +000012312 if (!Result.isInt()) {
12313 if (Loc) *Loc = E->getExprLoc();
12314 return false;
12315 }
12316
Richard Smith66e05fe2012-01-18 05:21:49 +000012317 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000012318 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012319}
12320
Craig Toppera31a8822013-08-22 07:09:37 +000012321bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
12322 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012323 assert(!isValueDependent() &&
12324 "Expression evaluator can't be called on a dependent expression.");
12325
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012326 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000012327 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000012328
Richard Smith9e575da2012-12-28 13:25:52 +000012329 ICEDiag D = CheckICE(this, Ctx);
12330 if (D.Kind != IK_ICE) {
12331 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000012332 return false;
12333 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000012334 return true;
12335}
12336
Craig Toppera31a8822013-08-22 07:09:37 +000012337bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000012338 SourceLocation *Loc, bool isEvaluated) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012339 assert(!isValueDependent() &&
12340 "Expression evaluator can't be called on a dependent expression.");
12341
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012342 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000012343 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
12344
12345 if (!isIntegerConstantExpr(Ctx, Loc))
12346 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000012347
Richard Smith5c40f092015-12-04 03:00:44 +000012348 // The only possible side-effects here are due to UB discovered in the
12349 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
12350 // required to treat the expression as an ICE, so we produce the folded
12351 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000012352 EvalResult ExprResult;
12353 Expr::EvalStatus Status;
12354 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
12355 Info.InConstantContext = true;
12356
12357 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000012358 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000012359
12360 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000012361 return true;
12362}
Richard Smith66e05fe2012-01-18 05:21:49 +000012363
Craig Toppera31a8822013-08-22 07:09:37 +000012364bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012365 assert(!isValueDependent() &&
12366 "Expression evaluator can't be called on a dependent expression.");
12367
Richard Smith9e575da2012-12-28 13:25:52 +000012368 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000012369}
12370
Craig Toppera31a8822013-08-22 07:09:37 +000012371bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000012372 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012373 assert(!isValueDependent() &&
12374 "Expression evaluator can't be called on a dependent expression.");
12375
Richard Smith66e05fe2012-01-18 05:21:49 +000012376 // We support this checking in C++98 mode in order to diagnose compatibility
12377 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012378 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000012379
Richard Smith98a0a492012-02-14 21:38:30 +000012380 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000012381 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012382 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000012383 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000012384 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000012385
12386 APValue Scratch;
12387 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
12388
12389 if (!Diags.empty()) {
12390 IsConstExpr = false;
12391 if (Loc) *Loc = Diags[0].first;
12392 } else if (!IsConstExpr) {
12393 // FIXME: This shouldn't happen.
12394 if (Loc) *Loc = getExprLoc();
12395 }
12396
12397 return IsConstExpr;
12398}
Richard Smith253c2a32012-01-27 01:14:48 +000012399
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012400bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
12401 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000012402 ArrayRef<const Expr*> Args,
12403 const Expr *This) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012404 assert(!isValueDependent() &&
12405 "Expression evaluator can't be called on a dependent expression.");
12406
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012407 Expr::EvalStatus Status;
12408 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000012409 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012410
George Burgess IV177399e2017-01-09 04:12:14 +000012411 LValue ThisVal;
12412 const LValue *ThisPtr = nullptr;
12413 if (This) {
12414#ifndef NDEBUG
12415 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
12416 assert(MD && "Don't provide `this` for non-methods.");
12417 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
12418#endif
12419 if (EvaluateObjectArgument(Info, This, ThisVal))
12420 ThisPtr = &ThisVal;
12421 if (Info.EvalStatus.HasSideEffects)
12422 return false;
12423 }
12424
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012425 ArgVector ArgValues(Args.size());
12426 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
12427 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000012428 if ((*I)->isValueDependent() ||
12429 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012430 // If evaluation fails, throw away the argument entirely.
12431 ArgValues[I - Args.begin()] = APValue();
12432 if (Info.EvalStatus.HasSideEffects)
12433 return false;
12434 }
12435
12436 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000012437 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012438 ArgValues.data());
12439 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
12440}
12441
Richard Smith253c2a32012-01-27 01:14:48 +000012442bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012443 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000012444 PartialDiagnosticAt> &Diags) {
12445 // FIXME: It would be useful to check constexpr function templates, but at the
12446 // moment the constant expression evaluator cannot cope with the non-rigorous
12447 // ASTs which we build for dependent expressions.
12448 if (FD->isDependentContext())
12449 return true;
12450
12451 Expr::EvalStatus Status;
12452 Status.Diag = &Diags;
12453
Richard Smith6d4c6582013-11-05 22:18:15 +000012454 EvalInfo Info(FD->getASTContext(), Status,
12455 EvalInfo::EM_PotentialConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000012456 Info.InConstantContext = true;
Richard Smith253c2a32012-01-27 01:14:48 +000012457
12458 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000012459 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000012460
Richard Smith7525ff62013-05-09 07:14:00 +000012461 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000012462 // is a temporary being used as the 'this' pointer.
12463 LValue This;
12464 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000012465 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000012466
Richard Smith253c2a32012-01-27 01:14:48 +000012467 ArrayRef<const Expr*> Args;
12468
Richard Smith2e312c82012-03-03 22:46:17 +000012469 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000012470 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
12471 // Evaluate the call as a constant initializer, to allow the construction
12472 // of objects of non-literal types.
12473 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000012474 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
12475 } else {
12476 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000012477 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000012478 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000012479 }
Richard Smith253c2a32012-01-27 01:14:48 +000012480
12481 return Diags.empty();
12482}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012483
12484bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
12485 const FunctionDecl *FD,
12486 SmallVectorImpl<
12487 PartialDiagnosticAt> &Diags) {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012488 assert(!E->isValueDependent() &&
12489 "Expression evaluator can't be called on a dependent expression.");
12490
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012491 Expr::EvalStatus Status;
12492 Status.Diag = &Diags;
12493
12494 EvalInfo Info(FD->getASTContext(), Status,
12495 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000012496 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012497
12498 // Fabricate a call stack frame to give the arguments a plausible cover story.
12499 ArrayRef<const Expr*> Args;
12500 ArgVector ArgValues(0);
12501 bool Success = EvaluateArgs(Args, ArgValues, Info);
12502 (void)Success;
12503 assert(Success &&
12504 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000012505 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012506
12507 APValue ResultScratch;
12508 Evaluate(ResultScratch, Info, E);
12509 return Diags.empty();
12510}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012511
12512bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
12513 unsigned Type) const {
12514 if (!getType()->isPointerType())
12515 return false;
12516
12517 Expr::EvalStatus Status;
12518 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000012519 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012520}