blob: 21cbd6dfa19069adc66b2ecff25c12cd6df432e3 [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"
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000050#include "llvm/ADT/Optional.h"
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000051#include "llvm/ADT/SmallBitVector.h"
Fangrui Song407659a2018-11-30 23:41:18 +000052#include "llvm/Support/SaveAndRestore.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000053#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000054#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000055#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000056
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000057#define DEBUG_TYPE "exprconstant"
58
Anders Carlsson7a241ba2008-07-03 04:20:39 +000059using namespace clang;
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000060using llvm::APInt;
Chris Lattner05706e882008-07-11 18:11:29 +000061using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000062using llvm::APFloat;
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000063using llvm::Optional;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000064
Richard Smithb228a862012-02-15 02:18:13 +000065static bool IsGlobalLValue(APValue::LValueBase B);
66
John McCall93d91dc2010-05-07 17:22:02 +000067namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000068 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000069 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000070 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000071
Eric Fiselier708afb52019-05-16 21:04:15 +000072 using SourceLocExprScopeGuard =
73 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
74
Richard Smithb228a862012-02-15 02:18:13 +000075 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000076 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000077 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000078 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000079 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000080 //
81 // extern int arr[]; void f() { extern int arr[3]; };
82 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000083 //
84 // For now, we take the array bound from the most recent declaration.
85 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
86 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
87 QualType T = Redecl->getType();
88 if (!T->isIncompleteArrayType())
89 return T;
90 }
91 return D->getType();
92 }
Richard Smith84401042013-06-03 05:03:02 +000093
Mikael Holmen3b6b2e32019-05-20 11:38:33 +000094 if (B.is<TypeInfoLValue>())
Richard Smithee0ce3022019-05-17 07:06:46 +000095 return B.getTypeInfoType();
96
Richard Smith84401042013-06-03 05:03:02 +000097 const Expr *Base = B.get<const Expr*>();
98
99 // For a materialized temporary, the type of the temporary we materialized
100 // may not be the type of the expression.
101 if (const MaterializeTemporaryExpr *MTE =
102 dyn_cast<MaterializeTemporaryExpr>(Base)) {
103 SmallVector<const Expr *, 2> CommaLHSs;
104 SmallVector<SubobjectAdjustment, 2> Adjustments;
105 const Expr *Temp = MTE->GetTemporaryExpr();
106 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
107 Adjustments);
108 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +0000109 // for it directly. Otherwise use the type after adjustment.
110 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +0000111 return Inner->getType();
112 }
113
114 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000115 }
116
Richard Smithd62306a2011-11-10 06:34:14 +0000117 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000118 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000119 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000120 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000121 }
122 /// Get an LValue path entry, which is known to not be an array index, as a
123 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000124 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000125 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000126 }
127 /// Determine whether this LValue path entry for a base class names a virtual
128 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000129 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000130 return E.getAsBaseOrMember().getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000131 }
132
George Burgess IVe3763372016-12-22 02:50:20 +0000133 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
134 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
135 const FunctionDecl *Callee = CE->getDirectCallee();
136 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
137 }
138
139 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
140 /// This will look through a single cast.
141 ///
142 /// Returns null if we couldn't unwrap a function with alloc_size.
143 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
144 if (!E->getType()->isPointerType())
145 return nullptr;
146
147 E = E->IgnoreParens();
148 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000149 // probably be a cast of some kind. In exotic cases, we might also see a
150 // top-level ExprWithCleanups. Ignore them either way.
Bill Wendling7c44da22018-10-31 03:48:47 +0000151 if (const auto *FE = dyn_cast<FullExpr>(E))
152 E = FE->getSubExpr()->IgnoreParens();
George Burgess IV47638762018-03-07 04:52:34 +0000153
George Burgess IVe3763372016-12-22 02:50:20 +0000154 if (const auto *Cast = dyn_cast<CastExpr>(E))
155 E = Cast->getSubExpr()->IgnoreParens();
156
157 if (const auto *CE = dyn_cast<CallExpr>(E))
158 return getAllocSizeAttr(CE) ? CE : nullptr;
159 return nullptr;
160 }
161
162 /// Determines whether or not the given Base contains a call to a function
163 /// with the alloc_size attribute.
164 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
165 const auto *E = Base.dyn_cast<const Expr *>();
166 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
167 }
168
Richard Smith6f4f0f12017-10-20 22:56:25 +0000169 /// The bound to claim that an array of unknown bound has.
170 /// The value in MostDerivedArraySize is undefined in this case. So, set it
171 /// to an arbitrary value that's likely to loudly break things if it's used.
172 static const uint64_t AssumedSizeForUnsizedArray =
173 std::numeric_limits<uint64_t>::max() / 2;
174
George Burgess IVe3763372016-12-22 02:50:20 +0000175 /// Determines if an LValue with the given LValueBase will have an unsized
176 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000177 /// Find the path length and type of the most-derived subobject in the given
178 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000179 static unsigned
180 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
181 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000182 uint64_t &ArraySize, QualType &Type, bool &IsArray,
183 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000184 // This only accepts LValueBases from APValues, and APValues don't support
185 // arrays that lack size info.
186 assert(!isBaseAnAllocSizeCall(Base) &&
187 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000188 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000189 Type = getType(Base);
190
Richard Smith80815602011-11-07 05:07:52 +0000191 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000192 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000193 const ArrayType *AT = Ctx.getAsArrayType(Type);
194 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000195 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000196 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000197
198 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
199 ArraySize = CAT->getSize().getZExtValue();
200 } else {
201 assert(I == 0 && "unexpected unsized array designator");
202 FirstEntryIsUnsizedArray = true;
203 ArraySize = AssumedSizeForUnsizedArray;
204 }
Richard Smith66c96992012-02-18 22:04:06 +0000205 } else if (Type->isAnyComplexType()) {
206 const ComplexType *CT = Type->castAs<ComplexType>();
207 Type = CT->getElementType();
208 ArraySize = 2;
209 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000210 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000211 } else if (const FieldDecl *FD = getAsField(Path[I])) {
212 Type = FD->getType();
213 ArraySize = 0;
214 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000215 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000216 } else {
Richard Smith80815602011-11-07 05:07:52 +0000217 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000218 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000219 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 }
Richard Smith80815602011-11-07 05:07:52 +0000221 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000222 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000223 }
224
Richard Smitha8105bc2012-01-06 16:39:00 +0000225 // The order of this enum is important for diagnostics.
226 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000227 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smithdebad642019-05-12 09:39:08 +0000228 CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000229 };
230
Richard Smith96e0c102011-11-04 02:25:55 +0000231 /// A path from a glvalue to a subobject of that glvalue.
232 struct SubobjectDesignator {
233 /// True if the subobject was named in a manner not supported by C++11. Such
234 /// lvalues can still be folded, but they are not core constant expressions
235 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000236 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000237
Richard Smitha8105bc2012-01-06 16:39:00 +0000238 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000239 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000240
Daniel Jasperffdee092017-05-02 19:21:42 +0000241 /// Indicator of whether the first entry is an unsized array.
242 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000243
George Burgess IVa51c4072015-10-16 01:49:01 +0000244 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000245 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000246
Richard Smitha8105bc2012-01-06 16:39:00 +0000247 /// The length of the path to the most-derived object of which this is a
248 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000249 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000250
George Burgess IVa51c4072015-10-16 01:49:01 +0000251 /// The size of the array of which the most-derived object is an element.
252 /// This will always be 0 if the most-derived object is not an array
253 /// element. 0 is not an indicator of whether or not the most-derived object
254 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000255 ///
256 /// If the current array is an unsized array, the value of this is
257 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000258 uint64_t MostDerivedArraySize;
259
260 /// The type of the most derived object referred to by this address.
261 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000262
Richard Smith80815602011-11-07 05:07:52 +0000263 typedef APValue::LValuePathEntry PathEntry;
264
Richard Smith96e0c102011-11-04 02:25:55 +0000265 /// The entries on the path from the glvalue to the designated subobject.
266 SmallVector<PathEntry, 8> Entries;
267
Richard Smitha8105bc2012-01-06 16:39:00 +0000268 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000269
Richard Smitha8105bc2012-01-06 16:39:00 +0000270 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000271 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000272 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000273 MostDerivedPathLength(0), MostDerivedArraySize(0),
274 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000275
276 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000277 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000278 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000279 MostDerivedPathLength(0), MostDerivedArraySize(0) {
280 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000281 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000282 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000283 ArrayRef<PathEntry> VEntries = V.getLValuePath();
284 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000285 if (V.getLValueBase()) {
286 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000287 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000288 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000289 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000290 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000291 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000292 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000293 }
Richard Smith80815602011-11-07 05:07:52 +0000294 }
295 }
296
Richard Smith31c69a32019-05-21 23:15:20 +0000297 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
298 unsigned NewLength) {
299 if (Invalid)
300 return;
301
302 assert(Base && "cannot truncate path for null pointer");
303 assert(NewLength <= Entries.size() && "not a truncation");
304
305 if (NewLength == Entries.size())
306 return;
307 Entries.resize(NewLength);
308
309 bool IsArray = false;
310 bool FirstIsUnsizedArray = false;
311 MostDerivedPathLength = findMostDerivedSubobject(
312 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
313 FirstIsUnsizedArray);
314 MostDerivedIsArrayElement = IsArray;
315 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
316 }
317
Richard Smith96e0c102011-11-04 02:25:55 +0000318 void setInvalid() {
319 Invalid = true;
320 Entries.clear();
321 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000322
George Burgess IVe3763372016-12-22 02:50:20 +0000323 /// Determine whether the most derived subobject is an array without a
324 /// known bound.
325 bool isMostDerivedAnUnsizedArray() const {
326 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000327 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000328 }
329
330 /// Determine what the most derived array's size is. Results in an assertion
331 /// failure if the most derived array lacks a size.
332 uint64_t getMostDerivedArraySize() const {
333 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
334 return MostDerivedArraySize;
335 }
336
Richard Smitha8105bc2012-01-06 16:39:00 +0000337 /// Determine whether this is a one-past-the-end pointer.
338 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000339 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000340 if (IsOnePastTheEnd)
341 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000342 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smith5b5e27a2019-05-10 20:05:31 +0000343 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
344 MostDerivedArraySize)
Richard Smitha8105bc2012-01-06 16:39:00 +0000345 return true;
346 return false;
347 }
348
Richard Smith06f71b52018-08-04 00:57:17 +0000349 /// Get the range of valid index adjustments in the form
350 /// {maximum value that can be subtracted from this pointer,
351 /// maximum value that can be added to this pointer}
352 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
353 if (Invalid || isMostDerivedAnUnsizedArray())
354 return {0, 0};
355
356 // [expr.add]p4: For the purposes of these operators, a pointer to a
357 // nonarray object behaves the same as a pointer to the first element of
358 // an array of length one with the type of the object as its element type.
359 bool IsArray = MostDerivedPathLength == Entries.size() &&
360 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000361 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
362 : (uint64_t)IsOnePastTheEnd;
Richard Smith06f71b52018-08-04 00:57:17 +0000363 uint64_t ArraySize =
364 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
365 return {ArrayIndex, ArraySize - ArrayIndex};
366 }
367
Richard Smitha8105bc2012-01-06 16:39:00 +0000368 /// Check that this refers to a valid subobject.
369 bool isValidSubobject() const {
370 if (Invalid)
371 return false;
372 return !isOnePastTheEnd();
373 }
374 /// Check that this refers to a valid subobject, and if not, produce a
375 /// relevant diagnostic and set the designator as invalid.
376 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
377
Richard Smith06f71b52018-08-04 00:57:17 +0000378 /// Get the type of the designated object.
379 QualType getType(ASTContext &Ctx) const {
380 assert(!Invalid && "invalid designator has no subobject type");
381 return MostDerivedPathLength == Entries.size()
382 ? MostDerivedType
383 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
384 }
385
Richard Smitha8105bc2012-01-06 16:39:00 +0000386 /// Update this designator to refer to the first element within this array.
387 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000388 Entries.push_back(PathEntry::ArrayIndex(0));
Richard Smitha8105bc2012-01-06 16:39:00 +0000389
390 // This is a most-derived object.
391 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000392 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000393 MostDerivedArraySize = CAT->getSize().getZExtValue();
394 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000395 }
George Burgess IVe3763372016-12-22 02:50:20 +0000396 /// Update this designator to refer to the first element within the array of
397 /// elements of type T. This is an array of unknown size.
398 void addUnsizedArrayUnchecked(QualType ElemTy) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000399 Entries.push_back(PathEntry::ArrayIndex(0));
George Burgess IVe3763372016-12-22 02:50:20 +0000400
401 MostDerivedType = ElemTy;
402 MostDerivedIsArrayElement = true;
403 // The value in MostDerivedArraySize is undefined in this case. So, set it
404 // to an arbitrary value that's likely to loudly break things if it's
405 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000406 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000407 MostDerivedPathLength = Entries.size();
408 }
Richard Smith96e0c102011-11-04 02:25:55 +0000409 /// Update this designator to refer to the given base or member of this
410 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000411 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000412 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
Richard Smitha8105bc2012-01-06 16:39:00 +0000413
414 // If this isn't a base class, it's a new most-derived object.
415 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
416 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000417 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000418 MostDerivedArraySize = 0;
419 MostDerivedPathLength = Entries.size();
420 }
Richard Smith96e0c102011-11-04 02:25:55 +0000421 }
Richard Smith66c96992012-02-18 22:04:06 +0000422 /// Update this designator to refer to the given complex component.
423 void addComplexUnchecked(QualType EltTy, bool Imag) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000424 Entries.push_back(PathEntry::ArrayIndex(Imag));
Richard Smith66c96992012-02-18 22:04:06 +0000425
426 // This is technically a most-derived object, though in practice this
427 // is unlikely to matter.
428 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000429 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000430 MostDerivedArraySize = 2;
431 MostDerivedPathLength = Entries.size();
432 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000433 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000434 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
435 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000436 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000437 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
438 if (Invalid || !N) return;
439 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
440 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000441 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000442 // Can't verify -- trust that the user is doing the right thing (or if
443 // not, trust that the caller will catch the bad behavior).
444 // FIXME: Should we reject if this overflows, at least?
Richard Smith5b5e27a2019-05-10 20:05:31 +0000445 Entries.back() = PathEntry::ArrayIndex(
446 Entries.back().getAsArrayIndex() + TruncatedN);
Daniel Jasperffdee092017-05-02 19:21:42 +0000447 return;
448 }
449
450 // [expr.add]p4: For the purposes of these operators, a pointer to a
451 // nonarray object behaves the same as a pointer to the first element of
452 // an array of length one with the type of the object as its element type.
453 bool IsArray = MostDerivedPathLength == Entries.size() &&
454 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000455 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
456 : (uint64_t)IsOnePastTheEnd;
Daniel Jasperffdee092017-05-02 19:21:42 +0000457 uint64_t ArraySize =
458 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
459
460 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
461 // Calculate the actual index in a wide enough type, so we can include
462 // it in the note.
463 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
464 (llvm::APInt&)N += ArrayIndex;
465 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
466 diagnosePointerArithmetic(Info, E, N);
467 setInvalid();
468 return;
469 }
470
471 ArrayIndex += TruncatedN;
472 assert(ArrayIndex <= ArraySize &&
473 "bounds check succeeded for out-of-bounds index");
474
475 if (IsArray)
Richard Smith5b5e27a2019-05-10 20:05:31 +0000476 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
Daniel Jasperffdee092017-05-02 19:21:42 +0000477 else
478 IsOnePastTheEnd = (ArrayIndex != 0);
479 }
Richard Smith96e0c102011-11-04 02:25:55 +0000480 };
481
Richard Smith254a73d2011-10-28 22:34:42 +0000482 /// A stack frame in the constexpr call stack.
483 struct CallStackFrame {
484 EvalInfo &Info;
485
486 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000487 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000488
Richard Smithf6f003a2011-12-16 19:06:07 +0000489 /// Callee - The function which was called.
490 const FunctionDecl *Callee;
491
Richard Smithd62306a2011-11-10 06:34:14 +0000492 /// This - The binding for the this pointer in this call, if any.
493 const LValue *This;
494
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000495 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000496 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000497 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000498
Eric Fiselier708afb52019-05-16 21:04:15 +0000499 /// Source location information about the default argument or default
500 /// initializer expression we're evaluating, if any.
501 CurrentSourceLocExprScope CurSourceLocExprScope;
502
Eli Friedman4830ec82012-06-25 21:21:08 +0000503 // Note that we intentionally use std::map here so that references to
504 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000505 typedef std::pair<const void *, unsigned> MapKeyTy;
506 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000507 /// Temporaries - Temporary lvalues materialized within this stack frame.
508 MapTy Temporaries;
509
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000510 /// CallLoc - The location of the call expression for this call.
511 SourceLocation CallLoc;
512
513 /// Index - The call index of this call.
514 unsigned Index;
515
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000516 /// The stack of integers for tracking version numbers for temporaries.
517 SmallVector<unsigned, 2> TempVersionStack = {1};
518 unsigned CurTempVersion = TempVersionStack.back();
519
520 unsigned getTempVersion() const { return TempVersionStack.back(); }
521
522 void pushTempVersion() {
523 TempVersionStack.push_back(++CurTempVersion);
524 }
525
526 void popTempVersion() {
527 TempVersionStack.pop_back();
528 }
529
Faisal Vali051e3a22017-02-16 04:12:21 +0000530 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000531 // on the overall stack usage of deeply-recursing constexpr evaluations.
Faisal Vali051e3a22017-02-16 04:12:21 +0000532 // (We should cache this map rather than recomputing it repeatedly.)
533 // But let's try this and see how it goes; we can look into caching the map
534 // as a later change.
535
536 /// LambdaCaptureFields - Mapping from captured variables/this to
537 /// corresponding data members in the closure class.
538 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
539 FieldDecl *LambdaThisCaptureField;
540
Richard Smithf6f003a2011-12-16 19:06:07 +0000541 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
542 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000543 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000544 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000545
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000546 // Return the temporary for Key whose version number is Version.
547 APValue *getTemporary(const void *Key, unsigned Version) {
548 MapKeyTy KV(Key, Version);
549 auto LB = Temporaries.lower_bound(KV);
550 if (LB != Temporaries.end() && LB->first == KV)
551 return &LB->second;
552 // Pair (Key,Version) wasn't found in the map. Check that no elements
553 // in the map have 'Key' as their key.
554 assert((LB == Temporaries.end() || LB->first.first != Key) &&
555 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
556 "Element with key 'Key' found in map");
557 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000558 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000559
560 // Return the current temporary for Key in the map.
561 APValue *getCurrentTemporary(const void *Key) {
562 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
563 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
564 return &std::prev(UB)->second;
565 return nullptr;
566 }
567
568 // Return the version number of the current temporary for Key.
569 unsigned getCurrentTemporaryVersion(const void *Key) const {
570 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
571 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
572 return std::prev(UB)->first.second;
573 return 0;
574 }
575
Richard Smith08d6a2c2013-07-24 07:11:57 +0000576 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000577 };
578
Richard Smith852c9db2013-04-20 22:23:05 +0000579 /// Temporarily override 'this'.
580 class ThisOverrideRAII {
581 public:
582 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
583 : Frame(Frame), OldThis(Frame.This) {
584 if (Enable)
585 Frame.This = NewThis;
586 }
587 ~ThisOverrideRAII() {
588 Frame.This = OldThis;
589 }
590 private:
591 CallStackFrame &Frame;
592 const LValue *OldThis;
593 };
594
Richard Smith92b1ce02011-12-12 09:28:41 +0000595 /// A partial diagnostic which we might know in advance that we are not going
596 /// to emit.
597 class OptionalDiagnostic {
598 PartialDiagnostic *Diag;
599
600 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000601 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
602 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000603
604 template<typename T>
605 OptionalDiagnostic &operator<<(const T &v) {
606 if (Diag)
607 *Diag << v;
608 return *this;
609 }
Richard Smithfe800032012-01-31 04:08:20 +0000610
611 OptionalDiagnostic &operator<<(const APSInt &I) {
612 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000613 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000614 I.toString(Buffer);
615 *Diag << StringRef(Buffer.data(), Buffer.size());
616 }
617 return *this;
618 }
619
620 OptionalDiagnostic &operator<<(const APFloat &F) {
621 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000622 // FIXME: Force the precision of the source value down so we don't
623 // print digits which are usually useless (we don't really care here if
624 // we truncate a digit by accident in edge cases). Ideally,
Fangrui Song6907ce22018-07-30 19:24:48 +0000625 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000626 // representation which rounds to the correct value, but it's a bit
627 // tricky to implement.
628 unsigned precision =
629 llvm::APFloat::semanticsPrecision(F.getSemantics());
630 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000631 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000632 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000633 *Diag << StringRef(Buffer.data(), Buffer.size());
634 }
635 return *this;
636 }
Leonard Chand3f3e162019-01-18 21:04:25 +0000637
638 OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
639 if (Diag) {
640 SmallVector<char, 32> Buffer;
641 FX.toString(Buffer);
642 *Diag << StringRef(Buffer.data(), Buffer.size());
643 }
644 return *this;
645 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000646 };
647
Richard Smith08d6a2c2013-07-24 07:11:57 +0000648 /// A cleanup, and a flag indicating whether it is lifetime-extended.
649 class Cleanup {
650 llvm::PointerIntPair<APValue*, 1, bool> Value;
651
652 public:
653 Cleanup(APValue *Val, bool IsLifetimeExtended)
654 : Value(Val, IsLifetimeExtended) {}
655
656 bool isLifetimeExtended() const { return Value.getInt(); }
657 void endLifetime() {
658 *Value.getPointer() = APValue();
659 }
660 };
661
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000662 /// A reference to an object whose construction we are currently evaluating.
663 struct ObjectUnderConstruction {
664 APValue::LValueBase Base;
665 ArrayRef<APValue::LValuePathEntry> Path;
666 friend bool operator==(const ObjectUnderConstruction &LHS,
667 const ObjectUnderConstruction &RHS) {
668 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
669 }
670 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
671 return llvm::hash_combine(Obj.Base, Obj.Path);
672 }
673 };
674 enum class ConstructionPhase { None, Bases, AfterBases };
675}
676
677namespace llvm {
678template<> struct DenseMapInfo<ObjectUnderConstruction> {
679 using Base = DenseMapInfo<APValue::LValueBase>;
680 static ObjectUnderConstruction getEmptyKey() {
681 return {Base::getEmptyKey(), {}}; }
682 static ObjectUnderConstruction getTombstoneKey() {
683 return {Base::getTombstoneKey(), {}};
684 }
685 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
686 return hash_value(Object);
687 }
688 static bool isEqual(const ObjectUnderConstruction &LHS,
689 const ObjectUnderConstruction &RHS) {
690 return LHS == RHS;
691 }
692};
693}
694
695namespace {
Richard Smithb228a862012-02-15 02:18:13 +0000696 /// EvalInfo - This is a private struct used by the evaluator to capture
697 /// information about a subexpression as it is folded. It retains information
698 /// about the AST context, but also maintains information about the folded
699 /// expression.
700 ///
701 /// If an expression could be evaluated, it is still possible it is not a C
702 /// "integer constant expression" or constant expression. If not, this struct
703 /// captures information about how and why not.
704 ///
705 /// One bit of information passed *into* the request for constant folding
706 /// indicates whether the subexpression is "evaluated" or not according to C
707 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
708 /// evaluate the expression regardless of what the RHS is, but C only allows
709 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000710 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000711 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000712
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000713 /// EvalStatus - Contains information about the evaluation.
714 Expr::EvalStatus &EvalStatus;
715
716 /// CurrentCall - The top of the constexpr call stack.
717 CallStackFrame *CurrentCall;
718
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000719 /// CallStackDepth - The number of calls in the call stack right now.
720 unsigned CallStackDepth;
721
Richard Smithb228a862012-02-15 02:18:13 +0000722 /// NextCallIndex - The next call index to assign.
723 unsigned NextCallIndex;
724
Richard Smitha3d3bd22013-05-08 02:12:03 +0000725 /// StepsLeft - The remaining number of evaluation steps we're permitted
726 /// to perform. This is essentially a limit for the number of statements
727 /// we will evaluate.
728 unsigned StepsLeft;
729
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000730 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000731 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000732 CallStackFrame BottomFrame;
733
Richard Smith08d6a2c2013-07-24 07:11:57 +0000734 /// A stack of values whose lifetimes end at the end of some surrounding
735 /// evaluation frame.
736 llvm::SmallVector<Cleanup, 16> CleanupStack;
737
Richard Smithd62306a2011-11-10 06:34:14 +0000738 /// EvaluatingDecl - This is the declaration whose initializer is being
739 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000740 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000741
742 /// EvaluatingDeclValue - This is the value being constructed for the
743 /// declaration whose initializer is being evaluated, if any.
744 APValue *EvaluatingDeclValue;
745
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000746 /// Set of objects that are currently being constructed.
747 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
748 ObjectsUnderConstruction;
Erik Pilkington42925492017-10-04 00:18:55 +0000749
750 struct EvaluatingConstructorRAII {
751 EvalInfo &EI;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000752 ObjectUnderConstruction Object;
Erik Pilkington42925492017-10-04 00:18:55 +0000753 bool DidInsert;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000754 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
755 bool HasBases)
Erik Pilkington42925492017-10-04 00:18:55 +0000756 : EI(EI), Object(Object) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000757 DidInsert =
758 EI.ObjectsUnderConstruction
759 .insert({Object, HasBases ? ConstructionPhase::Bases
760 : ConstructionPhase::AfterBases})
761 .second;
762 }
763 void finishedConstructingBases() {
764 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
Erik Pilkington42925492017-10-04 00:18:55 +0000765 }
766 ~EvaluatingConstructorRAII() {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000767 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
Erik Pilkington42925492017-10-04 00:18:55 +0000768 }
769 };
770
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000771 ConstructionPhase
772 isEvaluatingConstructor(APValue::LValueBase Base,
773 ArrayRef<APValue::LValuePathEntry> Path) {
774 return ObjectsUnderConstruction.lookup({Base, Path});
Erik Pilkington42925492017-10-04 00:18:55 +0000775 }
776
Richard Smith37be3362019-05-04 04:00:45 +0000777 /// If we're currently speculatively evaluating, the outermost call stack
778 /// depth at which we can mutate state, otherwise 0.
779 unsigned SpeculativeEvaluationDepth = 0;
780
Richard Smith410306b2016-12-12 02:53:20 +0000781 /// The current array initialization index, if we're performing array
782 /// initialization.
783 uint64_t ArrayInitIndex = -1;
784
Richard Smith357362d2011-12-13 06:39:58 +0000785 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
786 /// notes attached to it will also be stored, otherwise they will not be.
787 bool HasActiveDiagnostic;
788
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000789 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000790 /// fold (not just why it's not strictly a constant expression)?
791 bool HasFoldFailureDiagnostic;
792
Fangrui Song407659a2018-11-30 23:41:18 +0000793 /// Whether or not we're in a context where the front end requires a
794 /// constant value.
795 bool InConstantContext;
796
Richard Smith6d4c6582013-11-05 22:18:15 +0000797 enum EvaluationMode {
798 /// Evaluate as a constant expression. Stop if we find that the expression
799 /// is not a constant expression.
800 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000801
Richard Smith6d4c6582013-11-05 22:18:15 +0000802 /// Evaluate as a potential constant expression. Keep going if we hit a
803 /// construct that we can't evaluate yet (because we don't yet know the
804 /// value of something) but stop if we hit something that could never be
805 /// a constant expression.
806 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000807
Richard Smith6d4c6582013-11-05 22:18:15 +0000808 /// Fold the expression to a constant. Stop if we hit a side-effect that
809 /// we can't model.
810 EM_ConstantFold,
811
812 /// Evaluate the expression looking for integer overflow and similar
813 /// issues. Don't worry about side-effects, and try to visit all
814 /// subexpressions.
815 EM_EvaluateForOverflow,
816
817 /// Evaluate in any way we know how. Don't worry about side-effects that
818 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000819 EM_IgnoreSideEffects,
820
821 /// Evaluate as a constant expression. Stop if we find that the expression
822 /// is not a constant expression. Some expressions can be retried in the
823 /// optimizer if we don't constant fold them here, but in an unevaluated
824 /// context we try to fold them immediately since the optimizer never
825 /// gets a chance to look at it.
826 EM_ConstantExpressionUnevaluated,
827
828 /// Evaluate as a potential constant expression. Keep going if we hit a
829 /// construct that we can't evaluate yet (because we don't yet know the
830 /// value of something) but stop if we hit something that could never be
831 /// a constant expression. Some expressions can be retried in the
832 /// optimizer if we don't constant fold them here, but in an unevaluated
833 /// context we try to fold them immediately since the optimizer never
834 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000835 EM_PotentialConstantExpressionUnevaluated,
Richard Smith6d4c6582013-11-05 22:18:15 +0000836 } EvalMode;
837
838 /// Are we checking whether the expression is a potential constant
839 /// expression?
840 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000841 return EvalMode == EM_PotentialConstantExpression ||
842 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000843 }
844
845 /// Are we checking an expression for overflow?
846 // FIXME: We should check for any kind of undefined or suspicious behavior
847 // in such constructs, not just overflow.
848 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
849
850 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000851 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000852 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000853 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000854 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
855 EvaluatingDecl((const ValueDecl *)nullptr),
856 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
Richard Smith37be3362019-05-04 04:00:45 +0000857 HasFoldFailureDiagnostic(false),
Fangrui Song407659a2018-11-30 23:41:18 +0000858 InConstantContext(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000859
Richard Smith7525ff62013-05-09 07:14:00 +0000860 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
861 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000862 EvaluatingDeclValue = &Value;
863 }
864
David Blaikiebbafb8a2012-03-11 07:00:24 +0000865 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000866
Richard Smith357362d2011-12-13 06:39:58 +0000867 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000868 // Don't perform any constexpr calls (other than the call we're checking)
869 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000870 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000871 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000872 if (NextCallIndex == 0) {
873 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000874 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000875 return false;
876 }
Richard Smith357362d2011-12-13 06:39:58 +0000877 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
878 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000879 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000880 << getLangOpts().ConstexprCallDepth;
881 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000882 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000883
Richard Smith37be3362019-05-04 04:00:45 +0000884 std::pair<CallStackFrame *, unsigned>
885 getCallFrameAndDepth(unsigned CallIndex) {
886 assert(CallIndex && "no call index in getCallFrameAndDepth");
Richard Smithb228a862012-02-15 02:18:13 +0000887 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
888 // be null in this loop.
Richard Smith37be3362019-05-04 04:00:45 +0000889 unsigned Depth = CallStackDepth;
Richard Smithb228a862012-02-15 02:18:13 +0000890 CallStackFrame *Frame = CurrentCall;
Richard Smith37be3362019-05-04 04:00:45 +0000891 while (Frame->Index > CallIndex) {
Richard Smithb228a862012-02-15 02:18:13 +0000892 Frame = Frame->Caller;
Richard Smith37be3362019-05-04 04:00:45 +0000893 --Depth;
894 }
895 if (Frame->Index == CallIndex)
896 return {Frame, Depth};
897 return {nullptr, 0};
Richard Smithb228a862012-02-15 02:18:13 +0000898 }
899
Richard Smitha3d3bd22013-05-08 02:12:03 +0000900 bool nextStep(const Stmt *S) {
901 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000902 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000903 return false;
904 }
905 --StepsLeft;
906 return true;
907 }
908
Richard Smith357362d2011-12-13 06:39:58 +0000909 private:
910 /// Add a diagnostic to the diagnostics list.
911 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
912 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
913 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
914 return EvalStatus.Diag->back().second;
915 }
916
Richard Smithf6f003a2011-12-16 19:06:07 +0000917 /// Add notes containing a call stack to the current point of evaluation.
918 void addCallStack(unsigned Limit);
919
Faisal Valie690b7a2016-07-02 22:34:24 +0000920 private:
921 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
922 unsigned ExtraNotes, bool IsCCEDiag) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000923
Richard Smith92b1ce02011-12-12 09:28:41 +0000924 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000925 // If we have a prior diagnostic, it will be noting that the expression
926 // isn't a constant expression. This diagnostic is more important,
927 // unless we require this evaluation to produce a constant expression.
928 //
929 // FIXME: We might want to show both diagnostics to the user in
930 // EM_ConstantFold mode.
931 if (!EvalStatus.Diag->empty()) {
932 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000933 case EM_ConstantFold:
934 case EM_IgnoreSideEffects:
935 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000936 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000937 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000938 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000939 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000940 case EM_ConstantExpression:
941 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000942 case EM_ConstantExpressionUnevaluated:
943 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000944 HasActiveDiagnostic = false;
945 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000946 }
947 }
948
Richard Smithf6f003a2011-12-16 19:06:07 +0000949 unsigned CallStackNotes = CallStackDepth - 1;
950 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
951 if (Limit)
952 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000953 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000954 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000955
Richard Smith357362d2011-12-13 06:39:58 +0000956 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000957 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000958 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000959 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
960 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000961 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000962 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000963 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000964 }
Richard Smith357362d2011-12-13 06:39:58 +0000965 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000966 return OptionalDiagnostic();
967 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000968 public:
969 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
970 OptionalDiagnostic
971 FFDiag(SourceLocation Loc,
972 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
973 unsigned ExtraNotes = 0) {
974 return Diag(Loc, DiagId, ExtraNotes, false);
975 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000976
Faisal Valie690b7a2016-07-02 22:34:24 +0000977 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000978 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000979 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000980 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000981 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000982 HasActiveDiagnostic = false;
983 return OptionalDiagnostic();
984 }
985
Richard Smith92b1ce02011-12-12 09:28:41 +0000986 /// Diagnose that the evaluation does not produce a C++11 core constant
987 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000988 ///
989 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
990 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000991 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000992 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000993 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000994 // Don't override a previous diagnostic. Don't bother collecting
995 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000996 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000997 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000998 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000999 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001000 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +00001001 }
Faisal Valie690b7a2016-07-02 22:34:24 +00001002 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
1003 = diag::note_invalid_subexpr_in_const_expr,
1004 unsigned ExtraNotes = 0) {
1005 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
1006 }
Richard Smith357362d2011-12-13 06:39:58 +00001007 /// Add a note to a prior diagnostic.
1008 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
1009 if (!HasActiveDiagnostic)
1010 return OptionalDiagnostic();
1011 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +00001012 }
Richard Smithd0b4dd62011-12-19 06:19:21 +00001013
1014 /// Add a stack of notes to a prior diagnostic.
1015 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
1016 if (HasActiveDiagnostic) {
1017 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
1018 Diags.begin(), Diags.end());
1019 }
1020 }
Richard Smith253c2a32012-01-27 01:14:48 +00001021
Richard Smith6d4c6582013-11-05 22:18:15 +00001022 /// Should we continue evaluation after encountering a side-effect that we
1023 /// couldn't model?
1024 bool keepEvaluatingAfterSideEffect() {
1025 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00001026 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001027 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001028 case EM_EvaluateForOverflow:
1029 case EM_IgnoreSideEffects:
1030 return true;
1031
Richard Smith6d4c6582013-11-05 22:18:15 +00001032 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001033 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001034 case EM_ConstantFold:
1035 return false;
1036 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001037 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +00001038 }
1039
1040 /// Note that we have had a side-effect, and determine whether we should
1041 /// keep evaluating.
1042 bool noteSideEffect() {
1043 EvalStatus.HasSideEffects = true;
1044 return keepEvaluatingAfterSideEffect();
1045 }
1046
Richard Smithce8eca52015-12-08 03:21:47 +00001047 /// Should we continue evaluation after encountering undefined behavior?
1048 bool keepEvaluatingAfterUndefinedBehavior() {
1049 switch (EvalMode) {
1050 case EM_EvaluateForOverflow:
1051 case EM_IgnoreSideEffects:
1052 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +00001053 return true;
1054
1055 case EM_PotentialConstantExpression:
1056 case EM_PotentialConstantExpressionUnevaluated:
1057 case EM_ConstantExpression:
1058 case EM_ConstantExpressionUnevaluated:
1059 return false;
1060 }
1061 llvm_unreachable("Missed EvalMode case");
1062 }
1063
1064 /// Note that we hit something that was technically undefined behavior, but
1065 /// that we can evaluate past it (such as signed overflow or floating-point
1066 /// division by zero.)
1067 bool noteUndefinedBehavior() {
1068 EvalStatus.HasUndefinedBehavior = true;
1069 return keepEvaluatingAfterUndefinedBehavior();
1070 }
1071
Richard Smith253c2a32012-01-27 01:14:48 +00001072 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001073 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +00001074 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +00001075 if (!StepsLeft)
1076 return false;
1077
1078 switch (EvalMode) {
1079 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001080 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001081 case EM_EvaluateForOverflow:
1082 return true;
1083
1084 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001085 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001086 case EM_ConstantFold:
1087 case EM_IgnoreSideEffects:
1088 return false;
1089 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001090 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001091 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001092
George Burgess IV8c892b52016-05-25 22:31:54 +00001093 /// Notes that we failed to evaluate an expression that other expressions
1094 /// directly depend on, and determine if we should keep evaluating. This
1095 /// should only be called if we actually intend to keep evaluating.
1096 ///
1097 /// Call noteSideEffect() instead if we may be able to ignore the value that
1098 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1099 ///
1100 /// (Foo(), 1) // use noteSideEffect
1101 /// (Foo() || true) // use noteSideEffect
1102 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001103 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001104 // Failure when evaluating some expression often means there is some
1105 // subexpression whose evaluation was skipped. Therefore, (because we
1106 // don't track whether we skipped an expression when unwinding after an
1107 // evaluation failure) every evaluation failure that bubbles up from a
1108 // subexpression implies that a side-effect has potentially happened. We
1109 // skip setting the HasSideEffects flag to true until we decide to
1110 // continue evaluating after that point, which happens here.
1111 bool KeepGoing = keepEvaluatingAfterFailure();
1112 EvalStatus.HasSideEffects |= KeepGoing;
1113 return KeepGoing;
1114 }
1115
Richard Smith410306b2016-12-12 02:53:20 +00001116 class ArrayInitLoopIndex {
1117 EvalInfo &Info;
1118 uint64_t OuterIndex;
1119
1120 public:
1121 ArrayInitLoopIndex(EvalInfo &Info)
1122 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1123 Info.ArrayInitIndex = 0;
1124 }
1125 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1126
1127 operator uint64_t&() { return Info.ArrayInitIndex; }
1128 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001129 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001130
1131 /// Object used to treat all foldable expressions as constant expressions.
1132 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001133 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001134 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001135 bool HadNoPriorDiags;
1136 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001137
Richard Smith6d4c6582013-11-05 22:18:15 +00001138 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1139 : Info(Info),
1140 Enabled(Enabled),
1141 HadNoPriorDiags(Info.EvalStatus.Diag &&
1142 Info.EvalStatus.Diag->empty() &&
1143 !Info.EvalStatus.HasSideEffects),
1144 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001145 if (Enabled &&
1146 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1147 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001148 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001149 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001150 void keepDiagnostics() { Enabled = false; }
1151 ~FoldConstant() {
1152 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001153 !Info.EvalStatus.HasSideEffects)
1154 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001155 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001156 }
1157 };
Richard Smith17100ba2012-02-16 02:46:34 +00001158
James Y Knight892b09b2018-10-10 02:53:43 +00001159 /// RAII object used to set the current evaluation mode to ignore
1160 /// side-effects.
1161 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001162 EvalInfo &Info;
1163 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001164 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001165 : Info(Info), OldMode(Info.EvalMode) {
1166 if (!Info.checkingPotentialConstantExpression())
James Y Knight892b09b2018-10-10 02:53:43 +00001167 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001168 }
1169
James Y Knight892b09b2018-10-10 02:53:43 +00001170 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001171 };
1172
George Burgess IV8c892b52016-05-25 22:31:54 +00001173 /// RAII object used to optionally suppress diagnostics and side-effects from
1174 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001175 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001176 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001177 Expr::EvalStatus OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001178 unsigned OldSpeculativeEvaluationDepth;
Richard Smith17100ba2012-02-16 02:46:34 +00001179
George Burgess IV8c892b52016-05-25 22:31:54 +00001180 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001181 Info = Other.Info;
1182 OldStatus = Other.OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001183 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001184 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001185 }
1186
1187 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001188 if (!Info)
1189 return;
1190
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001191 Info->EvalStatus = OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001192 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
George Burgess IV8c892b52016-05-25 22:31:54 +00001193 }
1194
Richard Smith17100ba2012-02-16 02:46:34 +00001195 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001196 SpeculativeEvaluationRAII() = default;
1197
1198 SpeculativeEvaluationRAII(
1199 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001200 : Info(&Info), OldStatus(Info.EvalStatus),
Richard Smith37be3362019-05-04 04:00:45 +00001201 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
Richard Smith17100ba2012-02-16 02:46:34 +00001202 Info.EvalStatus.Diag = NewDiag;
Richard Smith37be3362019-05-04 04:00:45 +00001203 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
Richard Smith17100ba2012-02-16 02:46:34 +00001204 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001205
1206 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1207 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1208 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001209 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001210
1211 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1212 maybeRestoreState();
1213 moveFromAndCancel(std::move(Other));
1214 return *this;
1215 }
1216
1217 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001218 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001219
1220 /// RAII object wrapping a full-expression or block scope, and handling
1221 /// the ending of the lifetime of temporaries created within it.
1222 template<bool IsFullExpression>
1223 class ScopeRAII {
1224 EvalInfo &Info;
1225 unsigned OldStackSize;
1226 public:
1227 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001228 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1229 // Push a new temporary version. This is needed to distinguish between
1230 // temporaries created in different iterations of a loop.
1231 Info.CurrentCall->pushTempVersion();
1232 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001233 ~ScopeRAII() {
1234 // Body moved to a static method to encourage the compiler to inline away
1235 // instances of this class.
1236 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001237 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001238 }
1239 private:
1240 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1241 unsigned NewEnd = OldStackSize;
1242 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1243 I != N; ++I) {
1244 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1245 // Full-expression cleanup of a lifetime-extended temporary: nothing
1246 // to do, just move this cleanup to the right place in the stack.
1247 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1248 ++NewEnd;
1249 } else {
1250 // End the lifetime of the object.
1251 Info.CleanupStack[I].endLifetime();
1252 }
1253 }
1254 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1255 Info.CleanupStack.end());
1256 }
1257 };
1258 typedef ScopeRAII<false> BlockScopeRAII;
1259 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001260}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001261
Richard Smitha8105bc2012-01-06 16:39:00 +00001262bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1263 CheckSubobjectKind CSK) {
1264 if (Invalid)
1265 return false;
1266 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001267 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001268 << CSK;
1269 setInvalid();
1270 return false;
1271 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001272 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1273 // must actually be at least one array element; even a VLA cannot have a
1274 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001275 return true;
1276}
1277
Richard Smith6f4f0f12017-10-20 22:56:25 +00001278void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1279 const Expr *E) {
1280 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1281 // Do not set the designator as invalid: we can represent this situation,
1282 // and correct handling of __builtin_object_size requires us to do so.
1283}
1284
Richard Smitha8105bc2012-01-06 16:39:00 +00001285void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001286 const Expr *E,
1287 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001288 // If we're complaining, we must be able to statically determine the size of
1289 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001290 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001291 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001292 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001293 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001294 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001295 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001296 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001297 setInvalid();
1298}
1299
Richard Smithf6f003a2011-12-16 19:06:07 +00001300CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1301 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001302 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001303 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1304 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001305 Info.CurrentCall = this;
1306 ++Info.CallStackDepth;
1307}
1308
1309CallStackFrame::~CallStackFrame() {
1310 assert(Info.CurrentCall == this && "calls retired out of order");
1311 --Info.CallStackDepth;
1312 Info.CurrentCall = Caller;
1313}
1314
Richard Smith08d6a2c2013-07-24 07:11:57 +00001315APValue &CallStackFrame::createTemporary(const void *Key,
1316 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001317 unsigned Version = Info.CurrentCall->getTempVersion();
1318 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smithe637cbe2019-05-21 23:15:18 +00001319 assert(Result.isAbsent() && "temporary created multiple times");
Richard Smith08d6a2c2013-07-24 07:11:57 +00001320 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1321 return Result;
1322}
1323
Richard Smith84401042013-06-03 05:03:02 +00001324static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001325
1326void EvalInfo::addCallStack(unsigned Limit) {
1327 // Determine which calls to skip, if any.
1328 unsigned ActiveCalls = CallStackDepth - 1;
1329 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1330 if (Limit && Limit < ActiveCalls) {
1331 SkipStart = Limit / 2 + Limit % 2;
1332 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001333 }
1334
Richard Smithf6f003a2011-12-16 19:06:07 +00001335 // Walk the call stack and add the diagnostics.
1336 unsigned CallIdx = 0;
1337 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1338 Frame = Frame->Caller, ++CallIdx) {
1339 // Skip this call?
1340 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1341 if (CallIdx == SkipStart) {
1342 // Note that we're skipping calls.
1343 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1344 << unsigned(ActiveCalls - Limit);
1345 }
1346 continue;
1347 }
1348
Richard Smith5179eb72016-06-28 19:03:57 +00001349 // Use a different note for an inheriting constructor, because from the
1350 // user's perspective it's not really a function at all.
1351 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1352 if (CD->isInheritingConstructor()) {
1353 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1354 << CD->getParent();
1355 continue;
1356 }
1357 }
1358
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001359 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001360 llvm::raw_svector_ostream Out(Buffer);
1361 describeCall(Frame, Out);
1362 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1363 }
1364}
1365
Richard Smithdebad642019-05-12 09:39:08 +00001366/// Kinds of access we can perform on an object, for diagnostics. Note that
1367/// we consider a member function call to be a kind of access, even though
1368/// it is not formally an access of the object, because it has (largely) the
1369/// same set of semantic restrictions.
Hubert Tong147b7432018-12-12 16:53:43 +00001370enum AccessKinds {
1371 AK_Read,
1372 AK_Assign,
1373 AK_Increment,
Richard Smithdebad642019-05-12 09:39:08 +00001374 AK_Decrement,
1375 AK_MemberCall,
Richard Smith7bd54ab2019-05-15 20:22:21 +00001376 AK_DynamicCast,
Richard Smitha9330302019-05-17 19:19:28 +00001377 AK_TypeId,
Hubert Tong147b7432018-12-12 16:53:43 +00001378};
1379
Richard Smithdebad642019-05-12 09:39:08 +00001380static bool isModification(AccessKinds AK) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00001381 switch (AK) {
1382 case AK_Read:
1383 case AK_MemberCall:
1384 case AK_DynamicCast:
Richard Smitha9330302019-05-17 19:19:28 +00001385 case AK_TypeId:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001386 return false;
1387 case AK_Assign:
1388 case AK_Increment:
1389 case AK_Decrement:
1390 return true;
1391 }
1392 llvm_unreachable("unknown access kind");
1393}
1394
1395/// Is this an access per the C++ definition?
1396static bool isFormalAccess(AccessKinds AK) {
1397 return AK == AK_Read || isModification(AK);
Richard Smithdebad642019-05-12 09:39:08 +00001398}
1399
Richard Smithf6f003a2011-12-16 19:06:07 +00001400namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001401 struct ComplexValue {
1402 private:
1403 bool IsInt;
1404
1405 public:
1406 APSInt IntReal, IntImag;
1407 APFloat FloatReal, FloatImag;
1408
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001409 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001410
1411 void makeComplexFloat() { IsInt = false; }
1412 bool isComplexFloat() const { return !IsInt; }
1413 APFloat &getComplexFloatReal() { return FloatReal; }
1414 APFloat &getComplexFloatImag() { return FloatImag; }
1415
1416 void makeComplexInt() { IsInt = true; }
1417 bool isComplexInt() const { return IsInt; }
1418 APSInt &getComplexIntReal() { return IntReal; }
1419 APSInt &getComplexIntImag() { return IntImag; }
1420
Richard Smith2e312c82012-03-03 22:46:17 +00001421 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001422 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001423 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001424 else
Richard Smith2e312c82012-03-03 22:46:17 +00001425 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001426 }
Richard Smith2e312c82012-03-03 22:46:17 +00001427 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001428 assert(v.isComplexFloat() || v.isComplexInt());
1429 if (v.isComplexFloat()) {
1430 makeComplexFloat();
1431 FloatReal = v.getComplexFloatReal();
1432 FloatImag = v.getComplexFloatImag();
1433 } else {
1434 makeComplexInt();
1435 IntReal = v.getComplexIntReal();
1436 IntImag = v.getComplexIntImag();
1437 }
1438 }
John McCall93d91dc2010-05-07 17:22:02 +00001439 };
John McCall45d55e42010-05-07 21:00:08 +00001440
1441 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001442 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001443 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001444 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001445 bool IsNullPtr : 1;
1446 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001447
Richard Smithce40ad62011-11-12 22:28:03 +00001448 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001449 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001450 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001451 SubobjectDesignator &getLValueDesignator() { return Designator; }
1452 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001453 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001454
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001455 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1456 unsigned getLValueVersion() const { return Base.getVersion(); }
1457
Richard Smith2e312c82012-03-03 22:46:17 +00001458 void moveInto(APValue &V) const {
1459 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001460 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001461 else {
1462 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001463 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001464 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001465 }
John McCall45d55e42010-05-07 21:00:08 +00001466 }
Richard Smith2e312c82012-03-03 22:46:17 +00001467 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001468 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001469 Base = V.getLValueBase();
1470 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001471 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001472 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001473 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001474 }
1475
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001476 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001477#ifndef NDEBUG
1478 // We only allow a few types of invalid bases. Enforce that here.
1479 if (BInvalid) {
1480 const auto *E = B.get<const Expr *>();
1481 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1482 "Unexpected type of invalid base");
1483 }
1484#endif
1485
Richard Smithce40ad62011-11-12 22:28:03 +00001486 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001487 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001488 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001489 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001490 IsNullPtr = false;
1491 }
1492
1493 void setNull(QualType PointerTy, uint64_t TargetVal) {
1494 Base = (Expr *)nullptr;
1495 Offset = CharUnits::fromQuantity(TargetVal);
1496 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001497 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1498 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001499 }
1500
George Burgess IV3a03fab2015-09-04 21:28:13 +00001501 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001502 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001503 }
1504
Hubert Tong147b7432018-12-12 16:53:43 +00001505 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001506 // Check that this LValue is not based on a null pointer. If it is, produce
1507 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001508 template <typename GenDiagType>
1509 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001510 if (Designator.Invalid)
1511 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001512 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001513 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001514 Designator.setInvalid();
1515 return false;
1516 }
1517 return true;
1518 }
1519
Hubert Tong147b7432018-12-12 16:53:43 +00001520 public:
1521 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1522 CheckSubobjectKind CSK) {
1523 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1524 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1525 });
1526 }
1527
1528 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1529 AccessKinds AK) {
1530 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1531 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1532 });
1533 }
1534
Richard Smitha8105bc2012-01-06 16:39:00 +00001535 // Check this LValue refers to an object. If not, set the designator to be
1536 // invalid and emit a diagnostic.
1537 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001538 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001539 Designator.checkSubobject(Info, E, CSK);
1540 }
1541
1542 void addDecl(EvalInfo &Info, const Expr *E,
1543 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001544 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1545 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001546 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001547 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1548 if (!Designator.Entries.empty()) {
1549 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1550 Designator.setInvalid();
1551 return;
1552 }
Richard Smithefdb5032017-11-15 03:03:56 +00001553 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1554 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1555 Designator.FirstEntryIsAnUnsizedArray = true;
1556 Designator.addUnsizedArrayUnchecked(ElemTy);
1557 }
George Burgess IVe3763372016-12-22 02:50:20 +00001558 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001559 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001560 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1561 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001562 }
Richard Smith66c96992012-02-18 22:04:06 +00001563 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001564 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1565 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001566 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001567 void clearIsNullPointer() {
1568 IsNullPtr = false;
1569 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001570 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1571 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001572 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1573 // but we're not required to diagnose it and it's valid in C++.)
1574 if (!Index)
1575 return;
1576
1577 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1578 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1579 // offsets.
1580 uint64_t Offset64 = Offset.getQuantity();
1581 uint64_t ElemSize64 = ElementSize.getQuantity();
1582 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1583 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1584
1585 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001586 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001587 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001588 }
1589 void adjustOffset(CharUnits N) {
1590 Offset += N;
1591 if (N.getQuantity())
1592 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001593 }
John McCall45d55e42010-05-07 21:00:08 +00001594 };
Richard Smith027bf112011-11-17 22:56:20 +00001595
1596 struct MemberPtr {
1597 MemberPtr() {}
1598 explicit MemberPtr(const ValueDecl *Decl) :
1599 DeclAndIsDerivedMember(Decl, false), Path() {}
1600
1601 /// The member or (direct or indirect) field referred to by this member
1602 /// pointer, or 0 if this is a null member pointer.
1603 const ValueDecl *getDecl() const {
1604 return DeclAndIsDerivedMember.getPointer();
1605 }
1606 /// Is this actually a member of some type derived from the relevant class?
1607 bool isDerivedMember() const {
1608 return DeclAndIsDerivedMember.getInt();
1609 }
1610 /// Get the class which the declaration actually lives in.
1611 const CXXRecordDecl *getContainingRecord() const {
1612 return cast<CXXRecordDecl>(
1613 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1614 }
1615
Richard Smith2e312c82012-03-03 22:46:17 +00001616 void moveInto(APValue &V) const {
1617 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001618 }
Richard Smith2e312c82012-03-03 22:46:17 +00001619 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001620 assert(V.isMemberPointer());
1621 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1622 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1623 Path.clear();
1624 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1625 Path.insert(Path.end(), P.begin(), P.end());
1626 }
1627
1628 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1629 /// whether the member is a member of some class derived from the class type
1630 /// of the member pointer.
1631 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1632 /// Path - The path of base/derived classes from the member declaration's
1633 /// class (exclusive) to the class type of the member pointer (inclusive).
1634 SmallVector<const CXXRecordDecl*, 4> Path;
1635
1636 /// Perform a cast towards the class of the Decl (either up or down the
1637 /// hierarchy).
1638 bool castBack(const CXXRecordDecl *Class) {
1639 assert(!Path.empty());
1640 const CXXRecordDecl *Expected;
1641 if (Path.size() >= 2)
1642 Expected = Path[Path.size() - 2];
1643 else
1644 Expected = getContainingRecord();
1645 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1646 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1647 // if B does not contain the original member and is not a base or
1648 // derived class of the class containing the original member, the result
1649 // of the cast is undefined.
1650 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1651 // (D::*). We consider that to be a language defect.
1652 return false;
1653 }
1654 Path.pop_back();
1655 return true;
1656 }
1657 /// Perform a base-to-derived member pointer cast.
1658 bool castToDerived(const CXXRecordDecl *Derived) {
1659 if (!getDecl())
1660 return true;
1661 if (!isDerivedMember()) {
1662 Path.push_back(Derived);
1663 return true;
1664 }
1665 if (!castBack(Derived))
1666 return false;
1667 if (Path.empty())
1668 DeclAndIsDerivedMember.setInt(false);
1669 return true;
1670 }
1671 /// Perform a derived-to-base member pointer cast.
1672 bool castToBase(const CXXRecordDecl *Base) {
1673 if (!getDecl())
1674 return true;
1675 if (Path.empty())
1676 DeclAndIsDerivedMember.setInt(true);
1677 if (isDerivedMember()) {
1678 Path.push_back(Base);
1679 return true;
1680 }
1681 return castBack(Base);
1682 }
1683 };
Richard Smith357362d2011-12-13 06:39:58 +00001684
Richard Smith7bb00672012-02-01 01:42:44 +00001685 /// Compare two member pointers, which are assumed to be of the same type.
1686 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1687 if (!LHS.getDecl() || !RHS.getDecl())
1688 return !LHS.getDecl() && !RHS.getDecl();
1689 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1690 return false;
1691 return LHS.Path == RHS.Path;
1692 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001693}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001694
Richard Smith2e312c82012-03-03 22:46:17 +00001695static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001696static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1697 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001698 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001699static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1700 bool InvalidBaseOK = false);
1701static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1702 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001703static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1704 EvalInfo &Info);
1705static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001706static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001707static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001708 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001709static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001710static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001711static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1712 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001713static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001714
Leonard Chand3f3e162019-01-18 21:04:25 +00001715/// Evaluate an integer or fixed point expression into an APResult.
1716static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1717 EvalInfo &Info);
1718
1719/// Evaluate only a fixed point expression into an APResult.
1720static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1721 EvalInfo &Info);
1722
Chris Lattner05706e882008-07-11 18:11:29 +00001723//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001724// Misc utilities
1725//===----------------------------------------------------------------------===//
1726
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001727/// A helper function to create a temporary and set an LValue.
1728template <class KeyTy>
1729static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1730 LValue &LV, CallStackFrame &Frame) {
1731 LV.set({Key, Frame.Info.CurrentCall->Index,
1732 Frame.Info.CurrentCall->getTempVersion()});
1733 return Frame.createTemporary(Key, IsLifetimeExtended);
1734}
1735
Richard Smithd6cc1982017-01-31 02:23:02 +00001736/// Negate an APSInt in place, converting it to a signed form if necessary, and
1737/// preserving its value (by extending by up to one bit as needed).
1738static void negateAsSigned(APSInt &Int) {
1739 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1740 Int = Int.extend(Int.getBitWidth() + 1);
1741 Int.setIsSigned(true);
1742 }
1743 Int = -Int;
1744}
1745
Richard Smith84401042013-06-03 05:03:02 +00001746/// Produce a string describing the given constexpr call.
1747static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1748 unsigned ArgIndex = 0;
1749 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1750 !isa<CXXConstructorDecl>(Frame->Callee) &&
1751 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1752
1753 if (!IsMemberCall)
1754 Out << *Frame->Callee << '(';
1755
1756 if (Frame->This && IsMemberCall) {
1757 APValue Val;
1758 Frame->This->moveInto(Val);
1759 Val.printPretty(Out, Frame->Info.Ctx,
1760 Frame->This->Designator.MostDerivedType);
1761 // FIXME: Add parens around Val if needed.
1762 Out << "->" << *Frame->Callee << '(';
1763 IsMemberCall = false;
1764 }
1765
1766 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1767 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1768 if (ArgIndex > (unsigned)IsMemberCall)
1769 Out << ", ";
1770
1771 const ParmVarDecl *Param = *I;
1772 const APValue &Arg = Frame->Arguments[ArgIndex];
1773 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1774
1775 if (ArgIndex == 0 && IsMemberCall)
1776 Out << "->" << *Frame->Callee << '(';
1777 }
1778
1779 Out << ')';
1780}
1781
Richard Smithd9f663b2013-04-22 15:31:51 +00001782/// Evaluate an expression to see if it had side-effects, and discard its
1783/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001784/// \return \c true if the caller should keep evaluating.
1785static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001786 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001787 if (!Evaluate(Scratch, Info, E))
1788 // We don't need the value, but we might have skipped a side effect here.
1789 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001790 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001791}
1792
Richard Smithd62306a2011-11-10 06:34:14 +00001793/// Should this call expression be treated as a string literal?
1794static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001795 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001796 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1797 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1798}
1799
Richard Smithce40ad62011-11-12 22:28:03 +00001800static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001801 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1802 // constant expression of pointer type that evaluates to...
1803
1804 // ... a null pointer value, or a prvalue core constant expression of type
1805 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001806 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001807
Richard Smithce40ad62011-11-12 22:28:03 +00001808 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1809 // ... the address of an object with static storage duration,
1810 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1811 return VD->hasGlobalStorage();
1812 // ... the address of a function,
1813 return isa<FunctionDecl>(D);
1814 }
1815
Richard Smithee0ce3022019-05-17 07:06:46 +00001816 if (B.is<TypeInfoLValue>())
1817 return true;
1818
Richard Smithce40ad62011-11-12 22:28:03 +00001819 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001820 switch (E->getStmtClass()) {
1821 default:
1822 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001823 case Expr::CompoundLiteralExprClass: {
1824 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1825 return CLE->isFileScope() && CLE->isLValue();
1826 }
Richard Smithe6c01442013-06-05 00:46:14 +00001827 case Expr::MaterializeTemporaryExprClass:
1828 // A materialized temporary might have been lifetime-extended to static
1829 // storage duration.
1830 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001831 // A string literal has static storage duration.
1832 case Expr::StringLiteralClass:
1833 case Expr::PredefinedExprClass:
1834 case Expr::ObjCStringLiteralClass:
1835 case Expr::ObjCEncodeExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001836 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001837 return true;
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001838 case Expr::ObjCBoxedExprClass:
1839 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
Richard Smithd62306a2011-11-10 06:34:14 +00001840 case Expr::CallExprClass:
1841 return IsStringLiteralCall(cast<CallExpr>(E));
1842 // For GCC compatibility, &&label has static storage duration.
1843 case Expr::AddrLabelExprClass:
1844 return true;
1845 // A Block literal expression may be used as the initialization value for
1846 // Block variables at global or local static scope.
1847 case Expr::BlockExprClass:
1848 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001849 case Expr::ImplicitValueInitExprClass:
1850 // FIXME:
1851 // We can never form an lvalue with an implicit value initialization as its
1852 // base through expression evaluation, so these only appear in one case: the
1853 // implicit variable declaration we invent when checking whether a constexpr
1854 // constructor can produce a constant expression. We must assume that such
1855 // an expression might be a global lvalue.
1856 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001857 }
John McCall95007602010-05-10 23:27:23 +00001858}
1859
Richard Smith06f71b52018-08-04 00:57:17 +00001860static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1861 return LVal.Base.dyn_cast<const ValueDecl*>();
1862}
1863
1864static bool IsLiteralLValue(const LValue &Value) {
1865 if (Value.getLValueCallIndex())
1866 return false;
1867 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1868 return E && !isa<MaterializeTemporaryExpr>(E);
1869}
1870
1871static bool IsWeakLValue(const LValue &Value) {
1872 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1873 return Decl && Decl->isWeak();
1874}
1875
1876static bool isZeroSized(const LValue &Value) {
1877 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1878 if (Decl && isa<VarDecl>(Decl)) {
1879 QualType Ty = Decl->getType();
1880 if (Ty->isArrayType())
1881 return Ty->isIncompleteType() ||
1882 Decl->getASTContext().getTypeSize(Ty) == 0;
1883 }
1884 return false;
1885}
1886
1887static bool HasSameBase(const LValue &A, const LValue &B) {
1888 if (!A.getLValueBase())
1889 return !B.getLValueBase();
1890 if (!B.getLValueBase())
1891 return false;
1892
1893 if (A.getLValueBase().getOpaqueValue() !=
1894 B.getLValueBase().getOpaqueValue()) {
1895 const Decl *ADecl = GetLValueBaseDecl(A);
1896 if (!ADecl)
1897 return false;
1898 const Decl *BDecl = GetLValueBaseDecl(B);
1899 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1900 return false;
1901 }
1902
1903 return IsGlobalLValue(A.getLValueBase()) ||
1904 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1905 A.getLValueVersion() == B.getLValueVersion());
1906}
1907
Richard Smithb228a862012-02-15 02:18:13 +00001908static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1909 assert(Base && "no location for a null lvalue");
1910 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1911 if (VD)
1912 Info.Note(VD->getLocation(), diag::note_declared_at);
Richard Smithee0ce3022019-05-17 07:06:46 +00001913 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1914 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1915 // We have no information to show for a typeid(T) object.
Richard Smithb228a862012-02-15 02:18:13 +00001916}
1917
Richard Smith80815602011-11-07 05:07:52 +00001918/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001919/// value for an address or reference constant expression. Return true if we
1920/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001921static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001922 QualType Type, const LValue &LVal,
1923 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001924 bool IsReferenceType = Type->isReferenceType();
1925
Richard Smith357362d2011-12-13 06:39:58 +00001926 APValue::LValueBase Base = LVal.getLValueBase();
1927 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1928
Richard Smith0dea49e2012-02-18 04:58:18 +00001929 // Check that the object is a global. Note that the fake 'this' object we
1930 // manufacture when checking potential constant expressions is conservatively
1931 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001932 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001933 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001934 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001935 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001936 << IsReferenceType << !Designator.Entries.empty()
1937 << !!VD << VD;
1938 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001939 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001940 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001941 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001942 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001943 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001944 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001945 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001946 LVal.getLValueCallIndex() == 0) &&
1947 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001948
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001949 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1950 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001951 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001952 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001953 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001954
Hans Wennborg82dd8772014-06-25 22:19:48 +00001955 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001956 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001957 return false;
1958 }
1959 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1960 // __declspec(dllimport) must be handled very carefully:
1961 // We must never initialize an expression with the thunk in C++.
1962 // Doing otherwise would allow the same id-expression to yield
1963 // different addresses for the same function in different translation
1964 // units. However, this means that we must dynamically initialize the
1965 // expression with the contents of the import address table at runtime.
1966 //
1967 // The C language has no notion of ODR; furthermore, it has no notion of
1968 // dynamic initialization. This means that we are permitted to
1969 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001970 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1971 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001972 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001973 }
1974 }
1975
Richard Smitha8105bc2012-01-06 16:39:00 +00001976 // Allow address constant expressions to be past-the-end pointers. This is
1977 // an extension: the standard requires them to point to an object.
1978 if (!IsReferenceType)
1979 return true;
1980
1981 // A reference constant expression must refer to an object.
1982 if (!Base) {
1983 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001984 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001985 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001986 }
1987
Richard Smith357362d2011-12-13 06:39:58 +00001988 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001989 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001990 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001991 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001992 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001993 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001994 }
1995
Richard Smith80815602011-11-07 05:07:52 +00001996 return true;
1997}
1998
Reid Klecknercd016d82017-07-07 22:04:29 +00001999/// Member pointers are constant expressions unless they point to a
2000/// non-virtual dllimport member function.
2001static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2002 SourceLocation Loc,
2003 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00002004 const APValue &Value,
2005 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00002006 const ValueDecl *Member = Value.getMemberPointerDecl();
2007 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2008 if (!FD)
2009 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002010 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2011 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00002012}
2013
Richard Smithfddd3842011-12-30 21:15:51 +00002014/// Check that this core constant expression is of literal type, and if not,
2015/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00002016static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00002017 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002018 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00002019 return true;
2020
Richard Smith7525ff62013-05-09 07:14:00 +00002021 // C++1y: A constant initializer for an object o [...] may also invoke
2022 // constexpr constructors for o and its subobjects even if those objects
2023 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00002024 //
2025 // C++11 missed this detail for aggregates, so classes like this:
2026 // struct foo_t { union { int i; volatile int j; } u; };
2027 // are not (obviously) initializable like so:
2028 // __attribute__((__require_constant_initialization__))
2029 // static const foo_t x = {{0}};
2030 // because "i" is a subobject with non-literal initialization (due to the
2031 // volatile member of the union). See:
2032 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2033 // Therefore, we use the C++1y behavior.
2034 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00002035 return true;
2036
Richard Smithfddd3842011-12-30 21:15:51 +00002037 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002038 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002039 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00002040 << E->getType();
2041 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002042 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00002043 return false;
2044}
2045
Richard Smith0b0a0b62011-10-29 20:57:55 +00002046/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00002047/// constant expression. If not, report an appropriate diagnostic. Does not
2048/// check that the expression is of literal type.
Reid Kleckner1a840d22018-05-10 18:57:35 +00002049static bool
2050CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2051 const APValue &Value,
Richard Smith31c69a32019-05-21 23:15:20 +00002052 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen,
2053 SourceLocation SubobjectLoc = SourceLocation()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002054 if (!Value.hasValue()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002055 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00002056 << true << Type;
Richard Smith31c69a32019-05-21 23:15:20 +00002057 if (SubobjectLoc.isValid())
2058 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
Richard Smith1a90f592013-06-18 17:51:51 +00002059 return false;
2060 }
2061
Richard Smith77be48a2014-07-31 06:31:19 +00002062 // We allow _Atomic(T) to be initialized from anything that T can be
2063 // initialized from.
2064 if (const AtomicType *AT = Type->getAs<AtomicType>())
2065 Type = AT->getValueType();
2066
Richard Smithb228a862012-02-15 02:18:13 +00002067 // Core issue 1454: For a literal constant expression of array or class type,
2068 // each subobject of its value shall have been initialized by a constant
2069 // expression.
2070 if (Value.isArray()) {
2071 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2072 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2073 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
Richard Smith31c69a32019-05-21 23:15:20 +00002074 Value.getArrayInitializedElt(I), Usage,
2075 SubobjectLoc))
Richard Smithb228a862012-02-15 02:18:13 +00002076 return false;
2077 }
2078 if (!Value.hasArrayFiller())
2079 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002080 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
Richard Smith31c69a32019-05-21 23:15:20 +00002081 Usage, SubobjectLoc);
Richard Smith80815602011-11-07 05:07:52 +00002082 }
Richard Smithb228a862012-02-15 02:18:13 +00002083 if (Value.isUnion() && Value.getUnionField()) {
2084 return CheckConstantExpression(Info, DiagLoc,
2085 Value.getUnionField()->getType(),
Richard Smith31c69a32019-05-21 23:15:20 +00002086 Value.getUnionValue(), Usage,
2087 Value.getUnionField()->getLocation());
Richard Smithb228a862012-02-15 02:18:13 +00002088 }
2089 if (Value.isStruct()) {
2090 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2091 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2092 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002093 for (const CXXBaseSpecifier &BS : CD->bases()) {
2094 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
Richard Smith31c69a32019-05-21 23:15:20 +00002095 Value.getStructBase(BaseIndex), Usage,
2096 BS.getBeginLoc()))
Richard Smithb228a862012-02-15 02:18:13 +00002097 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002098 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00002099 }
2100 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002101 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00002102 if (I->isUnnamedBitfield())
2103 continue;
2104
David Blaikie2d7c57e2012-04-30 02:36:29 +00002105 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00002106 Value.getStructField(I->getFieldIndex()),
Richard Smith31c69a32019-05-21 23:15:20 +00002107 Usage, I->getLocation()))
Richard Smithb228a862012-02-15 02:18:13 +00002108 return false;
2109 }
2110 }
2111
2112 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00002113 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00002114 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00002115 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00002116 }
2117
Reid Klecknercd016d82017-07-07 22:04:29 +00002118 if (Value.isMemberPointer())
Reid Kleckner1a840d22018-05-10 18:57:35 +00002119 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00002120
Richard Smithb228a862012-02-15 02:18:13 +00002121 // Everything else is fine.
2122 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002123}
2124
Richard Smith2e312c82012-03-03 22:46:17 +00002125static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00002126 // A null base expression indicates a null pointer. These are always
2127 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00002128 if (!Value.getLValueBase()) {
2129 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002130 return true;
2131 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002132
Richard Smith027bf112011-11-17 22:56:20 +00002133 // We have a non-null base. These are generally known to be true, but if it's
2134 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002135 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002136 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002137 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002138}
2139
Richard Smith2e312c82012-03-03 22:46:17 +00002140static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002141 switch (Val.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002142 case APValue::None:
2143 case APValue::Indeterminate:
Richard Smith11562c52011-10-28 17:51:58 +00002144 return false;
2145 case APValue::Int:
2146 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002147 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00002148 case APValue::FixedPoint:
2149 Result = Val.getFixedPoint().getBoolValue();
2150 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002151 case APValue::Float:
2152 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002153 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002154 case APValue::ComplexInt:
2155 Result = Val.getComplexIntReal().getBoolValue() ||
2156 Val.getComplexIntImag().getBoolValue();
2157 return true;
2158 case APValue::ComplexFloat:
2159 Result = !Val.getComplexFloatReal().isZero() ||
2160 !Val.getComplexFloatImag().isZero();
2161 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002162 case APValue::LValue:
2163 return EvalPointerValueAsBool(Val, Result);
2164 case APValue::MemberPointer:
2165 Result = Val.getMemberPointerDecl();
2166 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002167 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002168 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002169 case APValue::Struct:
2170 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002171 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002172 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002173 }
2174
Richard Smith11562c52011-10-28 17:51:58 +00002175 llvm_unreachable("unknown APValue kind");
2176}
2177
2178static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2179 EvalInfo &Info) {
2180 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002181 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002182 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002183 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002184 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002185}
2186
Richard Smith357362d2011-12-13 06:39:58 +00002187template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002188static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002189 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002190 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002191 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002192 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002193}
2194
2195static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2196 QualType SrcType, const APFloat &Value,
2197 QualType DestType, APSInt &Result) {
2198 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002199 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002200 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002201
Richard Smith357362d2011-12-13 06:39:58 +00002202 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002203 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002204 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2205 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002206 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002207 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002208}
2209
Richard Smith357362d2011-12-13 06:39:58 +00002210static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2211 QualType SrcType, QualType DestType,
2212 APFloat &Result) {
2213 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002214 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002215 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2216 APFloat::rmNearestTiesToEven, &ignored)
2217 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002218 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002219 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002220}
2221
Richard Smith911e1422012-01-30 22:27:01 +00002222static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2223 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002224 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002225 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002226 // Figure out if this is a truncate, extend or noop cast.
2227 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002228 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002229 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002230 if (DestType->isBooleanType())
2231 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002232 return Result;
2233}
2234
Richard Smith357362d2011-12-13 06:39:58 +00002235static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2236 QualType SrcType, const APSInt &Value,
2237 QualType DestType, APFloat &Result) {
2238 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2239 if (Result.convertFromAPInt(Value, Value.isSigned(),
2240 APFloat::rmNearestTiesToEven)
2241 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002242 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002243 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002244}
2245
Richard Smith49ca8aa2013-08-06 07:09:20 +00002246static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2247 APValue &Value, const FieldDecl *FD) {
2248 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2249
2250 if (!Value.isInt()) {
2251 // Trying to store a pointer-cast-to-integer into a bitfield.
2252 // FIXME: In this case, we should provide the diagnostic for casting
2253 // a pointer to an integer.
2254 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002255 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002256 return false;
2257 }
2258
2259 APSInt &Int = Value.getInt();
2260 unsigned OldBitWidth = Int.getBitWidth();
2261 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2262 if (NewBitWidth < OldBitWidth)
2263 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2264 return true;
2265}
2266
Eli Friedman803acb32011-12-22 03:51:45 +00002267static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2268 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002269 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002270 if (!Evaluate(SVal, Info, E))
2271 return false;
2272 if (SVal.isInt()) {
2273 Res = SVal.getInt();
2274 return true;
2275 }
2276 if (SVal.isFloat()) {
2277 Res = SVal.getFloat().bitcastToAPInt();
2278 return true;
2279 }
2280 if (SVal.isVector()) {
2281 QualType VecTy = E->getType();
2282 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2283 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2284 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2285 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2286 Res = llvm::APInt::getNullValue(VecSize);
2287 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2288 APValue &Elt = SVal.getVectorElt(i);
2289 llvm::APInt EltAsInt;
2290 if (Elt.isInt()) {
2291 EltAsInt = Elt.getInt();
2292 } else if (Elt.isFloat()) {
2293 EltAsInt = Elt.getFloat().bitcastToAPInt();
2294 } else {
2295 // Don't try to handle vectors of anything other than int or float
2296 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002297 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002298 return false;
2299 }
2300 unsigned BaseEltSize = EltAsInt.getBitWidth();
2301 if (BigEndian)
2302 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2303 else
2304 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2305 }
2306 return true;
2307 }
2308 // Give up if the input isn't an int, float, or vector. For example, we
2309 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002310 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002311 return false;
2312}
2313
Richard Smith43e77732013-05-07 04:50:00 +00002314/// Perform the given integer operation, which is known to need at most BitWidth
2315/// bits, and check for overflow in the original type (if that type was not an
2316/// unsigned type).
2317template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002318static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2319 const APSInt &LHS, const APSInt &RHS,
2320 unsigned BitWidth, Operation Op,
2321 APSInt &Result) {
2322 if (LHS.isUnsigned()) {
2323 Result = Op(LHS, RHS);
2324 return true;
2325 }
Richard Smith43e77732013-05-07 04:50:00 +00002326
2327 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002328 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002329 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002330 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002331 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002332 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002333 << Result.toString(10) << E->getType();
2334 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002335 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002336 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002337 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002338}
2339
2340/// Perform the given binary integer operation.
2341static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2342 BinaryOperatorKind Opcode, APSInt RHS,
2343 APSInt &Result) {
2344 switch (Opcode) {
2345 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002346 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002347 return false;
2348 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002349 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2350 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002351 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002352 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2353 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002354 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002355 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2356 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002357 case BO_And: Result = LHS & RHS; return true;
2358 case BO_Xor: Result = LHS ^ RHS; return true;
2359 case BO_Or: Result = LHS | RHS; return true;
2360 case BO_Div:
2361 case BO_Rem:
2362 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002363 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002364 return false;
2365 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002366 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2367 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2368 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002369 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2370 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002371 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2372 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002373 return true;
2374 case BO_Shl: {
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
2382 // a shift is not a constant expression.
2383 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2384 RHS = -RHS;
2385 goto shift_right;
2386 }
2387 shift_left:
2388 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2389 // the 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();
Richard Smith7939ba02019-06-25 01:45:26 +00002394 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
Richard Smith43e77732013-05-07 04:50:00 +00002395 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2396 // operand, and must not overflow the corresponding unsigned type.
Richard Smith7939ba02019-06-25 01:45:26 +00002397 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2398 // E1 x 2^E2 module 2^N.
Richard Smith43e77732013-05-07 04:50:00 +00002399 if (LHS.isNegative())
2400 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2401 else if (LHS.countLeadingZeros() < SA)
2402 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2403 }
2404 Result = LHS << SA;
2405 return true;
2406 }
2407 case BO_Shr: {
2408 if (Info.getLangOpts().OpenCL)
2409 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2410 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2411 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2412 RHS.isUnsigned());
2413 else if (RHS.isSigned() && RHS.isNegative()) {
2414 // During constant-folding, a negative shift is an opposite shift. Such a
2415 // shift is not a constant expression.
2416 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2417 RHS = -RHS;
2418 goto shift_left;
2419 }
2420 shift_right:
2421 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2422 // shifted type.
2423 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2424 if (SA != RHS)
2425 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2426 << RHS << E->getType() << LHS.getBitWidth();
2427 Result = LHS >> SA;
2428 return true;
2429 }
2430
2431 case BO_LT: Result = LHS < RHS; return true;
2432 case BO_GT: Result = LHS > RHS; return true;
2433 case BO_LE: Result = LHS <= RHS; return true;
2434 case BO_GE: Result = LHS >= RHS; return true;
2435 case BO_EQ: Result = LHS == RHS; return true;
2436 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002437 case BO_Cmp:
2438 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002439 }
2440}
2441
Richard Smith861b5b52013-05-07 23:34:45 +00002442/// Perform the given binary floating-point operation, in-place, on LHS.
2443static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2444 APFloat &LHS, BinaryOperatorKind Opcode,
2445 const APFloat &RHS) {
2446 switch (Opcode) {
2447 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002448 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002449 return false;
2450 case BO_Mul:
2451 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2452 break;
2453 case BO_Add:
2454 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2455 break;
2456 case BO_Sub:
2457 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2458 break;
2459 case BO_Div:
2460 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2461 break;
2462 }
2463
Richard Smith0c6124b2015-12-03 01:36:22 +00002464 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002465 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002466 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002467 }
Richard Smith861b5b52013-05-07 23:34:45 +00002468 return true;
2469}
2470
Richard Smitha8105bc2012-01-06 16:39:00 +00002471/// Cast an lvalue referring to a base subobject to a derived class, by
2472/// truncating the lvalue's path to the given length.
2473static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2474 const RecordDecl *TruncatedType,
2475 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002476 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002477
2478 // Check we actually point to a derived class object.
2479 if (TruncatedElements == D.Entries.size())
2480 return true;
2481 assert(TruncatedElements >= D.MostDerivedPathLength &&
2482 "not casting to a derived class");
2483 if (!Result.checkSubobject(Info, E, CSK_Derived))
2484 return false;
2485
2486 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002487 const RecordDecl *RD = TruncatedType;
2488 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002489 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002490 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2491 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002492 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002493 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002494 else
Richard Smithd62306a2011-11-10 06:34:14 +00002495 Result.Offset -= Layout.getBaseClassOffset(Base);
2496 RD = Base;
2497 }
Richard Smith027bf112011-11-17 22:56:20 +00002498 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002499 return true;
2500}
2501
John McCalld7bca762012-05-01 00:38:49 +00002502static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002503 const CXXRecordDecl *Derived,
2504 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002505 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002506 if (!RL) {
2507 if (Derived->isInvalidDecl()) return false;
2508 RL = &Info.Ctx.getASTRecordLayout(Derived);
2509 }
2510
Richard Smithd62306a2011-11-10 06:34:14 +00002511 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002512 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002513 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002514}
2515
Richard Smitha8105bc2012-01-06 16:39:00 +00002516static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002517 const CXXRecordDecl *DerivedDecl,
2518 const CXXBaseSpecifier *Base) {
2519 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2520
John McCalld7bca762012-05-01 00:38:49 +00002521 if (!Base->isVirtual())
2522 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002523
Richard Smitha8105bc2012-01-06 16:39:00 +00002524 SubobjectDesignator &D = Obj.Designator;
2525 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002526 return false;
2527
Richard Smitha8105bc2012-01-06 16:39:00 +00002528 // Extract most-derived object and corresponding type.
2529 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2530 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2531 return false;
2532
2533 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002534 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002535 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2536 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002537 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002538 return true;
2539}
2540
Richard Smith84401042013-06-03 05:03:02 +00002541static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2542 QualType Type, LValue &Result) {
2543 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2544 PathE = E->path_end();
2545 PathI != PathE; ++PathI) {
2546 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2547 *PathI))
2548 return false;
2549 Type = (*PathI)->getType();
2550 }
2551 return true;
2552}
2553
Richard Smith921f1322019-05-13 23:35:21 +00002554/// Cast an lvalue referring to a derived class to a known base subobject.
2555static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2556 const CXXRecordDecl *DerivedRD,
2557 const CXXRecordDecl *BaseRD) {
2558 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2559 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2560 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2561 llvm_unreachable("Class must be derived from the passed in base class!");
2562
2563 for (CXXBasePathElement &Elem : Paths.front())
2564 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2565 return false;
2566 return true;
2567}
2568
Richard Smithd62306a2011-11-10 06:34:14 +00002569/// Update LVal to refer to the given field, which must be a member of the type
2570/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002571static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002572 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002573 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002574 if (!RL) {
2575 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002576 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002577 }
Richard Smithd62306a2011-11-10 06:34:14 +00002578
2579 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002580 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002581 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002582 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002583}
2584
Richard Smith1b78b3d2012-01-25 22:15:11 +00002585/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002586static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002587 LValue &LVal,
2588 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002589 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002590 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002591 return false;
2592 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002593}
2594
Richard Smithd62306a2011-11-10 06:34:14 +00002595/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002596static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2597 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002598 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2599 // extension.
2600 if (Type->isVoidType() || Type->isFunctionType()) {
2601 Size = CharUnits::One();
2602 return true;
2603 }
2604
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002605 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002606 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002607 return false;
2608 }
2609
Richard Smithd62306a2011-11-10 06:34:14 +00002610 if (!Type->isConstantSizeType()) {
2611 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002612 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002613 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002614 return false;
2615 }
2616
2617 Size = Info.Ctx.getTypeSizeInChars(Type);
2618 return true;
2619}
2620
2621/// Update a pointer value to model pointer arithmetic.
2622/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002623/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002624/// \param LVal - The pointer value to be updated.
2625/// \param EltTy - The pointee type represented by LVal.
2626/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002627static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2628 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002629 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002630 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002631 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002632 return false;
2633
Yaxun Liu402804b2016-12-15 08:09:08 +00002634 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002635 return true;
2636}
2637
Richard Smithd6cc1982017-01-31 02:23:02 +00002638static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2639 LValue &LVal, QualType EltTy,
2640 int64_t Adjustment) {
2641 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2642 APSInt::get(Adjustment));
2643}
2644
Richard Smith66c96992012-02-18 22:04:06 +00002645/// Update an lvalue to refer to a component of a complex number.
2646/// \param Info - Information about the ongoing evaluation.
2647/// \param LVal - The lvalue to be updated.
2648/// \param EltTy - The complex number's component type.
2649/// \param Imag - False for the real component, true for the imaginary.
2650static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2651 LValue &LVal, QualType EltTy,
2652 bool Imag) {
2653 if (Imag) {
2654 CharUnits SizeOfComponent;
2655 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2656 return false;
2657 LVal.Offset += SizeOfComponent;
2658 }
2659 LVal.addComplex(Info, E, EltTy, Imag);
2660 return true;
2661}
2662
Richard Smith27908702011-10-24 17:54:18 +00002663/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002664///
2665/// \param Info Information about the ongoing evaluation.
2666/// \param E An expression to be used when printing diagnostics.
2667/// \param VD The variable whose initializer should be obtained.
2668/// \param Frame The frame in which the variable was created. Must be null
2669/// if this variable is not local to the evaluation.
2670/// \param Result Filled in with a pointer to the value of the variable.
2671static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2672 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002673 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002674
Richard Smith254a73d2011-10-28 22:34:42 +00002675 // If this is a parameter to an active constexpr function call, perform
2676 // argument substitution.
2677 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002678 // Assume arguments of a potential constant expression are unknown
2679 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002680 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002681 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002682 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002683 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002684 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002685 }
Richard Smith3229b742013-05-05 21:17:10 +00002686 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002687 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002688 }
Richard Smith27908702011-10-24 17:54:18 +00002689
Richard Smithd9f663b2013-04-22 15:31:51 +00002690 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002691 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002692 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2693 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002694 if (!Result) {
2695 // Assume variables referenced within a lambda's call operator that were
2696 // not declared within the call operator are captures and during checking
2697 // of a potential constant expression, assume they are unknown constant
2698 // expressions.
2699 assert(isLambdaCallOperator(Frame->Callee) &&
2700 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2701 "missing value for local variable");
2702 if (Info.checkingPotentialConstantExpression())
2703 return false;
2704 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002705 Info.FFDiag(E->getBeginLoc(),
2706 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002707 << "captures not currently allowed";
2708 return false;
2709 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002710 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002711 }
2712
Richard Smithd0b4dd62011-12-19 06:19:21 +00002713 // Dig out the initializer, and use the declaration which it's attached to.
2714 const Expr *Init = VD->getAnyInitializer(VD);
2715 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002716 // If we're checking a potential constant expression, the variable could be
2717 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002718 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002719 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002720 return false;
2721 }
2722
Richard Smithd62306a2011-11-10 06:34:14 +00002723 // If we're currently evaluating the initializer of this declaration, use that
2724 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002725 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002726 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002727 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002728 }
2729
Richard Smithcecf1842011-11-01 21:06:14 +00002730 // Never evaluate the initializer of a weak variable. We can't be sure that
2731 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002732 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002733 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002734 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002735 }
Richard Smithcecf1842011-11-01 21:06:14 +00002736
Richard Smithd0b4dd62011-12-19 06:19:21 +00002737 // Check that we can fold the initializer. In C++, we will have already done
2738 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002739 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002740 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002741 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002742 Notes.size() + 1) << VD;
2743 Info.Note(VD->getLocation(), diag::note_declared_at);
2744 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002745 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002746 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002747 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002748 Notes.size() + 1) << VD;
2749 Info.Note(VD->getLocation(), diag::note_declared_at);
2750 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002751 }
Richard Smith27908702011-10-24 17:54:18 +00002752
Richard Smith3229b742013-05-05 21:17:10 +00002753 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002754 return true;
Richard Smith27908702011-10-24 17:54:18 +00002755}
2756
Richard Smith11562c52011-10-28 17:51:58 +00002757static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002758 Qualifiers Quals = T.getQualifiers();
2759 return Quals.hasConst() && !Quals.hasVolatile();
2760}
2761
Richard Smithe97cbd72011-11-11 04:05:33 +00002762/// Get the base index of the given base class within an APValue representing
2763/// the given derived class.
2764static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2765 const CXXRecordDecl *Base) {
2766 Base = Base->getCanonicalDecl();
2767 unsigned Index = 0;
2768 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2769 E = Derived->bases_end(); I != E; ++I, ++Index) {
2770 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2771 return Index;
2772 }
2773
2774 llvm_unreachable("base class missing from derived class's bases list");
2775}
2776
Richard Smith3da88fa2013-04-26 14:36:30 +00002777/// Extract the value of a character from a string literal.
2778static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2779 uint64_t Index) {
Eric Fiselier708afb52019-05-16 21:04:15 +00002780 assert(!isa<SourceLocExpr>(Lit) &&
2781 "SourceLocExpr should have already been converted to a StringLiteral");
2782
Akira Hatanakabc332642017-01-31 02:31:39 +00002783 // FIXME: Support MakeStringConstant
2784 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2785 std::string Str;
2786 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2787 assert(Index <= Str.size() && "Index too large");
2788 return APSInt::getUnsigned(Str.c_str()[Index]);
2789 }
2790
Alexey Bataevec474782014-10-09 08:45:04 +00002791 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2792 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002793 const StringLiteral *S = cast<StringLiteral>(Lit);
2794 const ConstantArrayType *CAT =
2795 Info.Ctx.getAsConstantArrayType(S->getType());
2796 assert(CAT && "string literal isn't an array");
2797 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002798 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002799
2800 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002801 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002802 if (Index < S->getLength())
2803 Value = S->getCodeUnit(Index);
2804 return Value;
2805}
2806
Richard Smith3da88fa2013-04-26 14:36:30 +00002807// Expand a string literal into an array of characters.
Eli Friedman3bf72d72019-02-08 21:18:46 +00002808//
2809// FIXME: This is inefficient; we should probably introduce something similar
2810// to the LLVM ConstantDataArray to make this cheaper.
2811static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
Richard Smith3da88fa2013-04-26 14:36:30 +00002812 APValue &Result) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002813 const ConstantArrayType *CAT =
2814 Info.Ctx.getAsConstantArrayType(S->getType());
2815 assert(CAT && "string literal isn't an array");
2816 QualType CharType = CAT->getElementType();
2817 assert(CharType->isIntegerType() && "unexpected character type");
2818
2819 unsigned Elts = CAT->getSize().getZExtValue();
2820 Result = APValue(APValue::UninitArray(),
2821 std::min(S->getLength(), Elts), Elts);
2822 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2823 CharType->isUnsignedIntegerType());
2824 if (Result.hasArrayFiller())
2825 Result.getArrayFiller() = APValue(Value);
2826 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2827 Value = S->getCodeUnit(I);
2828 Result.getArrayInitializedElt(I) = APValue(Value);
2829 }
2830}
2831
2832// Expand an array so that it has more than Index filled elements.
2833static void expandArray(APValue &Array, unsigned Index) {
2834 unsigned Size = Array.getArraySize();
2835 assert(Index < Size);
2836
2837 // Always at least double the number of elements for which we store a value.
2838 unsigned OldElts = Array.getArrayInitializedElts();
2839 unsigned NewElts = std::max(Index+1, OldElts * 2);
2840 NewElts = std::min(Size, std::max(NewElts, 8u));
2841
2842 // Copy the data across.
2843 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2844 for (unsigned I = 0; I != OldElts; ++I)
2845 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2846 for (unsigned I = OldElts; I != NewElts; ++I)
2847 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2848 if (NewValue.hasArrayFiller())
2849 NewValue.getArrayFiller() = Array.getArrayFiller();
2850 Array.swap(NewValue);
2851}
2852
Richard Smithb01fe402014-09-16 01:24:02 +00002853/// Determine whether a type would actually be read by an lvalue-to-rvalue
2854/// conversion. If it's of class type, we may assume that the copy operation
2855/// is trivial. Note that this is never true for a union type with fields
2856/// (because the copy always "reads" the active member) and always true for
2857/// a non-class type.
2858static bool isReadByLvalueToRvalueConversion(QualType T) {
2859 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2860 if (!RD || (RD->isUnion() && !RD->field_empty()))
2861 return true;
2862 if (RD->isEmpty())
2863 return false;
2864
2865 for (auto *Field : RD->fields())
2866 if (isReadByLvalueToRvalueConversion(Field->getType()))
2867 return true;
2868
2869 for (auto &BaseSpec : RD->bases())
2870 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2871 return true;
2872
2873 return false;
2874}
2875
2876/// Diagnose an attempt to read from any unreadable field within the specified
2877/// type, which might be a class type.
2878static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2879 QualType T) {
2880 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2881 if (!RD)
2882 return false;
2883
2884 if (!RD->hasMutableFields())
2885 return false;
2886
2887 for (auto *Field : RD->fields()) {
2888 // If we're actually going to read this field in some way, then it can't
2889 // be mutable. If we're in a union, then assigning to a mutable field
2890 // (even an empty one) can change the active member, so that's not OK.
2891 // FIXME: Add core issue number for the union case.
2892 if (Field->isMutable() &&
2893 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002894 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002895 Info.Note(Field->getLocation(), diag::note_declared_at);
2896 return true;
2897 }
2898
2899 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2900 return true;
2901 }
2902
2903 for (auto &BaseSpec : RD->bases())
2904 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2905 return true;
2906
2907 // All mutable fields were empty, and thus not actually read.
2908 return false;
2909}
2910
Richard Smithdebad642019-05-12 09:39:08 +00002911static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2912 APValue::LValueBase Base) {
2913 // A temporary we created.
2914 if (Base.getCallIndex())
2915 return true;
2916
2917 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2918 if (!Evaluating)
2919 return false;
2920
2921 // The variable whose initializer we're evaluating.
2922 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2923 if (declaresSameEntity(Evaluating, BaseD))
2924 return true;
2925
2926 // A temporary lifetime-extended by the variable whose initializer we're
2927 // evaluating.
2928 if (auto *BaseE = Base.dyn_cast<const Expr *>())
2929 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2930 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2931 return true;
2932
2933 return false;
2934}
2935
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002936namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002937/// A handle to a complete object (an object that is not a subobject of
2938/// another object).
2939struct CompleteObject {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002940 /// The identity of the object.
2941 APValue::LValueBase Base;
Richard Smith3229b742013-05-05 21:17:10 +00002942 /// The value of the complete object.
2943 APValue *Value;
2944 /// The type of the complete object.
2945 QualType Type;
2946
Craig Topper36250ad2014-05-12 05:36:57 +00002947 CompleteObject() : Value(nullptr) {}
Richard Smithdebad642019-05-12 09:39:08 +00002948 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2949 : Base(Base), Value(Value), Type(Type) {}
2950
2951 bool mayReadMutableMembers(EvalInfo &Info) const {
2952 // In C++14 onwards, it is permitted to read a mutable member whose
2953 // lifetime began within the evaluation.
2954 // FIXME: Should we also allow this in C++11?
2955 if (!Info.getLangOpts().CPlusPlus14)
2956 return false;
2957 return lifetimeStartedInEvaluation(Info, Base);
Richard Smith3229b742013-05-05 21:17:10 +00002958 }
2959
Richard Smithdebad642019-05-12 09:39:08 +00002960 explicit operator bool() const { return !Type.isNull(); }
Richard Smith3229b742013-05-05 21:17:10 +00002961};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002962} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002963
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002964static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2965 bool IsMutable = false) {
2966 // C++ [basic.type.qualifier]p1:
2967 // - A const object is an object of type const T or a non-mutable subobject
2968 // of a const object.
2969 if (ObjType.isConstQualified() && !IsMutable)
2970 SubobjType.addConst();
2971 // - A volatile object is an object of type const T or a subobject of a
2972 // volatile object.
2973 if (ObjType.isVolatileQualified())
2974 SubobjType.addVolatile();
2975 return SubobjType;
2976}
2977
Richard Smith3da88fa2013-04-26 14:36:30 +00002978/// Find the designated sub-object of an rvalue.
2979template<typename SubobjectHandler>
2980typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002981findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002982 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002983 if (Sub.Invalid)
2984 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002985 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002986 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002987 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002988 Info.FFDiag(E, Sub.isOnePastTheEnd()
2989 ? diag::note_constexpr_access_past_end
2990 : diag::note_constexpr_access_unsized_array)
2991 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002992 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002993 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002994 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002995 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002996
Richard Smith3229b742013-05-05 21:17:10 +00002997 APValue *O = Obj.Value;
2998 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002999 const FieldDecl *LastField = nullptr;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003000 const FieldDecl *VolatileField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00003001
Richard Smithd62306a2011-11-10 06:34:14 +00003002 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003003 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
Richard Smith31c69a32019-05-21 23:15:20 +00003004 // Reading an indeterminate value is undefined, but assigning over one is OK.
3005 if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003006 if (!Info.checkingPotentialConstantExpression())
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003007 Info.FFDiag(E, diag::note_constexpr_access_uninit)
Richard Smithe637cbe2019-05-21 23:15:18 +00003008 << handler.AccessKind << O->isIndeterminate();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003009 return handler.failed();
3010 }
3011
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003012 // C++ [class.ctor]p5:
3013 // const and volatile semantics are not applied on an object under
3014 // construction.
3015 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3016 ObjType->isRecordType() &&
3017 Info.isEvaluatingConstructor(
3018 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3019 Sub.Entries.begin() + I)) !=
3020 ConstructionPhase::None) {
3021 ObjType = Info.Ctx.getCanonicalType(ObjType);
3022 ObjType.removeLocalConst();
3023 ObjType.removeLocalVolatile();
3024 }
3025
3026 // If this is our last pass, check that the final object type is OK.
3027 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3028 // Accesses to volatile objects are prohibited.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003029 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003030 if (Info.getLangOpts().CPlusPlus) {
3031 int DiagKind;
3032 SourceLocation Loc;
3033 const NamedDecl *Decl = nullptr;
3034 if (VolatileField) {
3035 DiagKind = 2;
3036 Loc = VolatileField->getLocation();
3037 Decl = VolatileField;
3038 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3039 DiagKind = 1;
3040 Loc = VD->getLocation();
3041 Decl = VD;
3042 } else {
3043 DiagKind = 0;
3044 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3045 Loc = E->getExprLoc();
3046 }
3047 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3048 << handler.AccessKind << DiagKind << Decl;
3049 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3050 } else {
3051 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3052 }
3053 return handler.failed();
3054 }
3055
Richard Smithb01fe402014-09-16 01:24:02 +00003056 // If we are reading an object of class type, there may still be more
3057 // things we need to check: if there are any mutable subobjects, we
3058 // cannot perform this read. (This only happens when performing a trivial
3059 // copy or assignment.)
3060 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smithdebad642019-05-12 09:39:08 +00003061 !Obj.mayReadMutableMembers(Info) &&
3062 diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00003063 return handler.failed();
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003064 }
Richard Smithb01fe402014-09-16 01:24:02 +00003065
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003066 if (I == N) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00003067 if (!handler.found(*O, ObjType))
3068 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003069
Richard Smith49ca8aa2013-08-06 07:09:20 +00003070 // If we modified a bit-field, truncate it to the right width.
Richard Smithdebad642019-05-12 09:39:08 +00003071 if (isModification(handler.AccessKind) &&
Richard Smith49ca8aa2013-08-06 07:09:20 +00003072 LastField && LastField->isBitField() &&
3073 !truncateBitfieldValue(Info, E, *O, LastField))
3074 return false;
3075
3076 return true;
3077 }
3078
Craig Topper36250ad2014-05-12 05:36:57 +00003079 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00003080 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00003081 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00003082 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003083 assert(CAT && "vla in literal type?");
Richard Smith5b5e27a2019-05-10 20:05:31 +00003084 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003085 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00003086 // Note, it should not be possible to form a pointer with a valid
3087 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00003088 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003089 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003090 << handler.AccessKind;
3091 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003092 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003093 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003094 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003095
3096 ObjType = CAT->getElementType();
3097
Richard Smith3da88fa2013-04-26 14:36:30 +00003098 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00003099 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00003100 else if (handler.AccessKind != AK_Read) {
3101 expandArray(*O, Index);
3102 O = &O->getArrayInitializedElt(Index);
3103 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00003104 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00003105 } else if (ObjType->isAnyComplexType()) {
3106 // Next subobject is a complex number.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003107 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smith66c96992012-02-18 22:04:06 +00003108 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003109 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003110 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003111 << handler.AccessKind;
3112 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003113 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003114 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00003115 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003116
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003117 ObjType = getSubobjectType(
3118 ObjType, ObjType->castAs<ComplexType>()->getElementType());
Richard Smith3da88fa2013-04-26 14:36:30 +00003119
Richard Smith66c96992012-02-18 22:04:06 +00003120 assert(I == N - 1 && "extracting subobject of scalar?");
3121 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003122 return handler.found(Index ? O->getComplexIntImag()
3123 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003124 } else {
3125 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00003126 return handler.found(Index ? O->getComplexFloatImag()
3127 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003128 }
Richard Smithd62306a2011-11-10 06:34:14 +00003129 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00003130 if (Field->isMutable() && handler.AccessKind == AK_Read &&
Richard Smithdebad642019-05-12 09:39:08 +00003131 !Obj.mayReadMutableMembers(Info)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003132 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00003133 << Field;
3134 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00003135 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00003136 }
3137
Richard Smithd62306a2011-11-10 06:34:14 +00003138 // Next subobject is a class, struct or union field.
3139 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3140 if (RD->isUnion()) {
3141 const FieldDecl *UnionField = O->getUnionField();
3142 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00003143 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003144 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00003145 << handler.AccessKind << Field << !UnionField << UnionField;
3146 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003147 }
Richard Smithd62306a2011-11-10 06:34:14 +00003148 O = &O->getUnionValue();
3149 } else
3150 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00003151
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003152 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
Richard Smith49ca8aa2013-08-06 07:09:20 +00003153 LastField = Field;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003154 if (Field->getType().isVolatileQualified())
3155 VolatileField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00003156 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00003157 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00003158 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3159 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3160 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00003161
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003162 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
Richard Smithf3e9e432011-11-07 09:22:26 +00003163 }
3164 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003165}
3166
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003167namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003168struct ExtractSubobjectHandler {
3169 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00003170 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00003171
3172 static const AccessKinds AccessKind = AK_Read;
3173
3174 typedef bool result_type;
3175 bool failed() { return false; }
3176 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003177 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00003178 return true;
3179 }
3180 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003181 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003182 return true;
3183 }
3184 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003185 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003186 return true;
3187 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003188};
Richard Smith3229b742013-05-05 21:17:10 +00003189} // end anonymous namespace
3190
Richard Smith3da88fa2013-04-26 14:36:30 +00003191const AccessKinds ExtractSubobjectHandler::AccessKind;
3192
3193/// Extract the designated sub-object of an rvalue.
3194static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003195 const CompleteObject &Obj,
3196 const SubobjectDesignator &Sub,
3197 APValue &Result) {
3198 ExtractSubobjectHandler Handler = { Info, Result };
3199 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003200}
3201
Richard Smith3229b742013-05-05 21:17:10 +00003202namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003203struct ModifySubobjectHandler {
3204 EvalInfo &Info;
3205 APValue &NewVal;
3206 const Expr *E;
3207
3208 typedef bool result_type;
3209 static const AccessKinds AccessKind = AK_Assign;
3210
3211 bool checkConst(QualType QT) {
3212 // Assigning to a const object has undefined behavior.
3213 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003214 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003215 return false;
3216 }
3217 return true;
3218 }
3219
3220 bool failed() { return false; }
3221 bool found(APValue &Subobj, QualType SubobjType) {
3222 if (!checkConst(SubobjType))
3223 return false;
3224 // We've been given ownership of NewVal, so just swap it in.
3225 Subobj.swap(NewVal);
3226 return true;
3227 }
3228 bool found(APSInt &Value, QualType SubobjType) {
3229 if (!checkConst(SubobjType))
3230 return false;
3231 if (!NewVal.isInt()) {
3232 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003233 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003234 return false;
3235 }
3236 Value = NewVal.getInt();
3237 return true;
3238 }
3239 bool found(APFloat &Value, QualType SubobjType) {
3240 if (!checkConst(SubobjType))
3241 return false;
3242 Value = NewVal.getFloat();
3243 return true;
3244 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003245};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003246} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003247
Richard Smith3229b742013-05-05 21:17:10 +00003248const AccessKinds ModifySubobjectHandler::AccessKind;
3249
Richard Smith3da88fa2013-04-26 14:36:30 +00003250/// Update the designated sub-object of an rvalue to the given value.
3251static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003252 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003253 const SubobjectDesignator &Sub,
3254 APValue &NewVal) {
3255 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003256 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003257}
3258
Richard Smith84f6dcf2012-02-02 01:16:57 +00003259/// Find the position where two subobject designators diverge, or equivalently
3260/// the length of the common initial subsequence.
3261static unsigned FindDesignatorMismatch(QualType ObjType,
3262 const SubobjectDesignator &A,
3263 const SubobjectDesignator &B,
3264 bool &WasArrayIndex) {
3265 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3266 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003267 if (!ObjType.isNull() &&
3268 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003269 // Next subobject is an array element.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003270 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003271 WasArrayIndex = true;
3272 return I;
3273 }
Richard Smith66c96992012-02-18 22:04:06 +00003274 if (ObjType->isAnyComplexType())
3275 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3276 else
3277 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003278 } else {
Richard Smith5b5e27a2019-05-10 20:05:31 +00003279 if (A.Entries[I].getAsBaseOrMember() !=
3280 B.Entries[I].getAsBaseOrMember()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003281 WasArrayIndex = false;
3282 return I;
3283 }
3284 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3285 // Next subobject is a field.
3286 ObjType = FD->getType();
3287 else
3288 // Next subobject is a base class.
3289 ObjType = QualType();
3290 }
3291 }
3292 WasArrayIndex = false;
3293 return I;
3294}
3295
3296/// Determine whether the given subobject designators refer to elements of the
3297/// same array object.
3298static bool AreElementsOfSameArray(QualType ObjType,
3299 const SubobjectDesignator &A,
3300 const SubobjectDesignator &B) {
3301 if (A.Entries.size() != B.Entries.size())
3302 return false;
3303
George Burgess IVa51c4072015-10-16 01:49:01 +00003304 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003305 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3306 // A is a subobject of the array element.
3307 return false;
3308
3309 // If A (and B) designates an array element, the last entry will be the array
3310 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3311 // of length 1' case, and the entire path must match.
3312 bool WasArrayIndex;
3313 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3314 return CommonLength >= A.Entries.size() - IsArray;
3315}
3316
Richard Smith3229b742013-05-05 21:17:10 +00003317/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003318static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3319 AccessKinds AK, const LValue &LVal,
3320 QualType LValType) {
Richard Smith51ce8442019-05-17 08:01:34 +00003321 if (LVal.InvalidBase) {
3322 Info.FFDiag(E);
3323 return CompleteObject();
3324 }
3325
Richard Smith3229b742013-05-05 21:17:10 +00003326 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003327 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003328 return CompleteObject();
3329 }
3330
Craig Topper36250ad2014-05-12 05:36:57 +00003331 CallStackFrame *Frame = nullptr;
Richard Smith37be3362019-05-04 04:00:45 +00003332 unsigned Depth = 0;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003333 if (LVal.getLValueCallIndex()) {
Richard Smith37be3362019-05-04 04:00:45 +00003334 std::tie(Frame, Depth) =
3335 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003336 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003337 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003338 << AK << LVal.Base.is<const ValueDecl*>();
3339 NoteLValueLocation(Info, LVal.Base);
3340 return CompleteObject();
3341 }
Richard Smith3229b742013-05-05 21:17:10 +00003342 }
3343
Richard Smith7bd54ab2019-05-15 20:22:21 +00003344 bool IsAccess = isFormalAccess(AK);
3345
Richard Smith3229b742013-05-05 21:17:10 +00003346 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3347 // is not a constant expression (even if the object is non-volatile). We also
3348 // apply this rule to C++98, in order to conform to the expected 'volatile'
3349 // semantics.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003350 if (IsAccess && LValType.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003351 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003352 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003353 << AK << LValType;
3354 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003355 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003356 return CompleteObject();
3357 }
3358
3359 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003360 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003361 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00003362
3363 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3364 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3365 // In C++11, constexpr, non-volatile variables initialized with constant
3366 // expressions are constant expressions too. Inside constexpr functions,
3367 // parameters are constant expressions even if they're non-const.
3368 // In C++1y, objects local to a constant expression (those with a Frame) are
3369 // both readable and writable inside constant expressions.
3370 // In C, such things can also be folded, although they are not ICEs.
3371 const VarDecl *VD = dyn_cast<VarDecl>(D);
3372 if (VD) {
3373 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3374 VD = VDef;
3375 }
3376 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003377 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003378 return CompleteObject();
3379 }
3380
Richard Smith3229b742013-05-05 21:17:10 +00003381 // Unless we're looking at a local variable or argument in a constexpr call,
3382 // the variable we're reading must be const.
3383 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003384 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smithdebad642019-05-12 09:39:08 +00003385 declaresSameEntity(
3386 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003387 // OK, we can read and modify an object if we're in the process of
3388 // evaluating its initializer, because its lifetime began in this
3389 // evaluation.
Richard Smithdebad642019-05-12 09:39:08 +00003390 } else if (isModification(AK)) {
3391 // All the remaining cases do not permit modification of the object.
Faisal Valie690b7a2016-07-02 22:34:24 +00003392 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003393 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003394 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003395 // OK, we can read this variable.
3396 } else if (BaseType->isIntegralOrEnumerationType()) {
Richard Smithdebad642019-05-12 09:39:08 +00003397 // In OpenCL if a variable is in constant address space it is a const
3398 // value.
Xiuli Pan244e3f62016-06-07 04:34:00 +00003399 if (!(BaseType.isConstQualified() ||
3400 (Info.getLangOpts().OpenCL &&
3401 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003402 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003403 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003404 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003405 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003406 Info.Note(VD->getLocation(), diag::note_declared_at);
3407 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003408 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003409 }
3410 return CompleteObject();
3411 }
Richard Smith7bd54ab2019-05-15 20:22:21 +00003412 } else if (!IsAccess) {
Richard Smithdebad642019-05-12 09:39:08 +00003413 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003414 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3415 // We support folding of const floating-point types, in order to make
3416 // static const data members of such types (supported as an extension)
3417 // more useful.
3418 if (Info.getLangOpts().CPlusPlus11) {
3419 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3420 Info.Note(VD->getLocation(), diag::note_declared_at);
3421 } else {
3422 Info.CCEDiag(E);
3423 }
George Burgess IVb5316982016-12-27 05:33:20 +00003424 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3425 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3426 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003427 } else {
3428 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003429 if (Info.checkingPotentialConstantExpression() &&
3430 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3431 // The definition of this variable could be constexpr. We can't
3432 // access it right now, but may be able to in future.
3433 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003434 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003435 Info.Note(VD->getLocation(), diag::note_declared_at);
3436 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003437 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003438 }
3439 return CompleteObject();
3440 }
3441 }
3442
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003443 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003444 return CompleteObject();
3445 } else {
3446 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3447
3448 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003449 if (const MaterializeTemporaryExpr *MTE =
Richard Smithee0ce3022019-05-17 07:06:46 +00003450 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
Richard Smithe6c01442013-06-05 00:46:14 +00003451 assert(MTE->getStorageDuration() == SD_Static &&
3452 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003453
Richard Smithe6c01442013-06-05 00:46:14 +00003454 // Per C++1y [expr.const]p2:
3455 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3456 // - a [...] glvalue of integral or enumeration type that refers to
3457 // a non-volatile const object [...]
3458 // [...]
3459 // - a [...] glvalue of literal type that refers to a non-volatile
3460 // object whose lifetime began within the evaluation of e.
3461 //
3462 // C++11 misses the 'began within the evaluation of e' check and
3463 // instead allows all temporaries, including things like:
3464 // int &&r = 1;
3465 // int x = ++r;
3466 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003467 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003468 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3469 const ValueDecl *ED = MTE->getExtendingDecl();
3470 if (!(BaseType.isConstQualified() &&
3471 BaseType->isIntegralOrEnumerationType()) &&
3472 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003473 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003474 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Faisal Valie690b7a2016-07-02 22:34:24 +00003475 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003476 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3477 return CompleteObject();
3478 }
3479
3480 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3481 assert(BaseVal && "got reference to unevaluated temporary");
3482 } else {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003483 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003484 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smithee0ce3022019-05-17 07:06:46 +00003485 APValue Val;
3486 LVal.moveInto(Val);
3487 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3488 << AK
3489 << Val.getAsString(Info.Ctx,
3490 Info.Ctx.getLValueReferenceType(LValType));
3491 NoteLValueLocation(Info, LVal.Base);
Richard Smithe6c01442013-06-05 00:46:14 +00003492 return CompleteObject();
3493 }
3494 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003495 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003496 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003497 }
Richard Smith7525ff62013-05-09 07:14:00 +00003498 }
3499
Richard Smith9defb7d2018-02-21 03:38:30 +00003500 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003501 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003502 //
3503 // FIXME: Not all local state is mutable. Allow local constant subobjects
3504 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003505 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3506 Info.EvalStatus.HasSideEffects) ||
Richard Smithdebad642019-05-12 09:39:08 +00003507 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
Richard Smith3229b742013-05-05 21:17:10 +00003508 return CompleteObject();
3509
Richard Smithdebad642019-05-12 09:39:08 +00003510 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003511}
3512
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003513/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003514/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3515/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003516///
3517/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003518/// \param Conv - The expression for which we are performing the conversion.
3519/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003520/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3521/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003522/// \param LVal - The glvalue on which we are attempting to perform this action.
3523/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003524static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003525 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003526 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003527 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003528 return false;
3529
Richard Smith3229b742013-05-05 21:17:10 +00003530 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003531 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Eric Fiselier708afb52019-05-16 21:04:15 +00003532
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003533 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003534 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3535 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3536 // initializer until now for such expressions. Such an expression can't be
3537 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003538 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003539 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003540 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003541 }
Richard Smith3229b742013-05-05 21:17:10 +00003542 APValue Lit;
3543 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3544 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003545 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
Richard Smith3229b742013-05-05 21:17:10 +00003546 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003547 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00003548 // Special-case character extraction so we don't have to construct an
3549 // APValue for the whole string.
Eli Friedman041adb02019-02-09 02:22:17 +00003550 assert(LVal.Designator.Entries.size() <= 1 &&
Eli Friedman3bf72d72019-02-08 21:18:46 +00003551 "Can only read characters from string literals");
Eli Friedman041adb02019-02-09 02:22:17 +00003552 if (LVal.Designator.Entries.empty()) {
3553 // Fail for now for LValue to RValue conversion of an array.
3554 // (This shouldn't show up in C/C++, but it could be triggered by a
3555 // weird EvaluateAsRValue call from a tool.)
3556 Info.FFDiag(Conv);
3557 return false;
3558 }
Eli Friedman3bf72d72019-02-08 21:18:46 +00003559 if (LVal.Designator.isOnePastTheEnd()) {
3560 if (Info.getLangOpts().CPlusPlus11)
3561 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3562 else
3563 Info.FFDiag(Conv);
3564 return false;
3565 }
Richard Smith5b5e27a2019-05-10 20:05:31 +00003566 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
Eli Friedman3bf72d72019-02-08 21:18:46 +00003567 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3568 return true;
Richard Smith96e0c102011-11-04 02:25:55 +00003569 }
Richard Smith11562c52011-10-28 17:51:58 +00003570 }
3571
Richard Smith3229b742013-05-05 21:17:10 +00003572 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3573 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003574}
3575
3576/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003577static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003578 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003579 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003580 return false;
3581
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003582 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003583 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003584 return false;
3585 }
3586
Richard Smith3229b742013-05-05 21:17:10 +00003587 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003588 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3589}
3590
3591namespace {
3592struct CompoundAssignSubobjectHandler {
3593 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003594 const Expr *E;
3595 QualType PromotedLHSType;
3596 BinaryOperatorKind Opcode;
3597 const APValue &RHS;
3598
3599 static const AccessKinds AccessKind = AK_Assign;
3600
3601 typedef bool result_type;
3602
3603 bool checkConst(QualType QT) {
3604 // Assigning to a const object has undefined behavior.
3605 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003606 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003607 return false;
3608 }
3609 return true;
3610 }
3611
3612 bool failed() { return false; }
3613 bool found(APValue &Subobj, QualType SubobjType) {
3614 switch (Subobj.getKind()) {
3615 case APValue::Int:
3616 return found(Subobj.getInt(), SubobjType);
3617 case APValue::Float:
3618 return found(Subobj.getFloat(), SubobjType);
3619 case APValue::ComplexInt:
3620 case APValue::ComplexFloat:
3621 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003622 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003623 return false;
3624 case APValue::LValue:
3625 return foundPointer(Subobj, SubobjType);
3626 default:
3627 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003628 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003629 return false;
3630 }
3631 }
3632 bool found(APSInt &Value, QualType SubobjType) {
3633 if (!checkConst(SubobjType))
3634 return false;
3635
Tan S. B.9f935e82018-12-18 07:38:06 +00003636 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003637 // We don't support compound assignment on integer-cast-to-pointer
3638 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003639 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003640 return false;
3641 }
3642
Tan S. B.9f935e82018-12-18 07:38:06 +00003643 if (RHS.isInt()) {
3644 APSInt LHS =
3645 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3646 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3647 return false;
3648 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3649 return true;
3650 } else if (RHS.isFloat()) {
3651 APFloat FValue(0.0);
3652 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3653 FValue) &&
3654 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3655 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3656 Value);
3657 }
3658
3659 Info.FFDiag(E);
3660 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003661 }
3662 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003663 return checkConst(SubobjType) &&
3664 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3665 Value) &&
3666 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3667 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003668 }
3669 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3670 if (!checkConst(SubobjType))
3671 return false;
3672
3673 QualType PointeeType;
3674 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3675 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003676
3677 if (PointeeType.isNull() || !RHS.isInt() ||
3678 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003679 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003680 return false;
3681 }
3682
Richard Smithd6cc1982017-01-31 02:23:02 +00003683 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003684 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003685 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003686
3687 LValue LVal;
3688 LVal.setFrom(Info.Ctx, Subobj);
3689 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3690 return false;
3691 LVal.moveInto(Subobj);
3692 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003693 }
Richard Smith43e77732013-05-07 04:50:00 +00003694};
3695} // end anonymous namespace
3696
3697const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3698
3699/// Perform a compound assignment of LVal <op>= RVal.
3700static bool handleCompoundAssignment(
3701 EvalInfo &Info, const Expr *E,
3702 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3703 BinaryOperatorKind Opcode, const APValue &RVal) {
3704 if (LVal.Designator.Invalid)
3705 return false;
3706
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003707 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003708 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003709 return false;
3710 }
3711
3712 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3713 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3714 RVal };
3715 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3716}
3717
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003718namespace {
3719struct IncDecSubobjectHandler {
3720 EvalInfo &Info;
3721 const UnaryOperator *E;
3722 AccessKinds AccessKind;
3723 APValue *Old;
3724
Richard Smith243ef902013-05-05 23:31:59 +00003725 typedef bool result_type;
3726
3727 bool checkConst(QualType QT) {
3728 // Assigning to a const object has undefined behavior.
3729 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003730 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003731 return false;
3732 }
3733 return true;
3734 }
3735
3736 bool failed() { return false; }
3737 bool found(APValue &Subobj, QualType SubobjType) {
3738 // Stash the old value. Also clear Old, so we don't clobber it later
3739 // if we're post-incrementing a complex.
3740 if (Old) {
3741 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003742 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003743 }
3744
3745 switch (Subobj.getKind()) {
3746 case APValue::Int:
3747 return found(Subobj.getInt(), SubobjType);
3748 case APValue::Float:
3749 return found(Subobj.getFloat(), SubobjType);
3750 case APValue::ComplexInt:
3751 return found(Subobj.getComplexIntReal(),
3752 SubobjType->castAs<ComplexType>()->getElementType()
3753 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3754 case APValue::ComplexFloat:
3755 return found(Subobj.getComplexFloatReal(),
3756 SubobjType->castAs<ComplexType>()->getElementType()
3757 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3758 case APValue::LValue:
3759 return foundPointer(Subobj, SubobjType);
3760 default:
3761 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003762 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003763 return false;
3764 }
3765 }
3766 bool found(APSInt &Value, QualType SubobjType) {
3767 if (!checkConst(SubobjType))
3768 return false;
3769
3770 if (!SubobjType->isIntegerType()) {
3771 // We don't support increment / decrement on integer-cast-to-pointer
3772 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003773 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003774 return false;
3775 }
3776
3777 if (Old) *Old = APValue(Value);
3778
3779 // bool arithmetic promotes to int, and the conversion back to bool
3780 // doesn't reduce mod 2^n, so special-case it.
3781 if (SubobjType->isBooleanType()) {
3782 if (AccessKind == AK_Increment)
3783 Value = 1;
3784 else
3785 Value = !Value;
3786 return true;
3787 }
3788
3789 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003790 if (AccessKind == AK_Increment) {
3791 ++Value;
3792
3793 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3794 APSInt ActualValue(Value, /*IsUnsigned*/true);
3795 return HandleOverflow(Info, E, ActualValue, SubobjType);
3796 }
3797 } else {
3798 --Value;
3799
3800 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3801 unsigned BitWidth = Value.getBitWidth();
3802 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3803 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003804 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003805 }
3806 }
3807 return true;
3808 }
3809 bool found(APFloat &Value, QualType SubobjType) {
3810 if (!checkConst(SubobjType))
3811 return false;
3812
3813 if (Old) *Old = APValue(Value);
3814
3815 APFloat One(Value.getSemantics(), 1);
3816 if (AccessKind == AK_Increment)
3817 Value.add(One, APFloat::rmNearestTiesToEven);
3818 else
3819 Value.subtract(One, APFloat::rmNearestTiesToEven);
3820 return true;
3821 }
3822 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3823 if (!checkConst(SubobjType))
3824 return false;
3825
3826 QualType PointeeType;
3827 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3828 PointeeType = PT->getPointeeType();
3829 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003830 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003831 return false;
3832 }
3833
3834 LValue LVal;
3835 LVal.setFrom(Info.Ctx, Subobj);
3836 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3837 AccessKind == AK_Increment ? 1 : -1))
3838 return false;
3839 LVal.moveInto(Subobj);
3840 return true;
3841 }
Richard Smith243ef902013-05-05 23:31:59 +00003842};
3843} // end anonymous namespace
3844
3845/// Perform an increment or decrement on LVal.
3846static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3847 QualType LValType, bool IsIncrement, APValue *Old) {
3848 if (LVal.Designator.Invalid)
3849 return false;
3850
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003851 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003852 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003853 return false;
3854 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003855
3856 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3857 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3858 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3859 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3860}
3861
Richard Smithe97cbd72011-11-11 04:05:33 +00003862/// Build an lvalue for the object argument of a member function call.
3863static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3864 LValue &This) {
3865 if (Object->getType()->isPointerType())
3866 return EvaluatePointer(Object, This, Info);
3867
3868 if (Object->isGLValue())
3869 return EvaluateLValue(Object, This, Info);
3870
Richard Smithd9f663b2013-04-22 15:31:51 +00003871 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003872 return EvaluateTemporary(Object, This, Info);
3873
Faisal Valie690b7a2016-07-02 22:34:24 +00003874 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003875 return false;
3876}
3877
3878/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3879/// lvalue referring to the result.
3880///
3881/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003882/// \param LV - An lvalue referring to the base of the member pointer.
3883/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003884/// \param IncludeMember - Specifies whether the member itself is included in
3885/// the resulting LValue subobject designator. This is not possible when
3886/// creating a bound member function.
3887/// \return The field or method declaration to which the member pointer refers,
3888/// or 0 if evaluation fails.
3889static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003890 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003891 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003892 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003893 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003894 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003895 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003896 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003897
3898 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3899 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003900 if (!MemPtr.getDecl()) {
3901 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003902 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003903 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003904 }
Richard Smith253c2a32012-01-27 01:14:48 +00003905
Richard Smith027bf112011-11-17 22:56:20 +00003906 if (MemPtr.isDerivedMember()) {
3907 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003908 // The end of the derived-to-base path for the base object must match the
3909 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003910 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003911 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003912 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003913 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003914 }
Richard Smith027bf112011-11-17 22:56:20 +00003915 unsigned PathLengthToMember =
3916 LV.Designator.Entries.size() - MemPtr.Path.size();
3917 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3918 const CXXRecordDecl *LVDecl = getAsBaseClass(
3919 LV.Designator.Entries[PathLengthToMember + I]);
3920 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003921 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003922 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003923 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003924 }
Richard Smith027bf112011-11-17 22:56:20 +00003925 }
3926
3927 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003928 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003929 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003930 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003931 } else if (!MemPtr.Path.empty()) {
3932 // Extend the LValue path with the member pointer's path.
3933 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3934 MemPtr.Path.size() + IncludeMember);
3935
3936 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003937 if (const PointerType *PT = LVType->getAs<PointerType>())
3938 LVType = PT->getPointeeType();
3939 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3940 assert(RD && "member pointer access on non-class-type expression");
3941 // The first class in the path is that of the lvalue.
3942 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3943 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003944 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003945 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003946 RD = Base;
3947 }
3948 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003949 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3950 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003951 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003952 }
3953
3954 // Add the member. Note that we cannot build bound member functions here.
3955 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003956 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003957 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003958 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003959 } else if (const IndirectFieldDecl *IFD =
3960 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003961 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003962 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003963 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003964 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003965 }
Richard Smith027bf112011-11-17 22:56:20 +00003966 }
3967
3968 return MemPtr.getDecl();
3969}
3970
Richard Smith84401042013-06-03 05:03:02 +00003971static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3972 const BinaryOperator *BO,
3973 LValue &LV,
3974 bool IncludeMember = true) {
3975 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3976
3977 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003978 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003979 MemberPtr MemPtr;
3980 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3981 }
Craig Topper36250ad2014-05-12 05:36:57 +00003982 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003983 }
3984
3985 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3986 BO->getRHS(), IncludeMember);
3987}
3988
Richard Smith027bf112011-11-17 22:56:20 +00003989/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3990/// the provided lvalue, which currently refers to the base object.
3991static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3992 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003993 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003994 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003995 return false;
3996
Richard Smitha8105bc2012-01-06 16:39:00 +00003997 QualType TargetQT = E->getType();
3998 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3999 TargetQT = PT->getPointeeType();
4000
4001 // Check this cast lands within the final derived-to-base subobject path.
4002 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004003 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004004 << D.MostDerivedType << TargetQT;
4005 return false;
4006 }
4007
Richard Smith027bf112011-11-17 22:56:20 +00004008 // Check the type of the final cast. We don't need to check the path,
4009 // since a cast can only be formed if the path is unique.
4010 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00004011 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4012 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00004013 if (NewEntriesSize == D.MostDerivedPathLength)
4014 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4015 else
Richard Smith027bf112011-11-17 22:56:20 +00004016 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00004017 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004018 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00004019 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00004020 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00004021 }
Richard Smith027bf112011-11-17 22:56:20 +00004022
4023 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00004024 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00004025}
4026
Mike Stump876387b2009-10-27 22:09:17 +00004027namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00004028enum EvalStmtResult {
4029 /// Evaluation failed.
4030 ESR_Failed,
4031 /// Hit a 'return' statement.
4032 ESR_Returned,
4033 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00004034 ESR_Succeeded,
4035 /// Hit a 'continue' statement.
4036 ESR_Continue,
4037 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00004038 ESR_Break,
4039 /// Still scanning for 'case' or 'default' statement.
4040 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00004041};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004042}
Richard Smith254a73d2011-10-28 22:34:42 +00004043
Richard Smith97fcf4b2016-08-14 23:15:52 +00004044static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4045 // We don't need to evaluate the initializer for a static local.
4046 if (!VD->hasLocalStorage())
4047 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00004048
Richard Smith97fcf4b2016-08-14 23:15:52 +00004049 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004050 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00004051
Richard Smith97fcf4b2016-08-14 23:15:52 +00004052 const Expr *InitE = VD->getInit();
4053 if (!InitE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004054 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
4055 << false << VD->getType();
Richard Smith97fcf4b2016-08-14 23:15:52 +00004056 Val = APValue();
4057 return false;
4058 }
Richard Smith51f03172013-06-20 03:00:05 +00004059
Richard Smith97fcf4b2016-08-14 23:15:52 +00004060 if (InitE->isValueDependent())
4061 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00004062
Richard Smith97fcf4b2016-08-14 23:15:52 +00004063 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4064 // Wipe out any partially-computed value, to allow tracking that this
4065 // evaluation failed.
4066 Val = APValue();
4067 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00004068 }
4069
4070 return true;
4071}
4072
Richard Smith97fcf4b2016-08-14 23:15:52 +00004073static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4074 bool OK = true;
4075
4076 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4077 OK &= EvaluateVarDecl(Info, VD);
4078
4079 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4080 for (auto *BD : DD->bindings())
4081 if (auto *VD = BD->getHoldingVar())
4082 OK &= EvaluateDecl(Info, VD);
4083
4084 return OK;
4085}
4086
4087
Richard Smith4e18ca52013-05-06 05:56:11 +00004088/// Evaluate a condition (either a variable declaration or an expression).
4089static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4090 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004091 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004092 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4093 return false;
4094 return EvaluateAsBooleanCondition(Cond, Result, Info);
4095}
4096
Richard Smith89210072016-04-04 23:29:43 +00004097namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004098/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00004099/// statement should be stored.
4100struct StmtResult {
4101 /// The APValue that should be filled in with the returned value.
4102 APValue &Value;
4103 /// The location containing the result, if any (used to support RVO).
4104 const LValue *Slot;
4105};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004106
4107struct TempVersionRAII {
4108 CallStackFrame &Frame;
4109
4110 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4111 Frame.pushTempVersion();
4112 }
4113
4114 ~TempVersionRAII() {
4115 Frame.popTempVersion();
4116 }
4117};
4118
Richard Smith89210072016-04-04 23:29:43 +00004119}
Richard Smith52a980a2015-08-28 02:43:42 +00004120
4121static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00004122 const Stmt *S,
4123 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00004124
4125/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00004126static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004127 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00004128 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004129 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00004130 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00004131 case ESR_Break:
4132 return ESR_Succeeded;
4133 case ESR_Succeeded:
4134 case ESR_Continue:
4135 return ESR_Continue;
4136 case ESR_Failed:
4137 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00004138 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00004139 return ESR;
4140 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00004141 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00004142}
4143
Richard Smith496ddcf2013-05-12 17:32:42 +00004144/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004145static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004146 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004147 BlockScopeRAII Scope(Info);
4148
Richard Smith496ddcf2013-05-12 17:32:42 +00004149 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00004150 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004151 {
4152 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004153 if (const Stmt *Init = SS->getInit()) {
4154 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4155 if (ESR != ESR_Succeeded)
4156 return ESR;
4157 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004158 if (SS->getConditionVariable() &&
4159 !EvaluateDecl(Info, SS->getConditionVariable()))
4160 return ESR_Failed;
4161 if (!EvaluateInteger(SS->getCond(), Value, Info))
4162 return ESR_Failed;
4163 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004164
4165 // Find the switch case corresponding to the value of the condition.
4166 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00004167 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004168 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4169 SC = SC->getNextSwitchCase()) {
4170 if (isa<DefaultStmt>(SC)) {
4171 Found = SC;
4172 continue;
4173 }
4174
4175 const CaseStmt *CS = cast<CaseStmt>(SC);
4176 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4177 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4178 : LHS;
4179 if (LHS <= Value && Value <= RHS) {
4180 Found = SC;
4181 break;
4182 }
4183 }
4184
4185 if (!Found)
4186 return ESR_Succeeded;
4187
4188 // Search the switch body for the switch case and evaluate it from there.
4189 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4190 case ESR_Break:
4191 return ESR_Succeeded;
4192 case ESR_Succeeded:
4193 case ESR_Continue:
4194 case ESR_Failed:
4195 case ESR_Returned:
4196 return ESR;
4197 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004198 // This can only happen if the switch case is nested within a statement
4199 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004200 Info.FFDiag(Found->getBeginLoc(),
4201 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004202 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004203 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004204 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004205}
4206
Richard Smith254a73d2011-10-28 22:34:42 +00004207// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004208static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004209 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004210 if (!Info.nextStep(S))
4211 return ESR_Failed;
4212
Richard Smith496ddcf2013-05-12 17:32:42 +00004213 // If we're hunting down a 'case' or 'default' label, recurse through
4214 // substatements until we hit the label.
4215 if (Case) {
4216 // FIXME: We don't start the lifetime of objects whose initialization we
4217 // jump over. However, such objects must be of class type with a trivial
4218 // default constructor that initialize all subobjects, so must be empty,
4219 // so this almost never matters.
4220 switch (S->getStmtClass()) {
4221 case Stmt::CompoundStmtClass:
4222 // FIXME: Precompute which substatement of a compound statement we
4223 // would jump to, and go straight there rather than performing a
4224 // linear scan each time.
4225 case Stmt::LabelStmtClass:
4226 case Stmt::AttributedStmtClass:
4227 case Stmt::DoStmtClass:
4228 break;
4229
4230 case Stmt::CaseStmtClass:
4231 case Stmt::DefaultStmtClass:
4232 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004233 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004234 break;
4235
4236 case Stmt::IfStmtClass: {
4237 // FIXME: Precompute which side of an 'if' we would jump to, and go
4238 // straight there rather than scanning both sides.
4239 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004240
4241 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4242 // preceded by our switch label.
4243 BlockScopeRAII Scope(Info);
4244
Richard Smith496ddcf2013-05-12 17:32:42 +00004245 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4246 if (ESR != ESR_CaseNotFound || !IS->getElse())
4247 return ESR;
4248 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4249 }
4250
4251 case Stmt::WhileStmtClass: {
4252 EvalStmtResult ESR =
4253 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4254 if (ESR != ESR_Continue)
4255 return ESR;
4256 break;
4257 }
4258
4259 case Stmt::ForStmtClass: {
4260 const ForStmt *FS = cast<ForStmt>(S);
4261 EvalStmtResult ESR =
4262 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4263 if (ESR != ESR_Continue)
4264 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004265 if (FS->getInc()) {
4266 FullExpressionRAII IncScope(Info);
4267 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4268 return ESR_Failed;
4269 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004270 break;
4271 }
4272
4273 case Stmt::DeclStmtClass:
4274 // FIXME: If the variable has initialization that can't be jumped over,
4275 // bail out of any immediately-surrounding compound-statement too.
4276 default:
4277 return ESR_CaseNotFound;
4278 }
4279 }
4280
Richard Smith254a73d2011-10-28 22:34:42 +00004281 switch (S->getStmtClass()) {
4282 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004283 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004284 // Don't bother evaluating beyond an expression-statement which couldn't
4285 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004286 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004287 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004288 return ESR_Failed;
4289 return ESR_Succeeded;
4290 }
4291
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004292 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004293 return ESR_Failed;
4294
4295 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004296 return ESR_Succeeded;
4297
Richard Smithd9f663b2013-04-22 15:31:51 +00004298 case Stmt::DeclStmtClass: {
4299 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004300 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004301 // Each declaration initialization is its own full-expression.
4302 // FIXME: This isn't quite right; if we're performing aggregate
4303 // initialization, each braced subexpression is its own full-expression.
4304 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004305 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004306 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004307 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004308 return ESR_Succeeded;
4309 }
4310
Richard Smith357362d2011-12-13 06:39:58 +00004311 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004312 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004313 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004314 if (RetExpr &&
4315 !(Result.Slot
4316 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4317 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004318 return ESR_Failed;
4319 return ESR_Returned;
4320 }
Richard Smith254a73d2011-10-28 22:34:42 +00004321
4322 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004323 BlockScopeRAII Scope(Info);
4324
Richard Smith254a73d2011-10-28 22:34:42 +00004325 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004326 for (const auto *BI : CS->body()) {
4327 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004328 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004329 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004330 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004331 return ESR;
4332 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004333 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004334 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004335
4336 case Stmt::IfStmtClass: {
4337 const IfStmt *IS = cast<IfStmt>(S);
4338
4339 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004340 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004341 if (const Stmt *Init = IS->getInit()) {
4342 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4343 if (ESR != ESR_Succeeded)
4344 return ESR;
4345 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004346 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004347 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004348 return ESR_Failed;
4349
4350 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4351 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4352 if (ESR != ESR_Succeeded)
4353 return ESR;
4354 }
4355 return ESR_Succeeded;
4356 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004357
4358 case Stmt::WhileStmtClass: {
4359 const WhileStmt *WS = cast<WhileStmt>(S);
4360 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004361 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004362 bool Continue;
4363 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4364 Continue))
4365 return ESR_Failed;
4366 if (!Continue)
4367 break;
4368
4369 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4370 if (ESR != ESR_Continue)
4371 return ESR;
4372 }
4373 return ESR_Succeeded;
4374 }
4375
4376 case Stmt::DoStmtClass: {
4377 const DoStmt *DS = cast<DoStmt>(S);
4378 bool Continue;
4379 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004380 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004381 if (ESR != ESR_Continue)
4382 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004383 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004384
Richard Smith08d6a2c2013-07-24 07:11:57 +00004385 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004386 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4387 return ESR_Failed;
4388 } while (Continue);
4389 return ESR_Succeeded;
4390 }
4391
4392 case Stmt::ForStmtClass: {
4393 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004394 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004395 if (FS->getInit()) {
4396 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4397 if (ESR != ESR_Succeeded)
4398 return ESR;
4399 }
4400 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004401 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004402 bool Continue = true;
4403 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4404 FS->getCond(), Continue))
4405 return ESR_Failed;
4406 if (!Continue)
4407 break;
4408
4409 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4410 if (ESR != ESR_Continue)
4411 return ESR;
4412
Richard Smith08d6a2c2013-07-24 07:11:57 +00004413 if (FS->getInc()) {
4414 FullExpressionRAII IncScope(Info);
4415 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4416 return ESR_Failed;
4417 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004418 }
4419 return ESR_Succeeded;
4420 }
4421
Richard Smith896e0d72013-05-06 06:51:17 +00004422 case Stmt::CXXForRangeStmtClass: {
4423 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004424 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004425
Richard Smith8baa5002018-09-28 18:44:09 +00004426 // Evaluate the init-statement if present.
4427 if (FS->getInit()) {
4428 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4429 if (ESR != ESR_Succeeded)
4430 return ESR;
4431 }
4432
Richard Smith896e0d72013-05-06 06:51:17 +00004433 // Initialize the __range variable.
4434 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4435 if (ESR != ESR_Succeeded)
4436 return ESR;
4437
4438 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004439 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4440 if (ESR != ESR_Succeeded)
4441 return ESR;
4442 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004443 if (ESR != ESR_Succeeded)
4444 return ESR;
4445
4446 while (true) {
4447 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004448 {
4449 bool Continue = true;
4450 FullExpressionRAII CondExpr(Info);
4451 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4452 return ESR_Failed;
4453 if (!Continue)
4454 break;
4455 }
Richard Smith896e0d72013-05-06 06:51:17 +00004456
4457 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004458 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004459 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4460 if (ESR != ESR_Succeeded)
4461 return ESR;
4462
4463 // Loop body.
4464 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4465 if (ESR != ESR_Continue)
4466 return ESR;
4467
4468 // Increment: ++__begin
4469 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4470 return ESR_Failed;
4471 }
4472
4473 return ESR_Succeeded;
4474 }
4475
Richard Smith496ddcf2013-05-12 17:32:42 +00004476 case Stmt::SwitchStmtClass:
4477 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4478
Richard Smith4e18ca52013-05-06 05:56:11 +00004479 case Stmt::ContinueStmtClass:
4480 return ESR_Continue;
4481
4482 case Stmt::BreakStmtClass:
4483 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004484
4485 case Stmt::LabelStmtClass:
4486 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4487
4488 case Stmt::AttributedStmtClass:
4489 // As a general principle, C++11 attributes can be ignored without
4490 // any semantic impact.
4491 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4492 Case);
4493
4494 case Stmt::CaseStmtClass:
4495 case Stmt::DefaultStmtClass:
4496 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004497 case Stmt::CXXTryStmtClass:
4498 // Evaluate try blocks by evaluating all sub statements.
4499 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004500 }
4501}
4502
Richard Smithcc36f692011-12-22 02:22:31 +00004503/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4504/// default constructor. If so, we'll fold it whether or not it's marked as
4505/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4506/// so we need special handling.
4507static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004508 const CXXConstructorDecl *CD,
4509 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004510 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4511 return false;
4512
Richard Smith66e05fe2012-01-18 05:21:49 +00004513 // Value-initialization does not call a trivial default constructor, so such a
4514 // call is a core constant expression whether or not the constructor is
4515 // constexpr.
4516 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004517 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004518 // FIXME: If DiagDecl is an implicitly-declared special member function,
4519 // we should be much more explicit about why it's not constexpr.
4520 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4521 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4522 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004523 } else {
4524 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4525 }
4526 }
4527 return true;
4528}
4529
Richard Smith357362d2011-12-13 06:39:58 +00004530/// CheckConstexprFunction - Check that a function can be called in a constant
4531/// expression.
4532static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4533 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004534 const FunctionDecl *Definition,
4535 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004536 // Potential constant expressions can contain calls to declared, but not yet
4537 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004538 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004539 Declaration->isConstexpr())
4540 return false;
4541
James Y Knightc7d3e602018-10-05 17:49:48 +00004542 // Bail out if the function declaration itself is invalid. We will
4543 // have produced a relevant diagnostic while parsing it, so just
4544 // note the problematic sub-expression.
4545 if (Declaration->isInvalidDecl()) {
4546 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004547 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004548 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004549
Richard Smithd9c6b032019-05-09 19:45:49 +00004550 // DR1872: An instantiated virtual constexpr function can't be called in a
Richard Smith921f1322019-05-13 23:35:21 +00004551 // constant expression (prior to C++20). We can still constant-fold such a
4552 // call.
4553 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4554 cast<CXXMethodDecl>(Declaration)->isVirtual())
4555 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4556
4557 if (Definition && Definition->isInvalidDecl()) {
4558 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd9c6b032019-05-09 19:45:49 +00004559 return false;
4560 }
4561
Richard Smith357362d2011-12-13 06:39:58 +00004562 // Can we evaluate this function call?
Richard Smith921f1322019-05-13 23:35:21 +00004563 if (Definition && Definition->isConstexpr() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004564 return true;
4565
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004566 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004567 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004568
Richard Smith5179eb72016-06-28 19:03:57 +00004569 // If this function is not constexpr because it is an inherited
4570 // non-constexpr constructor, diagnose that directly.
4571 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4572 if (CD && CD->isInheritingConstructor()) {
4573 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004574 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004575 DiagDecl = CD = Inherited;
4576 }
4577
4578 // FIXME: If DiagDecl is an implicitly-declared special member function
4579 // or an inheriting constructor, we should be much more explicit about why
4580 // it's not constexpr.
4581 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004582 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004583 << CD->getInheritedConstructor().getConstructor()->getParent();
4584 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004585 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004586 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004587 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4588 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004589 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004590 }
4591 return false;
4592}
4593
Richard Smithdebad642019-05-12 09:39:08 +00004594namespace {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004595struct CheckDynamicTypeHandler {
4596 AccessKinds AccessKind;
Richard Smithdebad642019-05-12 09:39:08 +00004597 typedef bool result_type;
4598 bool failed() { return false; }
4599 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4600 bool found(APSInt &Value, QualType SubobjType) { return true; }
4601 bool found(APFloat &Value, QualType SubobjType) { return true; }
4602};
4603} // end anonymous namespace
4604
Richard Smith7bd54ab2019-05-15 20:22:21 +00004605/// Check that we can access the notional vptr of an object / determine its
4606/// dynamic type.
4607static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4608 AccessKinds AK, bool Polymorphic) {
Richard Smithdab287b2019-05-13 07:51:29 +00004609 if (This.Designator.Invalid)
4610 return false;
4611
Richard Smith7bd54ab2019-05-15 20:22:21 +00004612 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
Richard Smithdebad642019-05-12 09:39:08 +00004613
4614 if (!Obj)
4615 return false;
4616
4617 if (!Obj.Value) {
4618 // The object is not usable in constant expressions, so we can't inspect
4619 // its value to see if it's in-lifetime or what the active union members
4620 // are. We can still check for a one-past-the-end lvalue.
4621 if (This.Designator.isOnePastTheEnd() ||
4622 This.Designator.isMostDerivedAnUnsizedArray()) {
4623 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4624 ? diag::note_constexpr_access_past_end
4625 : diag::note_constexpr_access_unsized_array)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004626 << AK;
Richard Smithdebad642019-05-12 09:39:08 +00004627 return false;
Richard Smith7bd54ab2019-05-15 20:22:21 +00004628 } else if (Polymorphic) {
4629 // Conservatively refuse to perform a polymorphic operation if we would
Richard Smith921f1322019-05-13 23:35:21 +00004630 // not be able to read a notional 'vptr' value.
4631 APValue Val;
4632 This.moveInto(Val);
4633 QualType StarThisType =
4634 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
Richard Smith7bd54ab2019-05-15 20:22:21 +00004635 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4636 << AK << Val.getAsString(Info.Ctx, StarThisType);
Richard Smith921f1322019-05-13 23:35:21 +00004637 return false;
Richard Smithdebad642019-05-12 09:39:08 +00004638 }
4639 return true;
4640 }
4641
Richard Smith7bd54ab2019-05-15 20:22:21 +00004642 CheckDynamicTypeHandler Handler{AK};
Richard Smithdebad642019-05-12 09:39:08 +00004643 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4644}
4645
Richard Smith7bd54ab2019-05-15 20:22:21 +00004646/// Check that the pointee of the 'this' pointer in a member function call is
4647/// either within its lifetime or in its period of construction or destruction.
4648static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4649 const LValue &This) {
4650 return checkDynamicType(Info, E, This, AK_MemberCall, false);
4651}
4652
Richard Smith921f1322019-05-13 23:35:21 +00004653struct DynamicType {
4654 /// The dynamic class type of the object.
4655 const CXXRecordDecl *Type;
4656 /// The corresponding path length in the lvalue.
4657 unsigned PathLength;
4658};
4659
4660static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4661 unsigned PathLength) {
4662 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4663 Designator.Entries.size() && "invalid path length");
4664 return (PathLength == Designator.MostDerivedPathLength)
4665 ? Designator.MostDerivedType->getAsCXXRecordDecl()
4666 : getAsBaseClass(Designator.Entries[PathLength - 1]);
4667}
4668
4669/// Determine the dynamic type of an object.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004670static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4671 LValue &This, AccessKinds AK) {
Richard Smith921f1322019-05-13 23:35:21 +00004672 // If we don't have an lvalue denoting an object of class type, there is no
4673 // meaningful dynamic type. (We consider objects of non-class type to have no
4674 // dynamic type.)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004675 if (!checkDynamicType(Info, E, This, AK, true))
Richard Smith921f1322019-05-13 23:35:21 +00004676 return None;
4677
Richard Smith7bd54ab2019-05-15 20:22:21 +00004678 // Refuse to compute a dynamic type in the presence of virtual bases. This
4679 // shouldn't happen other than in constant-folding situations, since literal
4680 // types can't have virtual bases.
4681 //
4682 // Note that consumers of DynamicType assume that the type has no virtual
4683 // bases, and will need modifications if this restriction is relaxed.
4684 const CXXRecordDecl *Class =
4685 This.Designator.MostDerivedType->getAsCXXRecordDecl();
4686 if (!Class || Class->getNumVBases()) {
4687 Info.FFDiag(E);
4688 return None;
4689 }
4690
Richard Smith921f1322019-05-13 23:35:21 +00004691 // FIXME: For very deep class hierarchies, it might be beneficial to use a
4692 // binary search here instead. But the overwhelmingly common case is that
4693 // we're not in the middle of a constructor, so it probably doesn't matter
4694 // in practice.
4695 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4696 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4697 PathLength <= Path.size(); ++PathLength) {
4698 switch (Info.isEvaluatingConstructor(This.getLValueBase(),
4699 Path.slice(0, PathLength))) {
4700 case ConstructionPhase::Bases:
4701 // We're constructing a base class. This is not the dynamic type.
4702 break;
4703
4704 case ConstructionPhase::None:
4705 case ConstructionPhase::AfterBases:
4706 // We've finished constructing the base classes, so this is the dynamic
4707 // type.
4708 return DynamicType{getBaseClassType(This.Designator, PathLength),
4709 PathLength};
4710 }
4711 }
4712
4713 // CWG issue 1517: we're constructing a base class of the object described by
4714 // 'This', so that object has not yet begun its period of construction and
4715 // any polymorphic operation on it results in undefined behavior.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004716 Info.FFDiag(E);
Richard Smith921f1322019-05-13 23:35:21 +00004717 return None;
4718}
4719
4720/// Perform virtual dispatch.
4721static const CXXMethodDecl *HandleVirtualDispatch(
4722 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4723 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004724 Optional<DynamicType> DynType =
4725 ComputeDynamicType(Info, E, This, AK_MemberCall);
4726 if (!DynType)
Richard Smith921f1322019-05-13 23:35:21 +00004727 return nullptr;
Richard Smith921f1322019-05-13 23:35:21 +00004728
4729 // Find the final overrider. It must be declared in one of the classes on the
4730 // path from the dynamic type to the static type.
4731 // FIXME: If we ever allow literal types to have virtual base classes, that
4732 // won't be true.
4733 const CXXMethodDecl *Callee = Found;
4734 unsigned PathLength = DynType->PathLength;
4735 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4736 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
Richard Smith921f1322019-05-13 23:35:21 +00004737 const CXXMethodDecl *Overrider =
4738 Found->getCorrespondingMethodDeclaredInClass(Class, false);
4739 if (Overrider) {
4740 Callee = Overrider;
4741 break;
4742 }
4743 }
4744
4745 // C++2a [class.abstract]p6:
4746 // the effect of making a virtual call to a pure virtual function [...] is
4747 // undefined
4748 if (Callee->isPure()) {
4749 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4750 Info.Note(Callee->getLocation(), diag::note_declared_at);
4751 return nullptr;
4752 }
4753
4754 // If necessary, walk the rest of the path to determine the sequence of
4755 // covariant adjustment steps to apply.
4756 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4757 Found->getReturnType())) {
4758 CovariantAdjustmentPath.push_back(Callee->getReturnType());
4759 for (unsigned CovariantPathLength = PathLength + 1;
4760 CovariantPathLength != This.Designator.Entries.size();
4761 ++CovariantPathLength) {
4762 const CXXRecordDecl *NextClass =
4763 getBaseClassType(This.Designator, CovariantPathLength);
4764 const CXXMethodDecl *Next =
4765 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4766 if (Next && !Info.Ctx.hasSameUnqualifiedType(
4767 Next->getReturnType(), CovariantAdjustmentPath.back()))
4768 CovariantAdjustmentPath.push_back(Next->getReturnType());
4769 }
4770 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4771 CovariantAdjustmentPath.back()))
4772 CovariantAdjustmentPath.push_back(Found->getReturnType());
4773 }
4774
4775 // Perform 'this' adjustment.
4776 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4777 return nullptr;
4778
4779 return Callee;
4780}
4781
4782/// Perform the adjustment from a value returned by a virtual function to
4783/// a value of the statically expected type, which may be a pointer or
4784/// reference to a base class of the returned type.
4785static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4786 APValue &Result,
4787 ArrayRef<QualType> Path) {
4788 assert(Result.isLValue() &&
4789 "unexpected kind of APValue for covariant return");
4790 if (Result.isNullPointer())
4791 return true;
4792
4793 LValue LVal;
4794 LVal.setFrom(Info.Ctx, Result);
4795
4796 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4797 for (unsigned I = 1; I != Path.size(); ++I) {
4798 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4799 assert(OldClass && NewClass && "unexpected kind of covariant return");
4800 if (OldClass != NewClass &&
4801 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4802 return false;
4803 OldClass = NewClass;
4804 }
4805
4806 LVal.moveInto(Result);
4807 return true;
4808}
4809
Richard Smith7bd54ab2019-05-15 20:22:21 +00004810/// Determine whether \p Base, which is known to be a direct base class of
4811/// \p Derived, is a public base class.
4812static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4813 const CXXRecordDecl *Base) {
4814 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4815 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4816 if (BaseClass && declaresSameEntity(BaseClass, Base))
4817 return BaseSpec.getAccessSpecifier() == AS_public;
4818 }
4819 llvm_unreachable("Base is not a direct base of Derived");
4820}
4821
4822/// Apply the given dynamic cast operation on the provided lvalue.
4823///
4824/// This implements the hard case of dynamic_cast, requiring a "runtime check"
4825/// to find a suitable target subobject.
4826static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4827 LValue &Ptr) {
4828 // We can't do anything with a non-symbolic pointer value.
4829 SubobjectDesignator &D = Ptr.Designator;
4830 if (D.Invalid)
4831 return false;
4832
4833 // C++ [expr.dynamic.cast]p6:
4834 // If v is a null pointer value, the result is a null pointer value.
4835 if (Ptr.isNullPointer() && !E->isGLValue())
4836 return true;
4837
4838 // For all the other cases, we need the pointer to point to an object within
4839 // its lifetime / period of construction / destruction, and we need to know
4840 // its dynamic type.
4841 Optional<DynamicType> DynType =
4842 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4843 if (!DynType)
4844 return false;
4845
4846 // C++ [expr.dynamic.cast]p7:
4847 // If T is "pointer to cv void", then the result is a pointer to the most
4848 // derived object
4849 if (E->getType()->isVoidPointerType())
4850 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4851
4852 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
4853 assert(C && "dynamic_cast target is not void pointer nor class");
4854 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4855
4856 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4857 // C++ [expr.dynamic.cast]p9:
4858 if (!E->isGLValue()) {
4859 // The value of a failed cast to pointer type is the null pointer value
4860 // of the required result type.
4861 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4862 Ptr.setNull(E->getType(), TargetVal);
4863 return true;
4864 }
4865
4866 // A failed cast to reference type throws [...] std::bad_cast.
4867 unsigned DiagKind;
4868 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4869 DynType->Type->isDerivedFrom(C)))
4870 DiagKind = 0;
4871 else if (!Paths || Paths->begin() == Paths->end())
4872 DiagKind = 1;
4873 else if (Paths->isAmbiguous(CQT))
4874 DiagKind = 2;
4875 else {
4876 assert(Paths->front().Access != AS_public && "why did the cast fail?");
4877 DiagKind = 3;
4878 }
4879 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4880 << DiagKind << Ptr.Designator.getType(Info.Ctx)
4881 << Info.Ctx.getRecordType(DynType->Type)
4882 << E->getType().getUnqualifiedType();
4883 return false;
4884 };
4885
4886 // Runtime check, phase 1:
4887 // Walk from the base subobject towards the derived object looking for the
4888 // target type.
4889 for (int PathLength = Ptr.Designator.Entries.size();
4890 PathLength >= (int)DynType->PathLength; --PathLength) {
4891 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4892 if (declaresSameEntity(Class, C))
4893 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4894 // We can only walk across public inheritance edges.
4895 if (PathLength > (int)DynType->PathLength &&
4896 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4897 Class))
4898 return RuntimeCheckFailed(nullptr);
4899 }
4900
4901 // Runtime check, phase 2:
4902 // Search the dynamic type for an unambiguous public base of type C.
4903 CXXBasePaths Paths(/*FindAmbiguities=*/true,
4904 /*RecordPaths=*/true, /*DetectVirtual=*/false);
4905 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4906 Paths.front().Access == AS_public) {
4907 // Downcast to the dynamic type...
4908 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4909 return false;
4910 // ... then upcast to the chosen base class subobject.
4911 for (CXXBasePathElement &Elem : Paths.front())
4912 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4913 return false;
4914 return true;
4915 }
4916
4917 // Otherwise, the runtime check fails.
4918 return RuntimeCheckFailed(&Paths);
4919}
4920
Richard Smith31c69a32019-05-21 23:15:20 +00004921namespace {
4922struct StartLifetimeOfUnionMemberHandler {
4923 const FieldDecl *Field;
4924
4925 static const AccessKinds AccessKind = AK_Assign;
4926
4927 APValue getDefaultInitValue(QualType SubobjType) {
4928 if (auto *RD = SubobjType->getAsCXXRecordDecl()) {
4929 if (RD->isUnion())
4930 return APValue((const FieldDecl*)nullptr);
4931
4932 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4933 std::distance(RD->field_begin(), RD->field_end()));
4934
4935 unsigned Index = 0;
4936 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4937 End = RD->bases_end(); I != End; ++I, ++Index)
4938 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4939
4940 for (const auto *I : RD->fields()) {
4941 if (I->isUnnamedBitfield())
4942 continue;
4943 Struct.getStructField(I->getFieldIndex()) =
4944 getDefaultInitValue(I->getType());
4945 }
4946 return Struct;
4947 }
4948
4949 if (auto *AT = dyn_cast_or_null<ConstantArrayType>(
4950 SubobjType->getAsArrayTypeUnsafe())) {
4951 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4952 if (Array.hasArrayFiller())
4953 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4954 return Array;
4955 }
4956
4957 return APValue::IndeterminateValue();
4958 }
4959
4960 typedef bool result_type;
4961 bool failed() { return false; }
4962 bool found(APValue &Subobj, QualType SubobjType) {
4963 // We are supposed to perform no initialization but begin the lifetime of
4964 // the object. We interpret that as meaning to do what default
4965 // initialization of the object would do if all constructors involved were
4966 // trivial:
4967 // * All base, non-variant member, and array element subobjects' lifetimes
4968 // begin
4969 // * No variant members' lifetimes begin
4970 // * All scalar subobjects whose lifetimes begin have indeterminate values
4971 assert(SubobjType->isUnionType());
4972 if (!declaresSameEntity(Subobj.getUnionField(), Field))
4973 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
4974 return true;
4975 }
4976 bool found(APSInt &Value, QualType SubobjType) {
4977 llvm_unreachable("wrong value kind for union object");
4978 }
4979 bool found(APFloat &Value, QualType SubobjType) {
4980 llvm_unreachable("wrong value kind for union object");
4981 }
4982};
4983} // end anonymous namespace
4984
4985const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
4986
4987/// Handle a builtin simple-assignment or a call to a trivial assignment
4988/// operator whose left-hand side might involve a union member access. If it
4989/// does, implicitly start the lifetime of any accessed union elements per
4990/// C++20 [class.union]5.
4991static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
4992 const LValue &LHS) {
4993 if (LHS.InvalidBase || LHS.Designator.Invalid)
4994 return false;
4995
4996 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
4997 // C++ [class.union]p5:
4998 // define the set S(E) of subexpressions of E as follows:
Richard Smith31c69a32019-05-21 23:15:20 +00004999 unsigned PathLength = LHS.Designator.Entries.size();
Eric Fiselierffafdb92019-05-23 23:34:43 +00005000 for (const Expr *E = LHSExpr; E != nullptr;) {
Richard Smith31c69a32019-05-21 23:15:20 +00005001 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5002 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5003 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5004 if (!FD)
5005 break;
5006
5007 // ... and also contains A.B if B names a union member
5008 if (FD->getParent()->isUnion())
5009 UnionPathLengths.push_back({PathLength - 1, FD});
5010
5011 E = ME->getBase();
5012 --PathLength;
5013 assert(declaresSameEntity(FD,
5014 LHS.Designator.Entries[PathLength]
5015 .getAsBaseOrMember().getPointer()));
5016
5017 // -- If E is of the form A[B] and is interpreted as a built-in array
5018 // subscripting operator, S(E) is [S(the array operand, if any)].
5019 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5020 // Step over an ArrayToPointerDecay implicit cast.
5021 auto *Base = ASE->getBase()->IgnoreImplicit();
5022 if (!Base->getType()->isArrayType())
5023 break;
5024
5025 E = Base;
5026 --PathLength;
5027
5028 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5029 // Step over a derived-to-base conversion.
Eric Fiselierffafdb92019-05-23 23:34:43 +00005030 E = ICE->getSubExpr();
Richard Smith31c69a32019-05-21 23:15:20 +00005031 if (ICE->getCastKind() == CK_NoOp)
5032 continue;
5033 if (ICE->getCastKind() != CK_DerivedToBase &&
5034 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5035 break;
Richard Smitha481b012019-05-30 20:45:12 +00005036 // Walk path backwards as we walk up from the base to the derived class.
5037 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
Richard Smith31c69a32019-05-21 23:15:20 +00005038 --PathLength;
Dmitri Gribenkoa10fe832019-05-22 06:57:23 +00005039 (void)Elt;
Richard Smith31c69a32019-05-21 23:15:20 +00005040 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5041 LHS.Designator.Entries[PathLength]
5042 .getAsBaseOrMember().getPointer()));
5043 }
Richard Smith31c69a32019-05-21 23:15:20 +00005044
5045 // -- Otherwise, S(E) is empty.
5046 } else {
5047 break;
5048 }
5049 }
5050
5051 // Common case: no unions' lifetimes are started.
5052 if (UnionPathLengths.empty())
5053 return true;
5054
5055 // if modification of X [would access an inactive union member], an object
5056 // of the type of X is implicitly created
5057 CompleteObject Obj =
5058 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5059 if (!Obj)
5060 return false;
5061 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5062 llvm::reverse(UnionPathLengths)) {
5063 // Form a designator for the union object.
5064 SubobjectDesignator D = LHS.Designator;
5065 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5066
5067 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5068 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5069 return false;
5070 }
5071
5072 return true;
5073}
5074
Richard Smithbe6dd812014-11-19 21:27:17 +00005075/// Determine if a class has any fields that might need to be copied by a
5076/// trivial copy or move operation.
5077static bool hasFields(const CXXRecordDecl *RD) {
5078 if (!RD || RD->isEmpty())
5079 return false;
5080 for (auto *FD : RD->fields()) {
5081 if (FD->isUnnamedBitfield())
5082 continue;
5083 return true;
5084 }
5085 for (auto &Base : RD->bases())
5086 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5087 return true;
5088 return false;
5089}
5090
Richard Smithd62306a2011-11-10 06:34:14 +00005091namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00005092typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00005093}
5094
5095/// EvaluateArgs - Evaluate the arguments to a function call.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005096static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5097 EvalInfo &Info, const FunctionDecl *Callee) {
Richard Smith253c2a32012-01-27 01:14:48 +00005098 bool Success = true;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005099 llvm::SmallBitVector ForbiddenNullArgs;
5100 if (Callee->hasAttr<NonNullAttr>()) {
5101 ForbiddenNullArgs.resize(Args.size());
5102 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5103 if (!Attr->args_size()) {
5104 ForbiddenNullArgs.set();
5105 break;
5106 } else
5107 for (auto Idx : Attr->args()) {
5108 unsigned ASTIdx = Idx.getASTIndex();
5109 if (ASTIdx >= Args.size())
5110 continue;
5111 ForbiddenNullArgs[ASTIdx] = 1;
5112 }
5113 }
5114 }
Richard Smithd62306a2011-11-10 06:34:14 +00005115 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00005116 I != E; ++I) {
5117 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5118 // If we're checking for a potential constant expression, evaluate all
5119 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005120 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005121 return false;
5122 Success = false;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005123 } else if (!ForbiddenNullArgs.empty() &&
5124 ForbiddenNullArgs[I - Args.begin()] &&
5125 ArgValues[I - Args.begin()].isNullPointer()) {
5126 Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
5127 if (!Info.noteFailure())
5128 return false;
5129 Success = false;
Richard Smith253c2a32012-01-27 01:14:48 +00005130 }
5131 }
5132 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005133}
5134
Richard Smith254a73d2011-10-28 22:34:42 +00005135/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00005136static bool HandleFunctionCall(SourceLocation CallLoc,
5137 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005138 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00005139 EvalInfo &Info, APValue &Result,
5140 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00005141 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005142 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
Richard Smithd62306a2011-11-10 06:34:14 +00005143 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00005144
Richard Smith253c2a32012-01-27 01:14:48 +00005145 if (!Info.CheckCallLimit(CallLoc))
5146 return false;
5147
5148 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00005149
5150 // For a trivial copy or move assignment, perform an APValue copy. This is
5151 // essential for unions, where the operations performed by the assignment
5152 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00005153 //
5154 // Skip this for non-union classes with no fields; in that case, the defaulted
5155 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00005156 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00005157 if (MD && MD->isDefaulted() &&
5158 (MD->getParent()->isUnion() ||
5159 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00005160 assert(This &&
5161 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5162 LValue RHS;
5163 RHS.setFrom(Info.Ctx, ArgValues[0]);
5164 APValue RHSValue;
5165 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
5166 RHS, RHSValue))
5167 return false;
Richard Smith31c69a32019-05-21 23:15:20 +00005168 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5169 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5170 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00005171 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00005172 RHSValue))
5173 return false;
5174 This->moveInto(Result);
5175 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00005176 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00005177 // We're in a lambda; determine the lambda capture field maps unless we're
5178 // just constexpr checking a lambda's call operator. constexpr checking is
5179 // done before the captures have been added to the closure object (unless
5180 // we're inferring constexpr-ness), so we don't have access to them in this
5181 // case. But since we don't need the captures to constexpr check, we can
5182 // just ignore them.
5183 if (!Info.checkingPotentialConstantExpression())
5184 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5185 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00005186 }
5187
Richard Smith52a980a2015-08-28 02:43:42 +00005188 StmtResult Ret = {Result, ResultSlot};
5189 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00005190 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00005191 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00005192 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005193 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00005194 }
Richard Smithd9f663b2013-04-22 15:31:51 +00005195 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00005196}
5197
Richard Smithd62306a2011-11-10 06:34:14 +00005198/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00005199static bool HandleConstructorCall(const Expr *E, const LValue &This,
5200 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00005201 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00005202 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00005203 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00005204 if (!Info.CheckCallLimit(CallLoc))
5205 return false;
5206
Richard Smith3607ffe2012-02-13 03:54:03 +00005207 const CXXRecordDecl *RD = Definition->getParent();
5208 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005209 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00005210 return false;
5211 }
5212
Erik Pilkington42925492017-10-04 00:18:55 +00005213 EvalInfo::EvaluatingConstructorRAII EvalObj(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005214 Info,
5215 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5216 RD->getNumBases());
Richard Smith5179eb72016-06-28 19:03:57 +00005217 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00005218
Richard Smith52a980a2015-08-28 02:43:42 +00005219 // FIXME: Creating an APValue just to hold a nonexistent return value is
5220 // wasteful.
5221 APValue RetVal;
5222 StmtResult Ret = {RetVal, nullptr};
5223
Richard Smith5179eb72016-06-28 19:03:57 +00005224 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00005225 if (Definition->isDelegatingConstructor()) {
5226 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00005227 {
5228 FullExpressionRAII InitScope(Info);
5229 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
5230 return false;
5231 }
Richard Smith52a980a2015-08-28 02:43:42 +00005232 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005233 }
5234
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005235 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00005236 // essential for unions (or classes with anonymous union members), where the
5237 // operations performed by the constructor cannot be represented by
5238 // ctor-initializers.
5239 //
5240 // Skip this for empty non-union classes; we should not perform an
5241 // lvalue-to-rvalue conversion on them because their copy constructor does not
5242 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00005243 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00005244 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00005245 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005246 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00005247 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00005248 return handleLValueToRValueConversion(
5249 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5250 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005251 }
5252
5253 // Reserve space for the struct members.
Richard Smithe637cbe2019-05-21 23:15:18 +00005254 if (!RD->isUnion() && !Result.hasValue())
Richard Smithd62306a2011-11-10 06:34:14 +00005255 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005256 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005257
John McCalld7bca762012-05-01 00:38:49 +00005258 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005259 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5260
Richard Smith08d6a2c2013-07-24 07:11:57 +00005261 // A scope for temporaries lifetime-extended by reference members.
5262 BlockScopeRAII LifetimeExtendedScope(Info);
5263
Richard Smith253c2a32012-01-27 01:14:48 +00005264 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005265 unsigned BasesSeen = 0;
5266#ifndef NDEBUG
5267 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5268#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005269 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005270 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005271 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00005272 APValue *Value = &Result;
5273
5274 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00005275 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005276 if (I->isBaseInitializer()) {
5277 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00005278#ifndef NDEBUG
5279 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00005280 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00005281 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5282 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5283 "base class initializers not in expected order");
5284 ++BaseIt;
5285#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005286 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00005287 BaseType->getAsCXXRecordDecl(), &Layout))
5288 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005289 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00005290 } else if ((FD = I->getMember())) {
5291 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005292 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005293 if (RD->isUnion()) {
5294 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00005295 Value = &Result.getUnionValue();
5296 } else {
5297 Value = &Result.getStructField(FD->getFieldIndex());
5298 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00005299 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005300 // Walk the indirect field decl's chain to find the object to initialize,
5301 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005302 auto IndirectFieldChain = IFD->chain();
5303 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00005304 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005305 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5306 // Switch the union field if it differs. This happens if we had
5307 // preceding zero-initialization, and we're now initializing a union
5308 // subobject other than the first.
5309 // FIXME: In this case, the values of the other subobjects are
5310 // specified, since zero-initialization sets all padding bits to zero.
Richard Smithe637cbe2019-05-21 23:15:18 +00005311 if (!Value->hasValue() ||
Richard Smith1b78b3d2012-01-25 22:15:11 +00005312 (Value->isUnion() && Value->getUnionField() != FD)) {
5313 if (CD->isUnion())
5314 *Value = APValue(FD);
5315 else
5316 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005317 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00005318 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005319 // Store Subobject as its parent before updating it for the last element
5320 // in the chain.
5321 if (C == IndirectFieldChain.back())
5322 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005323 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00005324 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005325 if (CD->isUnion())
5326 Value = &Value->getUnionValue();
5327 else
5328 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00005329 }
Richard Smithd62306a2011-11-10 06:34:14 +00005330 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005331 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00005332 }
Richard Smith253c2a32012-01-27 01:14:48 +00005333
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005334 // Need to override This for implicit field initializers as in this case
5335 // This refers to innermost anonymous struct/union containing initializer,
5336 // not to currently constructed class.
5337 const Expr *Init = I->getInit();
5338 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5339 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00005340 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005341 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5342 (FD && FD->isBitField() &&
5343 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005344 // If we're checking for a potential constant expression, evaluate all
5345 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005346 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005347 return false;
5348 Success = false;
5349 }
Richard Smith921f1322019-05-13 23:35:21 +00005350
5351 // This is the point at which the dynamic type of the object becomes this
5352 // class type.
5353 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5354 EvalObj.finishedConstructingBases();
Richard Smithd62306a2011-11-10 06:34:14 +00005355 }
5356
Richard Smithd9f663b2013-04-22 15:31:51 +00005357 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00005358 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005359}
5360
Richard Smith5179eb72016-06-28 19:03:57 +00005361static bool HandleConstructorCall(const Expr *E, const LValue &This,
5362 ArrayRef<const Expr*> Args,
5363 const CXXConstructorDecl *Definition,
5364 EvalInfo &Info, APValue &Result) {
5365 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005366 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
Richard Smith5179eb72016-06-28 19:03:57 +00005367 return false;
5368
5369 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5370 Info, Result);
5371}
5372
Eli Friedman9a156e52008-11-12 09:44:48 +00005373//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00005374// Generic Evaluation
5375//===----------------------------------------------------------------------===//
5376namespace {
5377
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005378class BitCastBuffer {
5379 // FIXME: We're going to need bit-level granularity when we support
5380 // bit-fields.
5381 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
5382 // we don't support a host or target where that is the case. Still, we should
5383 // use a more generic type in case we ever do.
5384 SmallVector<Optional<unsigned char>, 32> Bytes;
5385
5386 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
5387 "Need at least 8 bit unsigned char");
5388
5389 bool TargetIsLittleEndian;
5390
5391public:
5392 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
5393 : Bytes(Width.getQuantity()),
5394 TargetIsLittleEndian(TargetIsLittleEndian) {}
5395
5396 LLVM_NODISCARD
5397 bool readObject(CharUnits Offset, CharUnits Width,
5398 SmallVectorImpl<unsigned char> &Output) const {
5399 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
5400 // If a byte of an integer is uninitialized, then the whole integer is
5401 // uninitalized.
5402 if (!Bytes[I.getQuantity()])
5403 return false;
5404 Output.push_back(*Bytes[I.getQuantity()]);
5405 }
5406 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5407 std::reverse(Output.begin(), Output.end());
5408 return true;
5409 }
5410
5411 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
5412 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5413 std::reverse(Input.begin(), Input.end());
5414
5415 size_t Index = 0;
5416 for (unsigned char Byte : Input) {
5417 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
5418 Bytes[Offset.getQuantity() + Index] = Byte;
5419 ++Index;
5420 }
5421 }
5422
5423 size_t size() { return Bytes.size(); }
5424};
5425
5426/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
5427/// target would represent the value at runtime.
5428class APValueToBufferConverter {
5429 EvalInfo &Info;
5430 BitCastBuffer Buffer;
5431 const CastExpr *BCE;
5432
5433 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
5434 const CastExpr *BCE)
5435 : Info(Info),
5436 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
5437 BCE(BCE) {}
5438
5439 bool visit(const APValue &Val, QualType Ty) {
5440 return visit(Val, Ty, CharUnits::fromQuantity(0));
5441 }
5442
5443 // Write out Val with type Ty into Buffer starting at Offset.
5444 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
5445 assert((size_t)Offset.getQuantity() <= Buffer.size());
5446
5447 // As a special case, nullptr_t has an indeterminate value.
5448 if (Ty->isNullPtrType())
5449 return true;
5450
5451 // Dig through Src to find the byte at SrcOffset.
5452 switch (Val.getKind()) {
5453 case APValue::Indeterminate:
5454 case APValue::None:
5455 return true;
5456
5457 case APValue::Int:
5458 return visitInt(Val.getInt(), Ty, Offset);
5459 case APValue::Float:
5460 return visitFloat(Val.getFloat(), Ty, Offset);
5461 case APValue::Array:
5462 return visitArray(Val, Ty, Offset);
5463 case APValue::Struct:
5464 return visitRecord(Val, Ty, Offset);
5465
5466 case APValue::ComplexInt:
5467 case APValue::ComplexFloat:
5468 case APValue::Vector:
5469 case APValue::FixedPoint:
5470 // FIXME: We should support these.
5471
5472 case APValue::Union:
5473 case APValue::MemberPointer:
5474 case APValue::AddrLabelDiff: {
5475 Info.FFDiag(BCE->getBeginLoc(),
5476 diag::note_constexpr_bit_cast_unsupported_type)
5477 << Ty;
5478 return false;
5479 }
5480
5481 case APValue::LValue:
5482 llvm_unreachable("LValue subobject in bit_cast?");
5483 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00005484 llvm_unreachable("Unhandled APValue::ValueKind");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005485 }
5486
5487 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
5488 const RecordDecl *RD = Ty->getAsRecordDecl();
5489 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5490
5491 // Visit the base classes.
5492 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5493 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5494 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5495 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5496
5497 if (!visitRecord(Val.getStructBase(I), BS.getType(),
5498 Layout.getBaseClassOffset(BaseDecl) + Offset))
5499 return false;
5500 }
5501 }
5502
5503 // Visit the fields.
5504 unsigned FieldIdx = 0;
5505 for (FieldDecl *FD : RD->fields()) {
5506 if (FD->isBitField()) {
5507 Info.FFDiag(BCE->getBeginLoc(),
5508 diag::note_constexpr_bit_cast_unsupported_bitfield);
5509 return false;
5510 }
5511
5512 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5513
5514 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
5515 "only bit-fields can have sub-char alignment");
5516 CharUnits FieldOffset =
5517 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
5518 QualType FieldTy = FD->getType();
5519 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
5520 return false;
5521 ++FieldIdx;
5522 }
5523
5524 return true;
5525 }
5526
5527 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
5528 const auto *CAT =
5529 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
5530 if (!CAT)
5531 return false;
5532
5533 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
5534 unsigned NumInitializedElts = Val.getArrayInitializedElts();
5535 unsigned ArraySize = Val.getArraySize();
5536 // First, initialize the initialized elements.
5537 for (unsigned I = 0; I != NumInitializedElts; ++I) {
5538 const APValue &SubObj = Val.getArrayInitializedElt(I);
5539 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
5540 return false;
5541 }
5542
5543 // Next, initialize the rest of the array using the filler.
5544 if (Val.hasArrayFiller()) {
5545 const APValue &Filler = Val.getArrayFiller();
5546 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
5547 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
5548 return false;
5549 }
5550 }
5551
5552 return true;
5553 }
5554
5555 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
5556 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
5557 SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
5558 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
5559 Buffer.writeObject(Offset, Bytes);
5560 return true;
5561 }
5562
5563 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
5564 APSInt AsInt(Val.bitcastToAPInt());
5565 return visitInt(AsInt, Ty, Offset);
5566 }
5567
5568public:
5569 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
5570 const CastExpr *BCE) {
5571 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
5572 APValueToBufferConverter Converter(Info, DstSize, BCE);
5573 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
5574 return None;
5575 return Converter.Buffer;
5576 }
5577};
5578
5579/// Write an BitCastBuffer into an APValue.
5580class BufferToAPValueConverter {
5581 EvalInfo &Info;
5582 const BitCastBuffer &Buffer;
5583 const CastExpr *BCE;
5584
5585 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
5586 const CastExpr *BCE)
5587 : Info(Info), Buffer(Buffer), BCE(BCE) {}
5588
5589 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
5590 // with an invalid type, so anything left is a deficiency on our part (FIXME).
5591 // Ideally this will be unreachable.
5592 llvm::NoneType unsupportedType(QualType Ty) {
5593 Info.FFDiag(BCE->getBeginLoc(),
5594 diag::note_constexpr_bit_cast_unsupported_type)
5595 << Ty;
5596 return None;
5597 }
5598
5599 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
5600 const EnumType *EnumSugar = nullptr) {
5601 if (T->isNullPtrType()) {
5602 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
5603 return APValue((Expr *)nullptr,
5604 /*Offset=*/CharUnits::fromQuantity(NullValue),
5605 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
5606 }
5607
5608 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
5609 SmallVector<uint8_t, 8> Bytes;
5610 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
5611 // If this is std::byte or unsigned char, then its okay to store an
5612 // indeterminate value.
5613 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
5614 bool IsUChar =
5615 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
5616 T->isSpecificBuiltinType(BuiltinType::Char_U));
5617 if (!IsStdByte && !IsUChar) {
5618 QualType DisplayType(EnumSugar ? (Type *)EnumSugar : T, 0);
5619 Info.FFDiag(BCE->getExprLoc(),
5620 diag::note_constexpr_bit_cast_indet_dest)
5621 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
5622 return None;
5623 }
5624
5625 return APValue::IndeterminateValue();
5626 }
5627
5628 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
5629 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
5630
5631 if (T->isIntegralOrEnumerationType()) {
5632 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
5633 return APValue(Val);
5634 }
5635
5636 if (T->isRealFloatingType()) {
5637 const llvm::fltSemantics &Semantics =
5638 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
5639 return APValue(APFloat(Semantics, Val));
5640 }
5641
5642 return unsupportedType(QualType(T, 0));
5643 }
5644
5645 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
5646 const RecordDecl *RD = RTy->getAsRecordDecl();
5647 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5648
5649 unsigned NumBases = 0;
5650 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
5651 NumBases = CXXRD->getNumBases();
5652
5653 APValue ResultVal(APValue::UninitStruct(), NumBases,
5654 std::distance(RD->field_begin(), RD->field_end()));
5655
5656 // Visit the base classes.
5657 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5658 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5659 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5660 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5661 if (BaseDecl->isEmpty() ||
5662 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
5663 continue;
5664
5665 Optional<APValue> SubObj = visitType(
5666 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
5667 if (!SubObj)
5668 return None;
5669 ResultVal.getStructBase(I) = *SubObj;
5670 }
5671 }
5672
5673 // Visit the fields.
5674 unsigned FieldIdx = 0;
5675 for (FieldDecl *FD : RD->fields()) {
5676 // FIXME: We don't currently support bit-fields. A lot of the logic for
5677 // this is in CodeGen, so we need to factor it around.
5678 if (FD->isBitField()) {
5679 Info.FFDiag(BCE->getBeginLoc(),
5680 diag::note_constexpr_bit_cast_unsupported_bitfield);
5681 return None;
5682 }
5683
5684 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5685 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
5686
5687 CharUnits FieldOffset =
5688 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
5689 Offset;
5690 QualType FieldTy = FD->getType();
5691 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
5692 if (!SubObj)
5693 return None;
5694 ResultVal.getStructField(FieldIdx) = *SubObj;
5695 ++FieldIdx;
5696 }
5697
5698 return ResultVal;
5699 }
5700
5701 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
5702 QualType RepresentationType = Ty->getDecl()->getIntegerType();
5703 assert(!RepresentationType.isNull() &&
5704 "enum forward decl should be caught by Sema");
5705 const BuiltinType *AsBuiltin =
5706 RepresentationType.getCanonicalType()->getAs<BuiltinType>();
5707 assert(AsBuiltin && "non-integral enum underlying type?");
5708 // Recurse into the underlying type. Treat std::byte transparently as
5709 // unsigned char.
5710 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
5711 }
5712
5713 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
5714 size_t Size = Ty->getSize().getLimitedValue();
5715 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
5716
5717 APValue ArrayValue(APValue::UninitArray(), Size, Size);
5718 for (size_t I = 0; I != Size; ++I) {
5719 Optional<APValue> ElementValue =
5720 visitType(Ty->getElementType(), Offset + I * ElementWidth);
5721 if (!ElementValue)
5722 return None;
5723 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
5724 }
5725
5726 return ArrayValue;
5727 }
5728
5729 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
5730 return unsupportedType(QualType(Ty, 0));
5731 }
5732
5733 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
5734 QualType Can = Ty.getCanonicalType();
5735
5736 switch (Can->getTypeClass()) {
5737#define TYPE(Class, Base) \
5738 case Type::Class: \
5739 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
5740#define ABSTRACT_TYPE(Class, Base)
5741#define NON_CANONICAL_TYPE(Class, Base) \
5742 case Type::Class: \
5743 llvm_unreachable("non-canonical type should be impossible!");
5744#define DEPENDENT_TYPE(Class, Base) \
5745 case Type::Class: \
5746 llvm_unreachable( \
5747 "dependent types aren't supported in the constant evaluator!");
5748#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
5749 case Type::Class: \
5750 llvm_unreachable("either dependent or not canonical!");
5751#include "clang/AST/TypeNodes.def"
5752 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00005753 llvm_unreachable("Unhandled Type::TypeClass");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005754 }
5755
5756public:
5757 // Pull out a full value of type DstType.
5758 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
5759 const CastExpr *BCE) {
5760 BufferToAPValueConverter Converter(Info, Buffer, BCE);
5761 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
5762 }
5763};
5764
5765static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
5766 QualType Ty, EvalInfo *Info,
5767 const ASTContext &Ctx,
5768 bool CheckingDest) {
5769 Ty = Ty.getCanonicalType();
5770
5771 auto diag = [&](int Reason) {
5772 if (Info)
5773 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
5774 << CheckingDest << (Reason == 4) << Reason;
5775 return false;
5776 };
5777 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
5778 if (Info)
5779 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
5780 << NoteTy << Construct << Ty;
5781 return false;
5782 };
5783
5784 if (Ty->isUnionType())
5785 return diag(0);
5786 if (Ty->isPointerType())
5787 return diag(1);
5788 if (Ty->isMemberPointerType())
5789 return diag(2);
5790 if (Ty.isVolatileQualified())
5791 return diag(3);
5792
5793 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
5794 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
5795 for (CXXBaseSpecifier &BS : CXXRD->bases())
5796 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
5797 CheckingDest))
5798 return note(1, BS.getType(), BS.getBeginLoc());
5799 }
5800 for (FieldDecl *FD : Record->fields()) {
5801 if (FD->getType()->isReferenceType())
5802 return diag(4);
5803 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
5804 CheckingDest))
5805 return note(0, FD->getType(), FD->getBeginLoc());
5806 }
5807 }
5808
5809 if (Ty->isArrayType() &&
5810 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
5811 Info, Ctx, CheckingDest))
5812 return false;
5813
5814 return true;
5815}
5816
5817static bool checkBitCastConstexprEligibility(EvalInfo *Info,
5818 const ASTContext &Ctx,
5819 const CastExpr *BCE) {
5820 bool DestOK = checkBitCastConstexprEligibilityType(
5821 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
5822 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
5823 BCE->getBeginLoc(),
5824 BCE->getSubExpr()->getType(), Info, Ctx, false);
5825 return SourceOK;
5826}
5827
5828static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
5829 APValue &SourceValue,
5830 const CastExpr *BCE) {
5831 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
5832 "no host or target supports non 8-bit chars");
5833 assert(SourceValue.isLValue() &&
5834 "LValueToRValueBitcast requires an lvalue operand!");
5835
5836 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
5837 return false;
5838
5839 LValue SourceLValue;
5840 APValue SourceRValue;
5841 SourceLValue.setFrom(Info.Ctx, SourceValue);
5842 if (!handleLValueToRValueConversion(Info, BCE,
5843 BCE->getSubExpr()->getType().withConst(),
5844 SourceLValue, SourceRValue))
5845 return false;
5846
5847 // Read out SourceValue into a char buffer.
5848 Optional<BitCastBuffer> Buffer =
5849 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
5850 if (!Buffer)
5851 return false;
5852
5853 // Write out the buffer into a new APValue.
5854 Optional<APValue> MaybeDestValue =
5855 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
5856 if (!MaybeDestValue)
5857 return false;
5858
5859 DestValue = std::move(*MaybeDestValue);
5860 return true;
5861}
5862
Aaron Ballman68af21c2014-01-03 19:26:43 +00005863template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00005864class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005865 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00005866private:
Richard Smith52a980a2015-08-28 02:43:42 +00005867 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005868 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005869 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005870 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005871 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005872 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005873 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005874
Richard Smith17100ba2012-02-16 02:46:34 +00005875 // Check whether a conditional operator with a non-constant condition is a
5876 // potential constant expression. If neither arm is a potential constant
5877 // expression, then the conditional operator is not either.
5878 template<typename ConditionalOperator>
5879 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005880 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00005881
5882 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00005883 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00005884 {
Richard Smith17100ba2012-02-16 02:46:34 +00005885 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00005886 StmtVisitorTy::Visit(E->getFalseExpr());
5887 if (Diag.empty())
5888 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00005889 }
Richard Smith17100ba2012-02-16 02:46:34 +00005890
George Burgess IV8c892b52016-05-25 22:31:54 +00005891 {
5892 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00005893 Diag.clear();
5894 StmtVisitorTy::Visit(E->getTrueExpr());
5895 if (Diag.empty())
5896 return;
5897 }
5898
5899 Error(E, diag::note_constexpr_conditional_never_const);
5900 }
5901
5902
5903 template<typename ConditionalOperator>
5904 bool HandleConditionalOperator(const ConditionalOperator *E) {
5905 bool BoolResult;
5906 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00005907 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00005908 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00005909 return false;
5910 }
5911 if (Info.noteFailure()) {
5912 StmtVisitorTy::Visit(E->getTrueExpr());
5913 StmtVisitorTy::Visit(E->getFalseExpr());
5914 }
Richard Smith17100ba2012-02-16 02:46:34 +00005915 return false;
5916 }
5917
5918 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
5919 return StmtVisitorTy::Visit(EvalExpr);
5920 }
5921
Peter Collingbournee9200682011-05-13 03:29:01 +00005922protected:
5923 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005924 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00005925 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
5926
Richard Smith92b1ce02011-12-12 09:28:41 +00005927 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005928 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005929 }
5930
Aaron Ballman68af21c2014-01-03 19:26:43 +00005931 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005932
5933public:
5934 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
5935
5936 EvalInfo &getEvalInfo() { return Info; }
5937
Richard Smithf57d8cb2011-12-09 22:58:01 +00005938 /// Report an evaluation error. This should only be called when an error is
5939 /// first discovered. When propagating an error, just return false.
5940 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005941 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005942 return false;
5943 }
5944 bool Error(const Expr *E) {
5945 return Error(E, diag::note_invalid_subexpr_in_const_expr);
5946 }
5947
Aaron Ballman68af21c2014-01-03 19:26:43 +00005948 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00005949 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00005950 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005951 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005952 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005953 }
5954
Bill Wendling8003edc2018-11-09 00:41:36 +00005955 bool VisitConstantExpr(const ConstantExpr *E)
5956 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005957 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005958 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005959 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005960 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005961 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005962 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005963 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00005964 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005965 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005966 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005967 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00005968 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005969 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
5970 TempVersionRAII RAII(*Info.CurrentCall);
Eric Fiselier708afb52019-05-16 21:04:15 +00005971 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005972 return StmtVisitorTy::Visit(E->getExpr());
5973 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005974 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005975 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00005976 // The initializer may not have been parsed yet, or might be erroneous.
5977 if (!E->getExpr())
5978 return Error(E);
Eric Fiselier708afb52019-05-16 21:04:15 +00005979 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Richard Smith17e32462013-09-13 20:51:45 +00005980 return StmtVisitorTy::Visit(E->getExpr());
5981 }
Eric Fiselier708afb52019-05-16 21:04:15 +00005982
Richard Smith5894a912011-12-19 22:12:41 +00005983 // We cannot create any objects for which cleanups are required, so there is
5984 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00005985 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00005986 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005987
Aaron Ballman68af21c2014-01-03 19:26:43 +00005988 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005989 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
5990 return static_cast<Derived*>(this)->VisitCastExpr(E);
5991 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005992 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00005993 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
5994 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005995 return static_cast<Derived*>(this)->VisitCastExpr(E);
5996 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005997 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
5998 return static_cast<Derived*>(this)->VisitCastExpr(E);
5999 }
Richard Smith6d6ecc32011-12-12 12:46:16 +00006000
Aaron Ballman68af21c2014-01-03 19:26:43 +00006001 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006002 switch (E->getOpcode()) {
6003 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006004 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006005
6006 case BO_Comma:
6007 VisitIgnoredValue(E->getLHS());
6008 return StmtVisitorTy::Visit(E->getRHS());
6009
6010 case BO_PtrMemD:
6011 case BO_PtrMemI: {
6012 LValue Obj;
6013 if (!HandleMemberPointerAccess(Info, E, Obj))
6014 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006015 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00006016 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00006017 return false;
6018 return DerivedSuccess(Result, E);
6019 }
6020 }
6021 }
6022
Aaron Ballman68af21c2014-01-03 19:26:43 +00006023 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00006024 // Evaluate and cache the common expression. We treat it as a temporary,
6025 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00006026 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00006027 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006028 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00006029
Richard Smith17100ba2012-02-16 02:46:34 +00006030 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006031 }
6032
Aaron Ballman68af21c2014-01-03 19:26:43 +00006033 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006034 bool IsBcpCall = false;
6035 // If the condition (ignoring parens) is a __builtin_constant_p call,
6036 // the result is a constant expression if it can be folded without
6037 // side-effects. This is an important GNU extension. See GCC PR38377
6038 // for discussion.
6039 if (const CallExpr *CallCE =
6040 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00006041 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00006042 IsBcpCall = true;
6043
6044 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6045 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00006046 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00006047 return false;
6048
Richard Smith6d4c6582013-11-05 22:18:15 +00006049 FoldConstant Fold(Info, IsBcpCall);
6050 if (!HandleConditionalOperator(E)) {
6051 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00006052 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00006053 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00006054
6055 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00006056 }
6057
Aaron Ballman68af21c2014-01-03 19:26:43 +00006058 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006059 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00006060 return DerivedSuccess(*Value, E);
6061
6062 const Expr *Source = E->getSourceExpr();
6063 if (!Source)
6064 return Error(E);
6065 if (Source == E) { // sanity checking.
6066 assert(0 && "OpaqueValueExpr recursively refers to itself");
6067 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00006068 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00006069 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00006070 }
Richard Smith4ce706a2011-10-11 21:43:33 +00006071
Aaron Ballman68af21c2014-01-03 19:26:43 +00006072 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006073 APValue Result;
6074 if (!handleCallExpr(E, Result, nullptr))
6075 return false;
6076 return DerivedSuccess(Result, E);
6077 }
6078
6079 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00006080 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00006081 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00006082 QualType CalleeType = Callee->getType();
6083
Craig Topper36250ad2014-05-12 05:36:57 +00006084 const FunctionDecl *FD = nullptr;
6085 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00006086 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith921f1322019-05-13 23:35:21 +00006087 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00006088
Richard Smithe97cbd72011-11-11 04:05:33 +00006089 // Extract function decl and 'this' pointer from the callee.
6090 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smith921f1322019-05-13 23:35:21 +00006091 const CXXMethodDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00006092 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6093 // Explicit bound member calls, such as x.f() or p->g();
6094 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006095 return false;
Richard Smith921f1322019-05-13 23:35:21 +00006096 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6097 if (!Member)
6098 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006099 This = &ThisVal;
Richard Smith921f1322019-05-13 23:35:21 +00006100 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00006101 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6102 // Indirect bound member calls ('.*' or '->*').
Richard Smith921f1322019-05-13 23:35:21 +00006103 Member = dyn_cast_or_null<CXXMethodDecl>(
6104 HandleMemberPointerAccess(Info, BE, ThisVal, false));
6105 if (!Member)
6106 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006107 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00006108 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006109 return Error(Callee);
Richard Smith921f1322019-05-13 23:35:21 +00006110 FD = Member;
Richard Smithe97cbd72011-11-11 04:05:33 +00006111 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00006112 LValue Call;
6113 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006114 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00006115
Richard Smitha8105bc2012-01-06 16:39:00 +00006116 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006117 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00006118 FD = dyn_cast_or_null<FunctionDecl>(
6119 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00006120 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006121 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00006122 // Don't call function pointers which have been cast to some other type.
6123 // Per DR (no number yet), the caller and callee can differ in noexcept.
6124 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6125 CalleeType->getPointeeType(), FD->getType())) {
6126 return Error(E);
6127 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006128
6129 // Overloaded operator calls to member functions are represented as normal
6130 // calls with '*this' as the first argument.
6131 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6132 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006133 // FIXME: When selecting an implicit conversion for an overloaded
6134 // operator delete, we sometimes try to evaluate calls to conversion
6135 // operators without a 'this' parameter!
6136 if (Args.empty())
6137 return Error(E);
6138
Nick Lewycky13073a62017-06-12 21:15:44 +00006139 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00006140 return false;
6141 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00006142 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00006143 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00006144 // Map the static invoker for the lambda back to the call operator.
6145 // Conveniently, we don't have to slice out the 'this' argument (as is
6146 // being done for the non-static case), since a static member function
6147 // doesn't have an implicit argument passed in.
6148 const CXXRecordDecl *ClosureClass = MD->getParent();
6149 assert(
6150 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6151 "Number of captures must be zero for conversion to function-ptr");
6152
6153 const CXXMethodDecl *LambdaCallOp =
6154 ClosureClass->getLambdaCallOperator();
6155
6156 // Set 'FD', the function that will be called below, to the call
6157 // operator. If the closure object represents a generic lambda, find
6158 // the corresponding specialization of the call operator.
6159
6160 if (ClosureClass->isGenericLambda()) {
6161 assert(MD->isFunctionTemplateSpecialization() &&
6162 "A generic lambda's static-invoker function must be a "
6163 "template specialization");
6164 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6165 FunctionTemplateDecl *CallOpTemplate =
6166 LambdaCallOp->getDescribedFunctionTemplate();
6167 void *InsertPos = nullptr;
6168 FunctionDecl *CorrespondingCallOpSpecialization =
6169 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6170 assert(CorrespondingCallOpSpecialization &&
6171 "We must always have a function call operator specialization "
6172 "that corresponds to our static invoker specialization");
6173 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6174 } else
6175 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00006176 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006177 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006178 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00006179
Richard Smith921f1322019-05-13 23:35:21 +00006180 SmallVector<QualType, 4> CovariantAdjustmentPath;
6181 if (This) {
6182 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006183 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
6184 // Perform virtual dispatch, if necessary.
6185 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6186 CovariantAdjustmentPath);
6187 if (!FD)
6188 return false;
6189 } else {
6190 // Check that the 'this' pointer points to an object of the right type.
6191 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
6192 return false;
6193 }
Richard Smith921f1322019-05-13 23:35:21 +00006194 }
Richard Smith47b34932012-02-01 02:39:43 +00006195
Craig Topper36250ad2014-05-12 05:36:57 +00006196 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00006197 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00006198
Nick Lewycky13073a62017-06-12 21:15:44 +00006199 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
6200 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00006201 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006202 return false;
6203
Richard Smith921f1322019-05-13 23:35:21 +00006204 if (!CovariantAdjustmentPath.empty() &&
6205 !HandleCovariantReturnAdjustment(Info, E, Result,
6206 CovariantAdjustmentPath))
6207 return false;
6208
Richard Smith52a980a2015-08-28 02:43:42 +00006209 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00006210 }
6211
Aaron Ballman68af21c2014-01-03 19:26:43 +00006212 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006213 return StmtVisitorTy::Visit(E->getInitializer());
6214 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006215 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00006216 if (E->getNumInits() == 0)
6217 return DerivedZeroInitialization(E);
6218 if (E->getNumInits() == 1)
6219 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00006220 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006221 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006222 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006223 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006224 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006225 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006226 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006227 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006228 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006229 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006230 }
Richard Smith4ce706a2011-10-11 21:43:33 +00006231
Richard Smithd62306a2011-11-10 06:34:14 +00006232 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00006233 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006234 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
6235 "missing temporary materialization conversion");
Richard Smithd62306a2011-11-10 06:34:14 +00006236 assert(!E->isArrow() && "missing call to bound member function?");
6237
Richard Smith2e312c82012-03-03 22:46:17 +00006238 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00006239 if (!Evaluate(Val, Info, E->getBase()))
6240 return false;
6241
6242 QualType BaseTy = E->getBase()->getType();
6243
6244 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00006245 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006246 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00006247 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00006248 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6249
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006250 // Note: there is no lvalue base here. But this case should only ever
6251 // happen in C or in C++98, where we cannot be evaluating a constexpr
6252 // constructor, which is the only case the base matters.
Richard Smithdebad642019-05-12 09:39:08 +00006253 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00006254 SubobjectDesignator Designator(BaseTy);
6255 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00006256
Richard Smith3229b742013-05-05 21:17:10 +00006257 APValue Result;
6258 return extractSubobject(Info, E, Obj, Designator, Result) &&
6259 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00006260 }
6261
Aaron Ballman68af21c2014-01-03 19:26:43 +00006262 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006263 switch (E->getCastKind()) {
6264 default:
6265 break;
6266
Richard Smitha23ab512013-05-23 00:30:41 +00006267 case CK_AtomicToNonAtomic: {
6268 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00006269 // This does not need to be done in place even for class/array types:
6270 // atomic-to-non-atomic conversion implies copying the object
6271 // representation.
6272 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00006273 return false;
6274 return DerivedSuccess(AtomicVal, E);
6275 }
6276
Richard Smith11562c52011-10-28 17:51:58 +00006277 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00006278 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00006279 return StmtVisitorTy::Visit(E->getSubExpr());
6280
6281 case CK_LValueToRValue: {
6282 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006283 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
6284 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006285 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00006286 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00006287 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00006288 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006289 return false;
6290 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00006291 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006292 case CK_LValueToRValueBitCast: {
6293 APValue DestValue, SourceValue;
6294 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
6295 return false;
6296 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
6297 return false;
6298 return DerivedSuccess(DestValue, E);
6299 }
Richard Smith11562c52011-10-28 17:51:58 +00006300 }
6301
Richard Smithf57d8cb2011-12-09 22:58:01 +00006302 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00006303 }
6304
Aaron Ballman68af21c2014-01-03 19:26:43 +00006305 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00006306 return VisitUnaryPostIncDec(UO);
6307 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006308 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00006309 return VisitUnaryPostIncDec(UO);
6310 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006311 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006312 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006313 return Error(UO);
6314
6315 LValue LVal;
6316 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
6317 return false;
6318 APValue RVal;
6319 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
6320 UO->isIncrementOp(), &RVal))
6321 return false;
6322 return DerivedSuccess(RVal, UO);
6323 }
6324
Aaron Ballman68af21c2014-01-03 19:26:43 +00006325 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00006326 // We will have checked the full-expressions inside the statement expression
6327 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00006328 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00006329 return Error(E);
6330
Richard Smith08d6a2c2013-07-24 07:11:57 +00006331 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00006332 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00006333 if (CS->body_empty())
6334 return true;
6335
Richard Smith51f03172013-06-20 03:00:05 +00006336 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
6337 BE = CS->body_end();
6338 /**/; ++BI) {
6339 if (BI + 1 == BE) {
6340 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
6341 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006342 Info.FFDiag((*BI)->getBeginLoc(),
6343 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00006344 return false;
6345 }
6346 return this->Visit(FinalExpr);
6347 }
6348
6349 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00006350 StmtResult Result = { ReturnValue, nullptr };
6351 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00006352 if (ESR != ESR_Succeeded) {
6353 // FIXME: If the statement-expression terminated due to 'return',
6354 // 'break', or 'continue', it would be nice to propagate that to
6355 // the outer statement evaluation rather than bailing out.
6356 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006357 Info.FFDiag((*BI)->getBeginLoc(),
6358 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00006359 return false;
6360 }
6361 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00006362
6363 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00006364 }
6365
Richard Smith4a678122011-10-24 18:44:57 +00006366 /// Visit a value which is evaluated, but whose value is ignored.
6367 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00006368 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00006369 }
David Majnemere9807b22016-02-26 04:23:19 +00006370
6371 /// Potentially visit a MemberExpr's base expression.
6372 void VisitIgnoredBaseExpression(const Expr *E) {
6373 // While MSVC doesn't evaluate the base expression, it does diagnose the
6374 // presence of side-effecting behavior.
6375 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
6376 return;
6377 VisitIgnoredValue(E);
6378 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006379};
6380
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006381} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00006382
6383//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006384// Common base class for lvalue and temporary evaluation.
6385//===----------------------------------------------------------------------===//
6386namespace {
6387template<class Derived>
6388class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00006389 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00006390protected:
6391 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006392 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00006393 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00006394 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00006395
6396 bool Success(APValue::LValueBase B) {
6397 Result.set(B);
6398 return true;
6399 }
6400
George Burgess IVf9013bf2017-02-10 22:52:29 +00006401 bool evaluatePointer(const Expr *E, LValue &Result) {
6402 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
6403 }
6404
Richard Smith027bf112011-11-17 22:56:20 +00006405public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006406 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
6407 : ExprEvaluatorBaseTy(Info), Result(Result),
6408 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00006409
Richard Smith2e312c82012-03-03 22:46:17 +00006410 bool Success(const APValue &V, const Expr *E) {
6411 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00006412 return true;
6413 }
Richard Smith027bf112011-11-17 22:56:20 +00006414
Richard Smith027bf112011-11-17 22:56:20 +00006415 bool VisitMemberExpr(const MemberExpr *E) {
6416 // Handle non-static data members.
6417 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006418 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00006419 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006420 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00006421 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00006422 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006423 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00006424 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00006425 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00006426 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00006427 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00006428 BaseTy = E->getBase()->getType();
6429 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00006430 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006431 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006432 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00006433 Result.setInvalid(E);
6434 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006435 }
Richard Smith027bf112011-11-17 22:56:20 +00006436
Richard Smith1b78b3d2012-01-25 22:15:11 +00006437 const ValueDecl *MD = E->getMemberDecl();
6438 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
6439 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6440 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6441 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00006442 if (!HandleLValueMember(this->Info, E, Result, FD))
6443 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00006444 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00006445 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
6446 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00006447 } else
6448 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006449
Richard Smith1b78b3d2012-01-25 22:15:11 +00006450 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00006451 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00006452 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00006453 RefValue))
6454 return false;
6455 return Success(RefValue, E);
6456 }
6457 return true;
6458 }
6459
6460 bool VisitBinaryOperator(const BinaryOperator *E) {
6461 switch (E->getOpcode()) {
6462 default:
6463 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6464
6465 case BO_PtrMemD:
6466 case BO_PtrMemI:
6467 return HandleMemberPointerAccess(this->Info, E, Result);
6468 }
6469 }
6470
6471 bool VisitCastExpr(const CastExpr *E) {
6472 switch (E->getCastKind()) {
6473 default:
6474 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6475
6476 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00006477 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00006478 if (!this->Visit(E->getSubExpr()))
6479 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006480
6481 // Now figure out the necessary offset to add to the base LV to get from
6482 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00006483 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
6484 Result);
Richard Smith027bf112011-11-17 22:56:20 +00006485 }
6486 }
6487};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006488}
Richard Smith027bf112011-11-17 22:56:20 +00006489
6490//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00006491// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006492//
6493// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
6494// function designators (in C), decl references to void objects (in C), and
6495// temporaries (if building with -Wno-address-of-temporary).
6496//
6497// LValue evaluation produces values comprising a base expression of one of the
6498// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00006499// - Declarations
6500// * VarDecl
6501// * FunctionDecl
6502// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00006503// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00006504// * StringLiteral
6505// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00006506// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00006507// * ObjCEncodeExpr
6508// * AddrLabelExpr
6509// * BlockExpr
6510// * CallExpr for a MakeStringConstant builtin
Richard Smithee0ce3022019-05-17 07:06:46 +00006511// - typeid(T) expressions, as TypeInfoLValues
Richard Smithce40ad62011-11-12 22:28:03 +00006512// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00006513// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00006514// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00006515// was evaluated, for cases where the MaterializeTemporaryExpr is missing
6516// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00006517// * A MaterializeTemporaryExpr that has static storage duration, with no
6518// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00006519// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00006520//===----------------------------------------------------------------------===//
6521namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006522class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00006523 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00006524public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006525 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
6526 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00006527
Richard Smith11562c52011-10-28 17:51:58 +00006528 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00006529 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00006530
Peter Collingbournee9200682011-05-13 03:29:01 +00006531 bool VisitDeclRefExpr(const DeclRefExpr *E);
6532 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006533 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006534 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
6535 bool VisitMemberExpr(const MemberExpr *E);
6536 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
6537 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00006538 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00006539 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006540 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
6541 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00006542 bool VisitUnaryReal(const UnaryOperator *E);
6543 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00006544 bool VisitUnaryPreInc(const UnaryOperator *UO) {
6545 return VisitUnaryPreIncDec(UO);
6546 }
6547 bool VisitUnaryPreDec(const UnaryOperator *UO) {
6548 return VisitUnaryPreIncDec(UO);
6549 }
Richard Smith3229b742013-05-05 21:17:10 +00006550 bool VisitBinAssign(const BinaryOperator *BO);
6551 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00006552
Peter Collingbournee9200682011-05-13 03:29:01 +00006553 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00006554 switch (E->getCastKind()) {
6555 default:
Richard Smith027bf112011-11-17 22:56:20 +00006556 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00006557
Eli Friedmance3e02a2011-10-11 00:13:24 +00006558 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00006559 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00006560 if (!Visit(E->getSubExpr()))
6561 return false;
6562 Result.Designator.setInvalid();
6563 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00006564
Richard Smith027bf112011-11-17 22:56:20 +00006565 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00006566 if (!Visit(E->getSubExpr()))
6567 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006568 return HandleBaseToDerivedCast(Info, E, Result);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006569
6570 case CK_Dynamic:
6571 if (!Visit(E->getSubExpr()))
6572 return false;
6573 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00006574 }
6575 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006576};
6577} // end anonymous namespace
6578
Richard Smith11562c52011-10-28 17:51:58 +00006579/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00006580/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00006581/// * function designators in C, and
6582/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00006583/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00006584static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
6585 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00006586 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00006587 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00006588 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006589}
6590
Peter Collingbournee9200682011-05-13 03:29:01 +00006591bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00006592 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00006593 return Success(FD);
6594 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00006595 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00006596 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00006597 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00006598 return Error(E);
6599}
Richard Smith733237d2011-10-24 23:14:33 +00006600
Faisal Vali0528a312016-11-13 06:09:16 +00006601
Richard Smith11562c52011-10-28 17:51:58 +00006602bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00006603
6604 // If we are within a lambda's call operator, check whether the 'VD' referred
6605 // to within 'E' actually represents a lambda-capture that maps to a
6606 // data-member/field within the closure object, and if so, evaluate to the
6607 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00006608 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
6609 isa<DeclRefExpr>(E) &&
6610 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
6611 // We don't always have a complete capture-map when checking or inferring if
6612 // the function call operator meets the requirements of a constexpr function
6613 // - but we don't need to evaluate the captures to determine constexprness
6614 // (dcl.constexpr C++17).
6615 if (Info.checkingPotentialConstantExpression())
6616 return false;
6617
Faisal Vali051e3a22017-02-16 04:12:21 +00006618 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00006619 // Start with 'Result' referring to the complete closure object...
6620 Result = *Info.CurrentCall->This;
6621 // ... then update it to refer to the field of the closure object
6622 // that represents the capture.
6623 if (!HandleLValueMember(Info, E, Result, FD))
6624 return false;
6625 // And if the field is of reference type, update 'Result' to refer to what
6626 // the field refers to.
6627 if (FD->getType()->isReferenceType()) {
6628 APValue RVal;
6629 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
6630 RVal))
6631 return false;
6632 Result.setFrom(Info.Ctx, RVal);
6633 }
6634 return true;
6635 }
6636 }
Craig Topper36250ad2014-05-12 05:36:57 +00006637 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00006638 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
6639 // Only if a local variable was declared in the function currently being
6640 // evaluated, do we expect to be able to find its value in the current
6641 // frame. (Otherwise it was likely declared in an enclosing context and
6642 // could either have a valid evaluatable value (for e.g. a constexpr
6643 // variable) or be ill-formed (and trigger an appropriate evaluation
6644 // diagnostic)).
6645 if (Info.CurrentCall->Callee &&
6646 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
6647 Frame = Info.CurrentCall;
6648 }
6649 }
Richard Smith3229b742013-05-05 21:17:10 +00006650
Richard Smithfec09922011-11-01 16:57:24 +00006651 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00006652 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006653 Result.set({VD, Frame->Index,
6654 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00006655 return true;
6656 }
Richard Smithce40ad62011-11-12 22:28:03 +00006657 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00006658 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00006659
Richard Smith3229b742013-05-05 21:17:10 +00006660 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006661 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006662 return false;
Richard Smithe637cbe2019-05-21 23:15:18 +00006663 if (!V->hasValue()) {
6664 // FIXME: Is it possible for V to be indeterminate here? If so, we should
6665 // adjust the diagnostic to say that.
Richard Smith6d4c6582013-11-05 22:18:15 +00006666 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00006667 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006668 return false;
6669 }
Richard Smith3229b742013-05-05 21:17:10 +00006670 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00006671}
6672
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006673bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
6674 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00006675 // Walk through the expression to find the materialized temporary itself.
6676 SmallVector<const Expr *, 2> CommaLHSs;
6677 SmallVector<SubobjectAdjustment, 2> Adjustments;
6678 const Expr *Inner = E->GetTemporaryExpr()->
6679 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00006680
Richard Smith84401042013-06-03 05:03:02 +00006681 // If we passed any comma operators, evaluate their LHSs.
6682 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
6683 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
6684 return false;
6685
Richard Smithe6c01442013-06-05 00:46:14 +00006686 // A materialized temporary with static storage duration can appear within the
6687 // result of a constant expression evaluation, so we need to preserve its
6688 // value for use outside this evaluation.
6689 APValue *Value;
6690 if (E->getStorageDuration() == SD_Static) {
6691 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00006692 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00006693 Result.set(E);
6694 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006695 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
6696 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00006697 }
6698
Richard Smithea4ad5d2013-06-06 08:19:16 +00006699 QualType Type = Inner->getType();
6700
Richard Smith84401042013-06-03 05:03:02 +00006701 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00006702 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
6703 (E->getStorageDuration() == SD_Static &&
6704 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
6705 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00006706 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00006707 }
Richard Smith84401042013-06-03 05:03:02 +00006708
6709 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00006710 for (unsigned I = Adjustments.size(); I != 0; /**/) {
6711 --I;
6712 switch (Adjustments[I].Kind) {
6713 case SubobjectAdjustment::DerivedToBaseAdjustment:
6714 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6715 Type, Result))
6716 return false;
6717 Type = Adjustments[I].DerivedToBase.BasePath->getType();
6718 break;
6719
6720 case SubobjectAdjustment::FieldAdjustment:
6721 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6722 return false;
6723 Type = Adjustments[I].Field->getType();
6724 break;
6725
6726 case SubobjectAdjustment::MemberPointerAdjustment:
6727 if (!HandleMemberPointerAccess(this->Info, Type, Result,
6728 Adjustments[I].Ptr.RHS))
6729 return false;
6730 Type = Adjustments[I].Ptr.MPT->getPointeeType();
6731 break;
6732 }
6733 }
6734
6735 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006736}
6737
Peter Collingbournee9200682011-05-13 03:29:01 +00006738bool
6739LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00006740 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6741 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00006742 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6743 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00006744 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006745}
6746
Richard Smith6e525142011-12-27 12:18:28 +00006747bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smitha9330302019-05-17 19:19:28 +00006748 TypeInfoLValue TypeInfo;
6749
Richard Smithee0ce3022019-05-17 07:06:46 +00006750 if (!E->isPotentiallyEvaluated()) {
Richard Smithee0ce3022019-05-17 07:06:46 +00006751 if (E->isTypeOperand())
6752 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6753 else
6754 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
Richard Smitha9330302019-05-17 19:19:28 +00006755 } else {
6756 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
6757 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
6758 << E->getExprOperand()->getType()
6759 << E->getExprOperand()->getSourceRange();
6760 }
6761
6762 if (!Visit(E->getExprOperand()))
6763 return false;
6764
6765 Optional<DynamicType> DynType =
6766 ComputeDynamicType(Info, E, Result, AK_TypeId);
6767 if (!DynType)
6768 return false;
6769
6770 TypeInfo =
6771 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
Richard Smithee0ce3022019-05-17 07:06:46 +00006772 }
Richard Smith6f3d4352012-10-17 23:52:07 +00006773
Richard Smitha9330302019-05-17 19:19:28 +00006774 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
Richard Smith6e525142011-12-27 12:18:28 +00006775}
6776
Francois Pichet0066db92012-04-16 04:08:35 +00006777bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
6778 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00006779}
Francois Pichet0066db92012-04-16 04:08:35 +00006780
Peter Collingbournee9200682011-05-13 03:29:01 +00006781bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006782 // Handle static data members.
6783 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006784 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00006785 return VisitVarDecl(E, VD);
6786 }
6787
Richard Smith254a73d2011-10-28 22:34:42 +00006788 // Handle static member functions.
6789 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
6790 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00006791 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00006792 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00006793 }
6794 }
6795
Richard Smithd62306a2011-11-10 06:34:14 +00006796 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00006797 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006798}
6799
Peter Collingbournee9200682011-05-13 03:29:01 +00006800bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006801 // FIXME: Deal with vectors as array subscript bases.
6802 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006803 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00006804
Nick Lewyckyad888682017-04-27 07:27:36 +00006805 bool Success = true;
6806 if (!evaluatePointer(E->getBase(), Result)) {
6807 if (!Info.noteFailure())
6808 return false;
6809 Success = false;
6810 }
Mike Stump11289f42009-09-09 15:08:12 +00006811
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006812 APSInt Index;
6813 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00006814 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006815
Nick Lewyckyad888682017-04-27 07:27:36 +00006816 return Success &&
6817 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006818}
Eli Friedman9a156e52008-11-12 09:44:48 +00006819
Peter Collingbournee9200682011-05-13 03:29:01 +00006820bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006821 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00006822}
6823
Richard Smith66c96992012-02-18 22:04:06 +00006824bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6825 if (!Visit(E->getSubExpr()))
6826 return false;
6827 // __real is a no-op on scalar lvalues.
6828 if (E->getSubExpr()->getType()->isAnyComplexType())
6829 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
6830 return true;
6831}
6832
6833bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6834 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
6835 "lvalue __imag__ on scalar?");
6836 if (!Visit(E->getSubExpr()))
6837 return false;
6838 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
6839 return true;
6840}
6841
Richard Smith243ef902013-05-05 23:31:59 +00006842bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006843 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00006844 return Error(UO);
6845
6846 if (!this->Visit(UO->getSubExpr()))
6847 return false;
6848
Richard Smith243ef902013-05-05 23:31:59 +00006849 return handleIncDec(
6850 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00006851 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00006852}
6853
6854bool LValueExprEvaluator::VisitCompoundAssignOperator(
6855 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006856 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00006857 return Error(CAO);
6858
Richard Smith3229b742013-05-05 21:17:10 +00006859 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00006860
6861 // The overall lvalue result is the result of evaluating the LHS.
6862 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00006863 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006864 Evaluate(RHS, this->Info, CAO->getRHS());
6865 return false;
6866 }
6867
Richard Smith3229b742013-05-05 21:17:10 +00006868 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
6869 return false;
6870
Richard Smith43e77732013-05-07 04:50:00 +00006871 return handleCompoundAssignment(
6872 this->Info, CAO,
6873 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
6874 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00006875}
6876
6877bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006878 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006879 return Error(E);
6880
Richard Smith3229b742013-05-05 21:17:10 +00006881 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00006882
6883 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00006884 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006885 Evaluate(NewVal, this->Info, E->getRHS());
6886 return false;
6887 }
6888
Richard Smith3229b742013-05-05 21:17:10 +00006889 if (!Evaluate(NewVal, this->Info, E->getRHS()))
6890 return false;
Richard Smith243ef902013-05-05 23:31:59 +00006891
Richard Smith31c69a32019-05-21 23:15:20 +00006892 if (Info.getLangOpts().CPlusPlus2a &&
6893 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
6894 return false;
6895
Richard Smith243ef902013-05-05 23:31:59 +00006896 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00006897 NewVal);
6898}
6899
Eli Friedman9a156e52008-11-12 09:44:48 +00006900//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006901// Pointer Evaluation
6902//===----------------------------------------------------------------------===//
6903
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006904/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00006905/// returned by a function with the alloc_size attribute. Returns true if we
6906/// were successful. Places an unsigned number into `Result`.
6907///
6908/// This expects the given CallExpr to be a call to a function with an
6909/// alloc_size attribute.
6910static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6911 const CallExpr *Call,
6912 llvm::APInt &Result) {
6913 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
6914
Joel E. Denny81508102018-03-13 14:51:22 +00006915 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
6916 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00006917 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
6918 if (Call->getNumArgs() <= SizeArgNo)
6919 return false;
6920
6921 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00006922 Expr::EvalResult ExprResult;
6923 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00006924 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006925 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00006926 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
6927 return false;
6928 Into = Into.zextOrSelf(BitsInSizeT);
6929 return true;
6930 };
6931
6932 APSInt SizeOfElem;
6933 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
6934 return false;
6935
Joel E. Denny81508102018-03-13 14:51:22 +00006936 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00006937 Result = std::move(SizeOfElem);
6938 return true;
6939 }
6940
6941 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00006942 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00006943 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
6944 return false;
6945
6946 bool Overflow;
6947 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
6948 if (Overflow)
6949 return false;
6950
6951 Result = std::move(BytesAvailable);
6952 return true;
6953}
6954
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006955/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00006956/// function.
6957static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6958 const LValue &LVal,
6959 llvm::APInt &Result) {
6960 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
6961 "Can't get the size of a non alloc_size function");
6962 const auto *Base = LVal.getLValueBase().get<const Expr *>();
6963 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
6964 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
6965}
6966
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006967/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00006968/// a function with the alloc_size attribute. If it was possible to do so, this
6969/// function will return true, make Result's Base point to said function call,
6970/// and mark Result's Base as invalid.
6971static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
6972 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006973 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00006974 return false;
6975
6976 // Because we do no form of static analysis, we only support const variables.
6977 //
6978 // Additionally, we can't support parameters, nor can we support static
6979 // variables (in the latter case, use-before-assign isn't UB; in the former,
6980 // we have no clue what they'll be assigned to).
6981 const auto *VD =
6982 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
6983 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
6984 return false;
6985
6986 const Expr *Init = VD->getAnyInitializer();
6987 if (!Init)
6988 return false;
6989
6990 const Expr *E = Init->IgnoreParens();
6991 if (!tryUnwrapAllocSizeCall(E))
6992 return false;
6993
6994 // Store E instead of E unwrapped so that the type of the LValue's base is
6995 // what the user wanted.
6996 Result.setInvalid(E);
6997
6998 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006999 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00007000 return true;
7001}
7002
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007003namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007004class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007005 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00007006 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007007 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00007008
Peter Collingbournee9200682011-05-13 03:29:01 +00007009 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00007010 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00007011 return true;
7012 }
George Burgess IVe3763372016-12-22 02:50:20 +00007013
George Burgess IVf9013bf2017-02-10 22:52:29 +00007014 bool evaluateLValue(const Expr *E, LValue &Result) {
7015 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7016 }
7017
7018 bool evaluatePointer(const Expr *E, LValue &Result) {
7019 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7020 }
7021
George Burgess IVe3763372016-12-22 02:50:20 +00007022 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007023public:
Mike Stump11289f42009-09-09 15:08:12 +00007024
George Burgess IVf9013bf2017-02-10 22:52:29 +00007025 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7026 : ExprEvaluatorBaseTy(info), Result(Result),
7027 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007028
Richard Smith2e312c82012-03-03 22:46:17 +00007029 bool Success(const APValue &V, const Expr *E) {
7030 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00007031 return true;
7032 }
Richard Smithfddd3842011-12-30 21:15:51 +00007033 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00007034 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
7035 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00007036 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00007037 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007038
John McCall45d55e42010-05-07 21:00:08 +00007039 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007040 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00007041 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007042 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00007043 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00007044 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00007045 if (E->isExpressibleAsConstantInitializer())
7046 return Success(E);
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00007047 if (Info.noteFailure())
7048 EvaluateIgnoredValue(Info, E->getSubExpr());
7049 return Error(E);
7050 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007051 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00007052 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00007053 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007054 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00007055 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00007056 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00007057 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007058 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00007059 }
Richard Smithd62306a2011-11-10 06:34:14 +00007060 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00007061 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00007062 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00007063 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00007064 if (!Info.CurrentCall->This) {
7065 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00007066 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00007067 else
Faisal Valie690b7a2016-07-02 22:34:24 +00007068 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00007069 return false;
7070 }
Richard Smithd62306a2011-11-10 06:34:14 +00007071 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00007072 // If we are inside a lambda's call operator, the 'this' expression refers
7073 // to the enclosing '*this' object (either by value or reference) which is
7074 // either copied into the closure object's field that represents the '*this'
7075 // or refers to '*this'.
7076 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7077 // Update 'Result' to refer to the data member/field of the closure object
7078 // that represents the '*this' capture.
7079 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00007080 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00007081 return false;
7082 // If we captured '*this' by reference, replace the field with its referent.
7083 if (Info.CurrentCall->LambdaThisCaptureField->getType()
7084 ->isPointerType()) {
7085 APValue RVal;
7086 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7087 RVal))
7088 return false;
7089
7090 Result.setFrom(Info.Ctx, RVal);
7091 }
7092 }
Richard Smithd62306a2011-11-10 06:34:14 +00007093 return true;
7094 }
John McCallc07a0c72011-02-17 10:25:35 +00007095
Eric Fiselier708afb52019-05-16 21:04:15 +00007096 bool VisitSourceLocExpr(const SourceLocExpr *E) {
7097 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7098 APValue LValResult = E->EvaluateInContext(
7099 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7100 Result.setFrom(Info.Ctx, LValResult);
7101 return true;
7102 }
7103
Eli Friedman449fe542009-03-23 04:56:01 +00007104 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007105};
Chris Lattner05706e882008-07-11 18:11:29 +00007106} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007107
George Burgess IVf9013bf2017-02-10 22:52:29 +00007108static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7109 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00007110 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00007111 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00007112}
7113
John McCall45d55e42010-05-07 21:00:08 +00007114bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00007115 if (E->getOpcode() != BO_Add &&
7116 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00007117 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00007118
Chris Lattner05706e882008-07-11 18:11:29 +00007119 const Expr *PExp = E->getLHS();
7120 const Expr *IExp = E->getRHS();
7121 if (IExp->getType()->isPointerType())
7122 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00007123
George Burgess IVf9013bf2017-02-10 22:52:29 +00007124 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00007125 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00007126 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007127
John McCall45d55e42010-05-07 21:00:08 +00007128 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00007129 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00007130 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007131
Richard Smith96e0c102011-11-04 02:25:55 +00007132 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00007133 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007134
Ted Kremenek28831752012-08-23 20:46:57 +00007135 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00007136 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007137}
Eli Friedman9a156e52008-11-12 09:44:48 +00007138
John McCall45d55e42010-05-07 21:00:08 +00007139bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007140 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007141}
Mike Stump11289f42009-09-09 15:08:12 +00007142
Richard Smith81dfef92018-07-11 00:29:05 +00007143bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7144 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00007145
Eli Friedman847a2bc2009-12-27 05:43:15 +00007146 switch (E->getCastKind()) {
7147 default:
7148 break;
John McCalle3027922010-08-25 11:45:40 +00007149 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00007150 case CK_CPointerToObjCPointerCast:
7151 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00007152 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007153 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00007154 if (!Visit(SubExpr))
7155 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00007156 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7157 // permitted in constant expressions in C++11. Bitcasts from cv void* are
7158 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00007159 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00007160 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00007161 if (SubExpr->getType()->isVoidPointerType())
7162 CCEDiag(E, diag::note_constexpr_invalid_cast)
7163 << 3 << SubExpr->getType();
7164 else
7165 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7166 }
Yaxun Liu402804b2016-12-15 08:09:08 +00007167 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7168 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00007169 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00007170
Anders Carlsson18275092010-10-31 20:41:46 +00007171 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00007172 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007173 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00007174 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007175 if (!Result.Base && Result.Offset.isZero())
7176 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00007177
Richard Smithd62306a2011-11-10 06:34:14 +00007178 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00007179 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00007180 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7181 castAs<PointerType>()->getPointeeType(),
7182 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00007183
Richard Smith027bf112011-11-17 22:56:20 +00007184 case CK_BaseToDerived:
7185 if (!Visit(E->getSubExpr()))
7186 return false;
7187 if (!Result.Base && Result.Offset.isZero())
7188 return true;
7189 return HandleBaseToDerivedCast(Info, E, Result);
7190
Richard Smith7bd54ab2019-05-15 20:22:21 +00007191 case CK_Dynamic:
7192 if (!Visit(E->getSubExpr()))
7193 return false;
7194 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7195
Richard Smith0b0a0b62011-10-29 20:57:55 +00007196 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007197 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007198 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00007199
John McCalle3027922010-08-25 11:45:40 +00007200 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007201 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7202
Richard Smith2e312c82012-03-03 22:46:17 +00007203 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00007204 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00007205 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00007206
John McCall45d55e42010-05-07 21:00:08 +00007207 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00007208 unsigned Size = Info.Ctx.getTypeSize(E->getType());
7209 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007210 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00007211 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00007212 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00007213 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00007214 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00007215 return true;
7216 } else {
7217 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00007218 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00007219 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00007220 }
7221 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00007222
7223 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00007224 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007225 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00007226 return false;
7227 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007228 APValue &Value = createTemporary(SubExpr, false, Result,
7229 *Info.CurrentCall);
7230 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00007231 return false;
7232 }
Richard Smith96e0c102011-11-04 02:25:55 +00007233 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00007234 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
7235 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00007236 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00007237 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00007238 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00007239 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00007240 }
Richard Smithdd785442011-10-31 20:57:44 +00007241
John McCalle3027922010-08-25 11:45:40 +00007242 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007243 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00007244
7245 case CK_LValueToRValue: {
7246 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007247 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00007248 return false;
7249
7250 APValue RVal;
7251 // Note, we use the subexpression's type in order to retain cv-qualifiers.
7252 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7253 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00007254 return InvalidBaseOK &&
7255 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00007256 return Success(RVal, E);
7257 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007258 }
7259
Richard Smith11562c52011-10-28 17:51:58 +00007260 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00007261}
Chris Lattner05706e882008-07-11 18:11:29 +00007262
Richard Smith6822bd72018-10-26 19:26:45 +00007263static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
7264 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007265 // C++ [expr.alignof]p3:
7266 // When alignof is applied to a reference type, the result is the
7267 // alignment of the referenced type.
7268 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
7269 T = Ref->getPointeeType();
7270
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00007271 if (T.getQualifiers().hasUnaligned())
7272 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00007273
7274 const bool AlignOfReturnsPreferred =
7275 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
7276
7277 // __alignof is defined to return the preferred alignment.
7278 // Before 8, clang returned the preferred alignment for alignof and _Alignof
7279 // as well.
7280 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
7281 return Info.Ctx.toCharUnitsFromBits(
7282 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
7283 // alignof and _Alignof are defined to return the ABI alignment.
7284 else if (ExprKind == UETT_AlignOf)
7285 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
7286 else
7287 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00007288}
7289
Richard Smith6822bd72018-10-26 19:26:45 +00007290static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
7291 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007292 E = E->IgnoreParens();
7293
7294 // The kinds of expressions that we have special-case logic here for
7295 // should be kept up to date with the special checks for those
7296 // expressions in Sema.
7297
7298 // alignof decl is always accepted, even if it doesn't make sense: we default
7299 // to 1 in those cases.
7300 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7301 return Info.Ctx.getDeclAlign(DRE->getDecl(),
7302 /*RefAsPointee*/true);
7303
7304 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
7305 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
7306 /*RefAsPointee*/true);
7307
Richard Smith6822bd72018-10-26 19:26:45 +00007308 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007309}
7310
George Burgess IVe3763372016-12-22 02:50:20 +00007311// To be clear: this happily visits unsupported builtins. Better name welcomed.
7312bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
7313 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
7314 return true;
7315
George Burgess IVf9013bf2017-02-10 22:52:29 +00007316 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00007317 return false;
7318
7319 Result.setInvalid(E);
7320 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00007321 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00007322 return true;
7323}
7324
Peter Collingbournee9200682011-05-13 03:29:01 +00007325bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007326 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00007327 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00007328
Richard Smith6328cbd2016-11-16 00:57:23 +00007329 if (unsigned BuiltinOp = E->getBuiltinCallee())
7330 return VisitBuiltinCallExpr(E, BuiltinOp);
7331
George Burgess IVe3763372016-12-22 02:50:20 +00007332 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007333}
7334
7335bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7336 unsigned BuiltinOp) {
7337 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00007338 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007339 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007340 case Builtin::BI__builtin_assume_aligned: {
7341 // We need to be very careful here because: if the pointer does not have the
7342 // asserted alignment, then the behavior is undefined, and undefined
7343 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00007344 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00007345 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00007346
Hal Finkel0dd05d42014-10-03 17:18:37 +00007347 LValue OffsetResult(Result);
7348 APSInt Alignment;
7349 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
7350 return false;
Richard Smith642a2362017-01-30 23:30:26 +00007351 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00007352
7353 if (E->getNumArgs() > 2) {
7354 APSInt Offset;
7355 if (!EvaluateInteger(E->getArg(2), Offset, Info))
7356 return false;
7357
Richard Smith642a2362017-01-30 23:30:26 +00007358 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007359 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
7360 }
7361
7362 // If there is a base object, then it must have the correct alignment.
7363 if (OffsetResult.Base) {
7364 CharUnits BaseAlignment;
7365 if (const ValueDecl *VD =
7366 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
7367 BaseAlignment = Info.Ctx.getDeclAlign(VD);
Richard Smithee0ce3022019-05-17 07:06:46 +00007368 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
7369 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007370 } else {
Richard Smithee0ce3022019-05-17 07:06:46 +00007371 BaseAlignment = GetAlignOfType(
7372 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007373 }
7374
7375 if (BaseAlignment < Align) {
7376 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00007377 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00007378 CCEDiag(E->getArg(0),
7379 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00007380 << (unsigned)BaseAlignment.getQuantity()
7381 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007382 return false;
7383 }
7384 }
7385
7386 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007387 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007388 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007389
Richard Smith642a2362017-01-30 23:30:26 +00007390 (OffsetResult.Base
7391 ? CCEDiag(E->getArg(0),
7392 diag::note_constexpr_baa_insufficient_alignment) << 1
7393 : CCEDiag(E->getArg(0),
7394 diag::note_constexpr_baa_value_insufficient_alignment))
7395 << (int)OffsetResult.Offset.getQuantity()
7396 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007397 return false;
7398 }
7399
7400 return true;
7401 }
Eric Fiselier26187502018-12-14 21:11:28 +00007402 case Builtin::BI__builtin_launder:
7403 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00007404 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007405 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00007406 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007407 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00007408 if (Info.getLangOpts().CPlusPlus11)
7409 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7410 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007411 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00007412 else
7413 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007414 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00007415 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007416 case Builtin::BI__builtin_wcschr:
7417 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00007418 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007419 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00007420 if (!Visit(E->getArg(0)))
7421 return false;
7422 APSInt Desired;
7423 if (!EvaluateInteger(E->getArg(1), Desired, Info))
7424 return false;
7425 uint64_t MaxLength = uint64_t(-1);
7426 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007427 BuiltinOp != Builtin::BIwcschr &&
7428 BuiltinOp != Builtin::BI__builtin_strchr &&
7429 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00007430 APSInt N;
7431 if (!EvaluateInteger(E->getArg(2), N, Info))
7432 return false;
7433 MaxLength = N.getExtValue();
7434 }
Hubert Tong147b7432018-12-12 16:53:43 +00007435 // We cannot find the value if there are no candidates to match against.
7436 if (MaxLength == 0u)
7437 return ZeroInitialization(E);
7438 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
7439 Result.Designator.Invalid)
7440 return false;
7441 QualType CharTy = Result.Designator.getType(Info.Ctx);
7442 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
7443 BuiltinOp == Builtin::BI__builtin_memchr;
7444 assert(IsRawByte ||
7445 Info.Ctx.hasSameUnqualifiedType(
7446 CharTy, E->getArg(0)->getType()->getPointeeType()));
7447 // Pointers to const void may point to objects of incomplete type.
7448 if (IsRawByte && CharTy->isIncompleteType()) {
7449 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
7450 return false;
7451 }
7452 // Give up on byte-oriented matching against multibyte elements.
7453 // FIXME: We can compare the bytes in the correct order.
7454 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
7455 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007456 // Figure out what value we're actually looking for (after converting to
7457 // the corresponding unsigned type if necessary).
7458 uint64_t DesiredVal;
7459 bool StopAtNull = false;
7460 switch (BuiltinOp) {
7461 case Builtin::BIstrchr:
7462 case Builtin::BI__builtin_strchr:
7463 // strchr compares directly to the passed integer, and therefore
7464 // always fails if given an int that is not a char.
7465 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
7466 E->getArg(1)->getType(),
7467 Desired),
7468 Desired))
7469 return ZeroInitialization(E);
7470 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007471 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007472 case Builtin::BImemchr:
7473 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00007474 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007475 // memchr compares by converting both sides to unsigned char. That's also
7476 // correct for strchr if we get this far (to cope with plain char being
7477 // unsigned in the strchr case).
7478 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
7479 break;
Richard Smithe9507952016-11-12 01:39:56 +00007480
Richard Smith8110c9d2016-11-29 19:45:17 +00007481 case Builtin::BIwcschr:
7482 case Builtin::BI__builtin_wcschr:
7483 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007484 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007485 case Builtin::BIwmemchr:
7486 case Builtin::BI__builtin_wmemchr:
7487 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
7488 DesiredVal = Desired.getZExtValue();
7489 break;
7490 }
Richard Smithe9507952016-11-12 01:39:56 +00007491
7492 for (; MaxLength; --MaxLength) {
7493 APValue Char;
7494 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
7495 !Char.isInt())
7496 return false;
7497 if (Char.getInt().getZExtValue() == DesiredVal)
7498 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00007499 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00007500 break;
7501 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
7502 return false;
7503 }
7504 // Not found: return nullptr.
7505 return ZeroInitialization(E);
7506 }
7507
Richard Smith06f71b52018-08-04 00:57:17 +00007508 case Builtin::BImemcpy:
7509 case Builtin::BImemmove:
7510 case Builtin::BIwmemcpy:
7511 case Builtin::BIwmemmove:
7512 if (Info.getLangOpts().CPlusPlus11)
7513 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7514 << /*isConstexpr*/0 << /*isConstructor*/0
7515 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7516 else
7517 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7518 LLVM_FALLTHROUGH;
7519 case Builtin::BI__builtin_memcpy:
7520 case Builtin::BI__builtin_memmove:
7521 case Builtin::BI__builtin_wmemcpy:
7522 case Builtin::BI__builtin_wmemmove: {
7523 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
7524 BuiltinOp == Builtin::BIwmemmove ||
7525 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
7526 BuiltinOp == Builtin::BI__builtin_wmemmove;
7527 bool Move = BuiltinOp == Builtin::BImemmove ||
7528 BuiltinOp == Builtin::BIwmemmove ||
7529 BuiltinOp == Builtin::BI__builtin_memmove ||
7530 BuiltinOp == Builtin::BI__builtin_wmemmove;
7531
7532 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00007533 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00007534 return false;
7535 LValue Dest = Result;
7536
7537 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00007538 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00007539 return false;
7540
7541 APSInt N;
7542 if (!EvaluateInteger(E->getArg(2), N, Info))
7543 return false;
7544 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
7545
7546 // If the size is zero, we treat this as always being a valid no-op.
7547 // (Even if one of the src and dest pointers is null.)
7548 if (!N)
7549 return true;
7550
Richard Smith128719c2018-09-13 22:47:33 +00007551 // Otherwise, if either of the operands is null, we can't proceed. Don't
7552 // try to determine the type of the copied objects, because there aren't
7553 // any.
7554 if (!Src.Base || !Dest.Base) {
7555 APValue Val;
7556 (!Src.Base ? Src : Dest).moveInto(Val);
7557 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
7558 << Move << WChar << !!Src.Base
7559 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
7560 return false;
7561 }
7562 if (Src.Designator.Invalid || Dest.Designator.Invalid)
7563 return false;
7564
Richard Smith06f71b52018-08-04 00:57:17 +00007565 // We require that Src and Dest are both pointers to arrays of
7566 // trivially-copyable type. (For the wide version, the designator will be
7567 // invalid if the designated object is not a wchar_t.)
7568 QualType T = Dest.Designator.getType(Info.Ctx);
7569 QualType SrcT = Src.Designator.getType(Info.Ctx);
7570 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
7571 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
7572 return false;
7573 }
Petr Pavlued083f22018-10-04 09:25:44 +00007574 if (T->isIncompleteType()) {
7575 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
7576 return false;
7577 }
Richard Smith06f71b52018-08-04 00:57:17 +00007578 if (!T.isTriviallyCopyableType(Info.Ctx)) {
7579 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
7580 return false;
7581 }
7582
7583 // Figure out how many T's we're copying.
7584 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
7585 if (!WChar) {
7586 uint64_t Remainder;
7587 llvm::APInt OrigN = N;
7588 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
7589 if (Remainder) {
7590 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7591 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
7592 << (unsigned)TSize;
7593 return false;
7594 }
7595 }
7596
7597 // Check that the copying will remain within the arrays, just so that we
7598 // can give a more meaningful diagnostic. This implicitly also checks that
7599 // N fits into 64 bits.
7600 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
7601 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
7602 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
7603 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7604 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
7605 << N.toString(10, /*Signed*/false);
7606 return false;
7607 }
7608 uint64_t NElems = N.getZExtValue();
7609 uint64_t NBytes = NElems * TSize;
7610
7611 // Check for overlap.
7612 int Direction = 1;
7613 if (HasSameBase(Src, Dest)) {
7614 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
7615 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
7616 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
7617 // Dest is inside the source region.
7618 if (!Move) {
7619 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7620 return false;
7621 }
7622 // For memmove and friends, copy backwards.
7623 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
7624 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
7625 return false;
7626 Direction = -1;
7627 } else if (!Move && SrcOffset >= DestOffset &&
7628 SrcOffset - DestOffset < NBytes) {
7629 // Src is inside the destination region for memcpy: invalid.
7630 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7631 return false;
7632 }
7633 }
7634
7635 while (true) {
7636 APValue Val;
7637 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
7638 !handleAssignment(Info, E, Dest, T, Val))
7639 return false;
7640 // Do not iterate past the last element; if we're copying backwards, that
7641 // might take us off the start of the array.
7642 if (--NElems == 0)
7643 return true;
7644 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
7645 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
7646 return false;
7647 }
7648 }
7649
Richard Smith6cbd65d2013-07-11 02:27:57 +00007650 default:
George Burgess IVe3763372016-12-22 02:50:20 +00007651 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00007652 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007653}
Chris Lattner05706e882008-07-11 18:11:29 +00007654
7655//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00007656// Member Pointer Evaluation
7657//===----------------------------------------------------------------------===//
7658
7659namespace {
7660class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007661 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00007662 MemberPtr &Result;
7663
7664 bool Success(const ValueDecl *D) {
7665 Result = MemberPtr(D);
7666 return true;
7667 }
7668public:
7669
7670 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
7671 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7672
Richard Smith2e312c82012-03-03 22:46:17 +00007673 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007674 Result.setFrom(V);
7675 return true;
7676 }
Richard Smithfddd3842011-12-30 21:15:51 +00007677 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00007678 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00007679 }
7680
7681 bool VisitCastExpr(const CastExpr *E);
7682 bool VisitUnaryAddrOf(const UnaryOperator *E);
7683};
7684} // end anonymous namespace
7685
7686static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
7687 EvalInfo &Info) {
7688 assert(E->isRValue() && E->getType()->isMemberPointerType());
7689 return MemberPointerExprEvaluator(Info, Result).Visit(E);
7690}
7691
7692bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7693 switch (E->getCastKind()) {
7694 default:
7695 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7696
7697 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007698 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007699 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00007700
7701 case CK_BaseToDerivedMemberPointer: {
7702 if (!Visit(E->getSubExpr()))
7703 return false;
7704 if (E->path_empty())
7705 return true;
7706 // Base-to-derived member pointer casts store the path in derived-to-base
7707 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
7708 // the wrong end of the derived->base arc, so stagger the path by one class.
7709 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
7710 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
7711 PathI != PathE; ++PathI) {
7712 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7713 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7714 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007715 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007716 }
7717 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7718 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007719 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007720 return true;
7721 }
7722
7723 case CK_DerivedToBaseMemberPointer:
7724 if (!Visit(E->getSubExpr()))
7725 return false;
7726 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7727 PathE = E->path_end(); PathI != PathE; ++PathI) {
7728 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7729 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7730 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007731 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007732 }
7733 return true;
7734 }
7735}
7736
7737bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7738 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7739 // member can be formed.
7740 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7741}
7742
7743//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00007744// Record Evaluation
7745//===----------------------------------------------------------------------===//
7746
7747namespace {
7748 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007749 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007750 const LValue &This;
7751 APValue &Result;
7752 public:
7753
7754 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
7755 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
7756
Richard Smith2e312c82012-03-03 22:46:17 +00007757 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00007758 Result = V;
7759 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00007760 }
Richard Smithb8348f52016-05-12 22:16:28 +00007761 bool ZeroInitialization(const Expr *E) {
7762 return ZeroInitialization(E, E->getType());
7763 }
7764 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00007765
Richard Smith52a980a2015-08-28 02:43:42 +00007766 bool VisitCallExpr(const CallExpr *E) {
7767 return handleCallExpr(E, Result, &This);
7768 }
Richard Smithe97cbd72011-11-11 04:05:33 +00007769 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00007770 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00007771 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7772 return VisitCXXConstructExpr(E, E->getType());
7773 }
Faisal Valic72a08c2017-01-09 03:02:53 +00007774 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00007775 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00007776 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007777 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007778
7779 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00007780 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007781}
Richard Smithd62306a2011-11-10 06:34:14 +00007782
Richard Smithfddd3842011-12-30 21:15:51 +00007783/// Perform zero-initialization on an object of non-union class type.
7784/// C++11 [dcl.init]p5:
7785/// To zero-initialize an object or reference of type T means:
7786/// [...]
7787/// -- if T is a (possibly cv-qualified) non-union class type,
7788/// each non-static data member and each base-class subobject is
7789/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00007790static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
7791 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00007792 const LValue &This, APValue &Result) {
7793 assert(!RD->isUnion() && "Expected non-union class type");
7794 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
7795 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00007796 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00007797
John McCalld7bca762012-05-01 00:38:49 +00007798 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007799 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7800
7801 if (CD) {
7802 unsigned Index = 0;
7803 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00007804 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00007805 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
7806 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00007807 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
7808 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00007809 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00007810 Result.getStructBase(Index)))
7811 return false;
7812 }
7813 }
7814
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007815 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00007816 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00007817 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00007818 continue;
7819
7820 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007821 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00007822 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007823
David Blaikie2d7c57e2012-04-30 02:36:29 +00007824 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007825 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00007826 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00007827 return false;
7828 }
7829
7830 return true;
7831}
7832
Richard Smithb8348f52016-05-12 22:16:28 +00007833bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
7834 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00007835 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007836 if (RD->isUnion()) {
7837 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
7838 // object's first non-static named data member is zero-initialized
7839 RecordDecl::field_iterator I = RD->field_begin();
7840 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00007841 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00007842 return true;
7843 }
7844
7845 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00007846 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00007847 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00007848 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00007849 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007850 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00007851 }
7852
Richard Smith5d108602012-02-17 00:44:16 +00007853 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00007854 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00007855 return false;
7856 }
7857
Richard Smitha8105bc2012-01-06 16:39:00 +00007858 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00007859}
7860
Richard Smithe97cbd72011-11-11 04:05:33 +00007861bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
7862 switch (E->getCastKind()) {
7863 default:
7864 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7865
7866 case CK_ConstructorConversion:
7867 return Visit(E->getSubExpr());
7868
7869 case CK_DerivedToBase:
7870 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00007871 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007872 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00007873 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007874 if (!DerivedObject.isStruct())
7875 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00007876
7877 // Derived-to-base rvalue conversion: just slice off the derived part.
7878 APValue *Value = &DerivedObject;
7879 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
7880 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7881 PathE = E->path_end(); PathI != PathE; ++PathI) {
7882 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
7883 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7884 Value = &Value->getStructBase(getBaseIndex(RD, Base));
7885 RD = Base;
7886 }
7887 Result = *Value;
7888 return true;
7889 }
7890 }
7891}
7892
Richard Smithd62306a2011-11-10 06:34:14 +00007893bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00007894 if (E->isTransparent())
7895 return Visit(E->getInit(0));
7896
Richard Smithd62306a2011-11-10 06:34:14 +00007897 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00007898 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007899 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007900 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
7901
7902 EvalInfo::EvaluatingConstructorRAII EvalObj(
7903 Info,
7904 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7905 CXXRD && CXXRD->getNumBases());
Richard Smithd62306a2011-11-10 06:34:14 +00007906
7907 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00007908 const FieldDecl *Field = E->getInitializedFieldInUnion();
7909 Result = APValue(Field);
7910 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00007911 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00007912
7913 // If the initializer list for a union does not contain any elements, the
7914 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00007915 // FIXME: The element should be initialized from an initializer list.
7916 // Is this difference ever observable for initializer lists which
7917 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00007918 ImplicitValueInitExpr VIE(Field->getType());
7919 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
7920
Richard Smithd62306a2011-11-10 06:34:14 +00007921 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00007922 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
7923 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00007924
7925 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7926 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7927 isa<CXXDefaultInitExpr>(InitExpr));
7928
Richard Smithb228a862012-02-15 02:18:13 +00007929 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00007930 }
7931
Richard Smithe637cbe2019-05-21 23:15:18 +00007932 if (!Result.hasValue())
Richard Smithc0d04a22016-05-25 22:06:25 +00007933 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
7934 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00007935 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00007936 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00007937
7938 // Initialize base classes.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007939 if (CXXRD && CXXRD->getNumBases()) {
Richard Smith872307e2016-03-08 22:17:41 +00007940 for (const auto &Base : CXXRD->bases()) {
7941 assert(ElementNo < E->getNumInits() && "missing init for base class");
7942 const Expr *Init = E->getInit(ElementNo);
7943
7944 LValue Subobject = This;
7945 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
7946 return false;
7947
7948 APValue &FieldVal = Result.getStructBase(ElementNo);
7949 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007950 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00007951 return false;
7952 Success = false;
7953 }
7954 ++ElementNo;
7955 }
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007956
7957 EvalObj.finishedConstructingBases();
Richard Smith872307e2016-03-08 22:17:41 +00007958 }
7959
7960 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007961 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007962 // Anonymous bit-fields are not considered members of the class for
7963 // purposes of aggregate initialization.
7964 if (Field->isUnnamedBitfield())
7965 continue;
7966
7967 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00007968
Richard Smith253c2a32012-01-27 01:14:48 +00007969 bool HaveInit = ElementNo < E->getNumInits();
7970
7971 // FIXME: Diagnostics here should point to the end of the initializer
7972 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00007973 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007974 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00007975 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00007976
7977 // Perform an implicit value-initialization for members beyond the end of
7978 // the initializer list.
7979 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00007980 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00007981
Richard Smith852c9db2013-04-20 22:23:05 +00007982 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7983 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7984 isa<CXXDefaultInitExpr>(Init));
7985
Richard Smith49ca8aa2013-08-06 07:09:20 +00007986 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7987 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
7988 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007989 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00007990 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00007991 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00007992 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00007993 }
7994 }
7995
Richard Smith253c2a32012-01-27 01:14:48 +00007996 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00007997}
7998
Richard Smithb8348f52016-05-12 22:16:28 +00007999bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8000 QualType T) {
8001 // Note that E's type is not necessarily the type of our class here; we might
8002 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00008003 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00008004 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
8005
Richard Smithfddd3842011-12-30 21:15:51 +00008006 bool ZeroInit = E->requiresZeroInitialization();
8007 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00008008 // If we've already performed zero-initialization, we're already done.
Richard Smithe637cbe2019-05-21 23:15:18 +00008009 if (Result.hasValue())
Richard Smith9eae7232012-01-12 18:54:33 +00008010 return true;
8011
Richard Smithda3f4fd2014-03-05 23:32:50 +00008012 // We can get here in two different ways:
8013 // 1) We're performing value-initialization, and should zero-initialize
8014 // the object, or
8015 // 2) We're performing default-initialization of an object with a trivial
8016 // constexpr default constructor, in which case we should start the
8017 // lifetimes of all the base subobjects (there can be no data member
8018 // subobjects in this case) per [basic.life]p1.
8019 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00008020 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00008021 }
8022
Craig Topper36250ad2014-05-12 05:36:57 +00008023 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00008024 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00008025
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00008026 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00008027 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008028
Richard Smith1bc5c2c2012-01-10 04:32:03 +00008029 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00008030 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00008031 if (const MaterializeTemporaryExpr *ME
8032 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
8033 return Visit(ME->GetTemporaryExpr());
8034
Richard Smithb8348f52016-05-12 22:16:28 +00008035 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00008036 return false;
8037
Craig Topper5fc8fc22014-08-27 06:28:36 +00008038 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00008039 return HandleConstructorCall(E, This, Args,
8040 cast<CXXConstructorDecl>(Definition), Info,
8041 Result);
8042}
8043
8044bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
8045 const CXXInheritedCtorInitExpr *E) {
8046 if (!Info.CurrentCall) {
8047 assert(Info.checkingPotentialConstantExpression());
8048 return false;
8049 }
8050
8051 const CXXConstructorDecl *FD = E->getConstructor();
8052 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
8053 return false;
8054
8055 const FunctionDecl *Definition = nullptr;
8056 auto Body = FD->getBody(Definition);
8057
8058 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
8059 return false;
8060
8061 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008062 cast<CXXConstructorDecl>(Definition), Info,
8063 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00008064}
8065
Richard Smithcc1b96d2013-06-12 22:31:48 +00008066bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
8067 const CXXStdInitializerListExpr *E) {
8068 const ConstantArrayType *ArrayType =
8069 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
8070
8071 LValue Array;
8072 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
8073 return false;
8074
8075 // Get a pointer to the first element of the array.
8076 Array.addArray(Info, E, ArrayType);
8077
8078 // FIXME: Perform the checks on the field types in SemaInit.
8079 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
8080 RecordDecl::field_iterator Field = Record->field_begin();
8081 if (Field == Record->field_end())
8082 return Error(E);
8083
8084 // Start pointer.
8085 if (!Field->getType()->isPointerType() ||
8086 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8087 ArrayType->getElementType()))
8088 return Error(E);
8089
8090 // FIXME: What if the initializer_list type has base classes, etc?
8091 Result = APValue(APValue::UninitStruct(), 0, 2);
8092 Array.moveInto(Result.getStructField(0));
8093
8094 if (++Field == Record->field_end())
8095 return Error(E);
8096
8097 if (Field->getType()->isPointerType() &&
8098 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8099 ArrayType->getElementType())) {
8100 // End pointer.
8101 if (!HandleLValueArrayAdjustment(Info, E, Array,
8102 ArrayType->getElementType(),
8103 ArrayType->getSize().getZExtValue()))
8104 return false;
8105 Array.moveInto(Result.getStructField(1));
8106 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
8107 // Length.
8108 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
8109 else
8110 return Error(E);
8111
8112 if (++Field != Record->field_end())
8113 return Error(E);
8114
8115 return true;
8116}
8117
Faisal Valic72a08c2017-01-09 03:02:53 +00008118bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
8119 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
8120 if (ClosureClass->isInvalidDecl()) return false;
8121
8122 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008123
Faisal Vali051e3a22017-02-16 04:12:21 +00008124 const size_t NumFields =
8125 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00008126
8127 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
8128 E->capture_init_end()) &&
8129 "The number of lambda capture initializers should equal the number of "
8130 "fields within the closure type");
8131
Faisal Vali051e3a22017-02-16 04:12:21 +00008132 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
8133 // Iterate through all the lambda's closure object's fields and initialize
8134 // them.
8135 auto *CaptureInitIt = E->capture_init_begin();
8136 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
8137 bool Success = true;
8138 for (const auto *Field : ClosureClass->fields()) {
8139 assert(CaptureInitIt != E->capture_init_end());
8140 // Get the initializer for this field
8141 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00008142
Faisal Vali051e3a22017-02-16 04:12:21 +00008143 // If there is no initializer, either this is a VLA or an error has
8144 // occurred.
8145 if (!CurFieldInit)
8146 return Error(E);
8147
8148 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8149 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
8150 if (!Info.keepEvaluatingAfterFailure())
8151 return false;
8152 Success = false;
8153 }
8154 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00008155 }
Faisal Vali051e3a22017-02-16 04:12:21 +00008156 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00008157}
8158
Richard Smithd62306a2011-11-10 06:34:14 +00008159static bool EvaluateRecord(const Expr *E, const LValue &This,
8160 APValue &Result, EvalInfo &Info) {
8161 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00008162 "can't evaluate expression as a record rvalue");
8163 return RecordExprEvaluator(Info, This, Result).Visit(E);
8164}
8165
8166//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00008167// Temporary Evaluation
8168//
8169// Temporaries are represented in the AST as rvalues, but generally behave like
8170// lvalues. The full-object of which the temporary is a subobject is implicitly
8171// materialized so that a reference can bind to it.
8172//===----------------------------------------------------------------------===//
8173namespace {
8174class TemporaryExprEvaluator
8175 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
8176public:
8177 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00008178 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00008179
8180 /// Visit an expression which constructs the value of this temporary.
8181 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00008182 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
8183 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00008184 }
8185
8186 bool VisitCastExpr(const CastExpr *E) {
8187 switch (E->getCastKind()) {
8188 default:
8189 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8190
8191 case CK_ConstructorConversion:
8192 return VisitConstructExpr(E->getSubExpr());
8193 }
8194 }
8195 bool VisitInitListExpr(const InitListExpr *E) {
8196 return VisitConstructExpr(E);
8197 }
8198 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8199 return VisitConstructExpr(E);
8200 }
8201 bool VisitCallExpr(const CallExpr *E) {
8202 return VisitConstructExpr(E);
8203 }
Richard Smith513955c2014-12-17 19:24:30 +00008204 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
8205 return VisitConstructExpr(E);
8206 }
Faisal Valic72a08c2017-01-09 03:02:53 +00008207 bool VisitLambdaExpr(const LambdaExpr *E) {
8208 return VisitConstructExpr(E);
8209 }
Richard Smith027bf112011-11-17 22:56:20 +00008210};
8211} // end anonymous namespace
8212
8213/// Evaluate an expression of record type as a temporary.
8214static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00008215 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00008216 return TemporaryExprEvaluator(Info, Result).Visit(E);
8217}
8218
8219//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008220// Vector Evaluation
8221//===----------------------------------------------------------------------===//
8222
8223namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008224 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008225 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00008226 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008227 public:
Mike Stump11289f42009-09-09 15:08:12 +00008228
Richard Smith2d406342011-10-22 21:10:00 +00008229 VectorExprEvaluator(EvalInfo &info, APValue &Result)
8230 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00008231
Craig Topper9798b932015-09-29 04:30:05 +00008232 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008233 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
8234 // FIXME: remove this APValue copy.
8235 Result = APValue(V.data(), V.size());
8236 return true;
8237 }
Richard Smith2e312c82012-03-03 22:46:17 +00008238 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00008239 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00008240 Result = V;
8241 return true;
8242 }
Richard Smithfddd3842011-12-30 21:15:51 +00008243 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00008244
Richard Smith2d406342011-10-22 21:10:00 +00008245 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00008246 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00008247 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00008248 bool VisitInitListExpr(const InitListExpr *E);
8249 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008250 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00008251 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00008252 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008253 };
8254} // end anonymous namespace
8255
8256static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008257 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00008258 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008259}
8260
George Burgess IV533ff002015-12-11 00:23:35 +00008261bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008262 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00008263 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00008264
Richard Smith161f09a2011-12-06 22:44:34 +00008265 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00008266 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008267
Eli Friedmanc757de22011-03-25 00:43:55 +00008268 switch (E->getCastKind()) {
8269 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00008270 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00008271 if (SETy->isIntegerType()) {
8272 APSInt IntResult;
8273 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00008274 return false;
8275 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00008276 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00008277 APFloat FloatResult(0.0);
8278 if (!EvaluateFloat(SE, FloatResult, Info))
8279 return false;
8280 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00008281 } else {
Richard Smith2d406342011-10-22 21:10:00 +00008282 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008283 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00008284
8285 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00008286 SmallVector<APValue, 4> Elts(NElts, Val);
8287 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00008288 }
Eli Friedman803acb32011-12-22 03:51:45 +00008289 case CK_BitCast: {
8290 // Evaluate the operand into an APInt we can extract from.
8291 llvm::APInt SValInt;
8292 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
8293 return false;
8294 // Extract the elements
8295 QualType EltTy = VTy->getElementType();
8296 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
8297 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8298 SmallVector<APValue, 4> Elts;
8299 if (EltTy->isRealFloatingType()) {
8300 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00008301 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00008302 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00008303 FloatEltSize = 80;
8304 for (unsigned i = 0; i < NElts; i++) {
8305 llvm::APInt Elt;
8306 if (BigEndian)
8307 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
8308 else
8309 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00008310 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00008311 }
8312 } else if (EltTy->isIntegerType()) {
8313 for (unsigned i = 0; i < NElts; i++) {
8314 llvm::APInt Elt;
8315 if (BigEndian)
8316 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
8317 else
8318 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
8319 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
8320 }
8321 } else {
8322 return Error(E);
8323 }
8324 return Success(Elts, E);
8325 }
Eli Friedmanc757de22011-03-25 00:43:55 +00008326 default:
Richard Smith11562c52011-10-28 17:51:58 +00008327 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008328 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008329}
8330
Richard Smith2d406342011-10-22 21:10:00 +00008331bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008332VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008333 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008334 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00008335 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00008336
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008337 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008338 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008339
Eli Friedmanb9c71292012-01-03 23:24:20 +00008340 // The number of initializers can be less than the number of
8341 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00008342 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00008343 // should be initialized with zeroes.
8344 unsigned CountInits = 0, CountElts = 0;
8345 while (CountElts < NumElements) {
8346 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00008347 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00008348 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00008349 APValue v;
8350 if (!EvaluateVector(E->getInit(CountInits), v, Info))
8351 return Error(E);
8352 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00008353 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00008354 Elements.push_back(v.getVectorElt(j));
8355 CountElts += vlen;
8356 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008357 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00008358 if (CountInits < NumInits) {
8359 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00008360 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00008361 } else // trailing integer zero.
8362 sInt = Info.Ctx.MakeIntValue(0, EltTy);
8363 Elements.push_back(APValue(sInt));
8364 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008365 } else {
8366 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00008367 if (CountInits < NumInits) {
8368 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00008369 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00008370 } else // trailing float zero.
8371 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
8372 Elements.push_back(APValue(f));
8373 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00008374 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00008375 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008376 }
Richard Smith2d406342011-10-22 21:10:00 +00008377 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008378}
8379
Richard Smith2d406342011-10-22 21:10:00 +00008380bool
Richard Smithfddd3842011-12-30 21:15:51 +00008381VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008382 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00008383 QualType EltTy = VT->getElementType();
8384 APValue ZeroElement;
8385 if (EltTy->isIntegerType())
8386 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
8387 else
8388 ZeroElement =
8389 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
8390
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008391 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00008392 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008393}
8394
Richard Smith2d406342011-10-22 21:10:00 +00008395bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00008396 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00008397 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008398}
8399
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008400//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00008401// Array Evaluation
8402//===----------------------------------------------------------------------===//
8403
8404namespace {
8405 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008406 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00008407 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00008408 APValue &Result;
8409 public:
8410
Richard Smithd62306a2011-11-10 06:34:14 +00008411 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
8412 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00008413
8414 bool Success(const APValue &V, const Expr *E) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00008415 assert(V.isArray() && "expected array");
Richard Smithf3e9e432011-11-07 09:22:26 +00008416 Result = V;
8417 return true;
8418 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008419
Richard Smithfddd3842011-12-30 21:15:51 +00008420 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00008421 const ConstantArrayType *CAT =
8422 Info.Ctx.getAsConstantArrayType(E->getType());
8423 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008424 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00008425
8426 Result = APValue(APValue::UninitArray(), 0,
8427 CAT->getSize().getZExtValue());
8428 if (!Result.hasArrayFiller()) return true;
8429
Richard Smithfddd3842011-12-30 21:15:51 +00008430 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00008431 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00008432 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00008433 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00008434 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00008435 }
8436
Richard Smith52a980a2015-08-28 02:43:42 +00008437 bool VisitCallExpr(const CallExpr *E) {
8438 return handleCallExpr(E, Result, &This);
8439 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008440 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00008441 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00008442 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00008443 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
8444 const LValue &Subobject,
8445 APValue *Value, QualType Type);
Eli Friedman3bf72d72019-02-08 21:18:46 +00008446 bool VisitStringLiteral(const StringLiteral *E) {
8447 expandStringLiteral(Info, E, Result);
8448 return true;
8449 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008450 };
8451} // end anonymous namespace
8452
Richard Smithd62306a2011-11-10 06:34:14 +00008453static bool EvaluateArray(const Expr *E, const LValue &This,
8454 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00008455 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00008456 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00008457}
8458
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008459// Return true iff the given array filler may depend on the element index.
8460static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
8461 // For now, just whitelist non-class value-initialization and initialization
8462 // lists comprised of them.
8463 if (isa<ImplicitValueInitExpr>(FillerExpr))
8464 return false;
8465 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
8466 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
8467 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
8468 return true;
8469 }
8470 return false;
8471 }
8472 return true;
8473}
8474
Richard Smithf3e9e432011-11-07 09:22:26 +00008475bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8476 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
8477 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008478 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00008479
Richard Smithca2cfbf2011-12-22 01:07:19 +00008480 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
8481 // an appropriately-typed string literal enclosed in braces.
Eli Friedman3bf72d72019-02-08 21:18:46 +00008482 if (E->isStringLiteralInit())
8483 return Visit(E->getInit(0));
Richard Smithca2cfbf2011-12-22 01:07:19 +00008484
Richard Smith253c2a32012-01-27 01:14:48 +00008485 bool Success = true;
8486
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008487 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
8488 "zero-initialized array shouldn't have any initialized elts");
8489 APValue Filler;
8490 if (Result.isArray() && Result.hasArrayFiller())
8491 Filler = Result.getArrayFiller();
8492
Richard Smith9543c5e2013-04-22 14:44:29 +00008493 unsigned NumEltsToInit = E->getNumInits();
8494 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00008495 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00008496
8497 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008498 // array element.
8499 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00008500 NumEltsToInit = NumElts;
8501
Nicola Zaghen3538b392018-05-15 13:30:56 +00008502 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
8503 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008504
Richard Smith9543c5e2013-04-22 14:44:29 +00008505 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008506
8507 // If the array was previously zero-initialized, preserve the
8508 // zero-initialized values.
Richard Smithe637cbe2019-05-21 23:15:18 +00008509 if (Filler.hasValue()) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008510 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
8511 Result.getArrayInitializedElt(I) = Filler;
8512 if (Result.hasArrayFiller())
8513 Result.getArrayFiller() = Filler;
8514 }
8515
Richard Smithd62306a2011-11-10 06:34:14 +00008516 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00008517 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00008518 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
8519 const Expr *Init =
8520 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00008521 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00008522 Info, Subobject, Init) ||
8523 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00008524 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00008525 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00008526 return false;
8527 Success = false;
8528 }
Richard Smithd62306a2011-11-10 06:34:14 +00008529 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008530
Richard Smith9543c5e2013-04-22 14:44:29 +00008531 if (!Result.hasArrayFiller())
8532 return Success;
8533
8534 // If we get here, we have a trivial filler, which we can just evaluate
8535 // once and splat over the rest of the array elements.
8536 assert(FillerExpr && "no array filler for incomplete init list");
8537 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
8538 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00008539}
8540
Richard Smith410306b2016-12-12 02:53:20 +00008541bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
8542 if (E->getCommonExpr() &&
8543 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
8544 Info, E->getCommonExpr()->getSourceExpr()))
8545 return false;
8546
8547 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
8548
8549 uint64_t Elements = CAT->getSize().getZExtValue();
8550 Result = APValue(APValue::UninitArray(), Elements, Elements);
8551
8552 LValue Subobject = This;
8553 Subobject.addArray(Info, E, CAT);
8554
8555 bool Success = true;
8556 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
8557 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8558 Info, Subobject, E->getSubExpr()) ||
8559 !HandleLValueArrayAdjustment(Info, E, Subobject,
8560 CAT->getElementType(), 1)) {
8561 if (!Info.noteFailure())
8562 return false;
8563 Success = false;
8564 }
8565 }
8566
8567 return Success;
8568}
8569
Richard Smith027bf112011-11-17 22:56:20 +00008570bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00008571 return VisitCXXConstructExpr(E, This, &Result, E->getType());
8572}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008573
Richard Smith9543c5e2013-04-22 14:44:29 +00008574bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8575 const LValue &Subobject,
8576 APValue *Value,
8577 QualType Type) {
Richard Smithe637cbe2019-05-21 23:15:18 +00008578 bool HadZeroInit = Value->hasValue();
Richard Smith9543c5e2013-04-22 14:44:29 +00008579
8580 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
8581 unsigned N = CAT->getSize().getZExtValue();
8582
8583 // Preserve the array filler if we had prior zero-initialization.
8584 APValue Filler =
8585 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
8586 : APValue();
8587
8588 *Value = APValue(APValue::UninitArray(), N, N);
8589
8590 if (HadZeroInit)
8591 for (unsigned I = 0; I != N; ++I)
8592 Value->getArrayInitializedElt(I) = Filler;
8593
8594 // Initialize the elements.
8595 LValue ArrayElt = Subobject;
8596 ArrayElt.addArray(Info, E, CAT);
8597 for (unsigned I = 0; I != N; ++I)
8598 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
8599 CAT->getElementType()) ||
8600 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
8601 CAT->getElementType(), 1))
8602 return false;
8603
8604 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008605 }
Richard Smith027bf112011-11-17 22:56:20 +00008606
Richard Smith9543c5e2013-04-22 14:44:29 +00008607 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00008608 return Error(E);
8609
Richard Smithb8348f52016-05-12 22:16:28 +00008610 return RecordExprEvaluator(Info, Subobject, *Value)
8611 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00008612}
8613
Richard Smithf3e9e432011-11-07 09:22:26 +00008614//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00008615// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00008616//
8617// As a GNU extension, we support casting pointers to sufficiently-wide integer
8618// types and back in constant folding. Integer values are thus represented
8619// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00008620//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00008621
8622namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008623class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008624 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00008625 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00008626public:
Richard Smith2e312c82012-03-03 22:46:17 +00008627 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008628 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00008629
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008630 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008631 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008632 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008633 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008634 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008635 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008636 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008637 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008638 return true;
8639 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008640 bool Success(const llvm::APSInt &SI, const Expr *E) {
8641 return Success(SI, E, Result);
8642 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008643
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008644 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008645 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008646 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008647 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008648 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008649 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008650 Result.getInt().setIsUnsigned(
8651 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008652 return true;
8653 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008654 bool Success(const llvm::APInt &I, const Expr *E) {
8655 return Success(I, E, Result);
8656 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008657
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008658 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008659 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008660 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008661 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008662 return true;
8663 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008664 bool Success(uint64_t Value, const Expr *E) {
8665 return Success(Value, E, Result);
8666 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008667
Ken Dyckdbc01912011-03-11 02:13:43 +00008668 bool Success(CharUnits Size, const Expr *E) {
8669 return Success(Size.getQuantity(), E);
8670 }
8671
Richard Smith2e312c82012-03-03 22:46:17 +00008672 bool Success(const APValue &V, const Expr *E) {
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00008673 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00008674 Result = V;
8675 return true;
8676 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008677 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00008678 }
Mike Stump11289f42009-09-09 15:08:12 +00008679
Richard Smithfddd3842011-12-30 21:15:51 +00008680 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00008681
Peter Collingbournee9200682011-05-13 03:29:01 +00008682 //===--------------------------------------------------------------------===//
8683 // Visitor Methods
8684 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00008685
Fangrui Song407659a2018-11-30 23:41:18 +00008686 bool VisitConstantExpr(const ConstantExpr *E);
8687
Chris Lattner7174bf32008-07-12 00:38:25 +00008688 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008689 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00008690 }
8691 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008692 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00008693 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008694
8695 bool CheckReferencedDecl(const Expr *E, const Decl *D);
8696 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008697 if (CheckReferencedDecl(E, E->getDecl()))
8698 return true;
8699
8700 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008701 }
8702 bool VisitMemberExpr(const MemberExpr *E) {
8703 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00008704 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008705 return true;
8706 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008707
8708 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008709 }
8710
Peter Collingbournee9200682011-05-13 03:29:01 +00008711 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00008712 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00008713 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00008714 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00008715 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00008716
Peter Collingbournee9200682011-05-13 03:29:01 +00008717 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008718 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00008719
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008720 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008721 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008722 }
Mike Stump11289f42009-09-09 15:08:12 +00008723
Ted Kremeneke65b0862012-03-06 20:05:56 +00008724 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8725 return Success(E->getValue(), E);
8726 }
Richard Smith410306b2016-12-12 02:53:20 +00008727
8728 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8729 if (Info.ArrayInitIndex == uint64_t(-1)) {
8730 // We were asked to evaluate this subexpression independent of the
8731 // enclosing ArrayInitLoopExpr. We can't do that.
8732 Info.FFDiag(E);
8733 return false;
8734 }
8735 return Success(Info.ArrayInitIndex, E);
8736 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008737
Richard Smith4ce706a2011-10-11 21:43:33 +00008738 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00008739 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00008740 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008741 }
8742
Douglas Gregor29c42f22012-02-24 07:38:34 +00008743 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8744 return Success(E->getValue(), E);
8745 }
8746
John Wiegley6242b6a2011-04-28 00:16:57 +00008747 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
8748 return Success(E->getValue(), E);
8749 }
8750
John Wiegleyf9f65842011-04-25 06:54:41 +00008751 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
8752 return Success(E->getValue(), E);
8753 }
8754
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008755 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008756 bool VisitUnaryImag(const UnaryOperator *E);
8757
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008758 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008759 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Eric Fiselier708afb52019-05-16 21:04:15 +00008760 bool VisitSourceLocExpr(const SourceLocExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008761 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00008762};
Leonard Chandb01c3a2018-06-20 17:19:40 +00008763
8764class FixedPointExprEvaluator
8765 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
8766 APValue &Result;
8767
8768 public:
8769 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
8770 : ExprEvaluatorBaseTy(info), Result(result) {}
8771
Leonard Chandb01c3a2018-06-20 17:19:40 +00008772 bool Success(const llvm::APInt &I, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008773 return Success(
8774 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008775 }
8776
Leonard Chandb01c3a2018-06-20 17:19:40 +00008777 bool Success(uint64_t Value, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008778 return Success(
8779 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008780 }
8781
8782 bool Success(const APValue &V, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008783 return Success(V.getFixedPoint(), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008784 }
8785
Leonard Chand3f3e162019-01-18 21:04:25 +00008786 bool Success(const APFixedPoint &V, const Expr *E) {
8787 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
8788 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8789 "Invalid evaluation result.");
8790 Result = APValue(V);
8791 return true;
8792 }
Leonard Chandb01c3a2018-06-20 17:19:40 +00008793
8794 //===--------------------------------------------------------------------===//
8795 // Visitor Methods
8796 //===--------------------------------------------------------------------===//
8797
8798 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
8799 return Success(E->getValue(), E);
8800 }
8801
Leonard Chand3f3e162019-01-18 21:04:25 +00008802 bool VisitCastExpr(const CastExpr *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008803 bool VisitUnaryOperator(const UnaryOperator *E);
Leonard Chand3f3e162019-01-18 21:04:25 +00008804 bool VisitBinaryOperator(const BinaryOperator *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008805};
Chris Lattner05706e882008-07-11 18:11:29 +00008806} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008807
Richard Smith11562c52011-10-28 17:51:58 +00008808/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
8809/// produce either the integer value or a pointer.
8810///
8811/// GCC has a heinous extension which folds casts between pointer types and
8812/// pointer-sized integral types. We support this by allowing the evaluation of
8813/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
8814/// Some simple arithmetic on such values is supported (they are treated much
8815/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00008816static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00008817 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008818 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008819 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00008820}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008821
Richard Smithf57d8cb2011-12-09 22:58:01 +00008822static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00008823 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008824 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00008825 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008826 if (!Val.isInt()) {
8827 // FIXME: It would be better to produce the diagnostic for casting
8828 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00008829 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008830 return false;
8831 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008832 Result = Val.getInt();
8833 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008834}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008835
Eric Fiselier708afb52019-05-16 21:04:15 +00008836bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
8837 APValue Evaluated = E->EvaluateInContext(
8838 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8839 return Success(Evaluated, E);
8840}
8841
Leonard Chand3f3e162019-01-18 21:04:25 +00008842static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
8843 EvalInfo &Info) {
8844 if (E->getType()->isFixedPointType()) {
8845 APValue Val;
8846 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
8847 return false;
8848 if (!Val.isFixedPoint())
8849 return false;
8850
8851 Result = Val.getFixedPoint();
8852 return true;
8853 }
8854 return false;
8855}
8856
8857static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
8858 EvalInfo &Info) {
8859 if (E->getType()->isIntegerType()) {
8860 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
8861 APSInt Val;
8862 if (!EvaluateInteger(E, Val, Info))
8863 return false;
8864 Result = APFixedPoint(Val, FXSema);
8865 return true;
8866 } else if (E->getType()->isFixedPointType()) {
8867 return EvaluateFixedPoint(E, Result, Info);
8868 }
8869 return false;
8870}
8871
Richard Smithf57d8cb2011-12-09 22:58:01 +00008872/// Check whether the given declaration can be directly converted to an integral
8873/// rvalue. If not, no diagnostic is produced; there are other things we can
8874/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008875bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00008876 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00008877 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008878 // Check for signedness/width mismatches between E type and ECD value.
8879 bool SameSign = (ECD->getInitVal().isSigned()
8880 == E->getType()->isSignedIntegerOrEnumerationType());
8881 bool SameWidth = (ECD->getInitVal().getBitWidth()
8882 == Info.Ctx.getIntWidth(E->getType()));
8883 if (SameSign && SameWidth)
8884 return Success(ECD->getInitVal(), E);
8885 else {
8886 // Get rid of mismatch (otherwise Success assertions will fail)
8887 // by computing a new value matching the type of E.
8888 llvm::APSInt Val = ECD->getInitVal();
8889 if (!SameSign)
8890 Val.setIsSigned(!ECD->getInitVal().isSigned());
8891 if (!SameWidth)
8892 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
8893 return Success(Val, E);
8894 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00008895 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008896 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00008897}
8898
Richard Smith08b682b2018-05-23 21:18:00 +00008899/// Values returned by __builtin_classify_type, chosen to match the values
8900/// produced by GCC's builtin.
8901enum class GCCTypeClass {
8902 None = -1,
8903 Void = 0,
8904 Integer = 1,
8905 // GCC reserves 2 for character types, but instead classifies them as
8906 // integers.
8907 Enum = 3,
8908 Bool = 4,
8909 Pointer = 5,
8910 // GCC reserves 6 for references, but appears to never use it (because
8911 // expressions never have reference type, presumably).
8912 PointerToDataMember = 7,
8913 RealFloat = 8,
8914 Complex = 9,
8915 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
8916 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
8917 // GCC claims to reserve 11 for pointers to member functions, but *actually*
8918 // uses 12 for that purpose, same as for a class or struct. Maybe it
8919 // internally implements a pointer to member as a struct? Who knows.
8920 PointerToMemberFunction = 12, // Not a bug, see above.
8921 ClassOrStruct = 12,
8922 Union = 13,
8923 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
8924 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
8925 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
8926 // literals.
8927};
8928
Chris Lattner86ee2862008-10-06 06:40:35 +00008929/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8930/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00008931static GCCTypeClass
8932EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
8933 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00008934
Richard Smith08b682b2018-05-23 21:18:00 +00008935 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008936 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
8937
8938 switch (CanTy->getTypeClass()) {
8939#define TYPE(ID, BASE)
8940#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
8941#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
8942#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
8943#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00008944 case Type::Auto:
8945 case Type::DeducedTemplateSpecialization:
8946 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008947
8948 case Type::Builtin:
8949 switch (BT->getKind()) {
8950#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00008951#define SIGNED_TYPE(ID, SINGLETON_ID) \
8952 case BuiltinType::ID: return GCCTypeClass::Integer;
8953#define FLOATING_TYPE(ID, SINGLETON_ID) \
8954 case BuiltinType::ID: return GCCTypeClass::RealFloat;
8955#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
8956 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008957#include "clang/AST/BuiltinTypes.def"
8958 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00008959 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008960
8961 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00008962 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008963
Richard Smith08b682b2018-05-23 21:18:00 +00008964 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008965 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00008966 case BuiltinType::WChar_U:
8967 case BuiltinType::Char8:
8968 case BuiltinType::Char16:
8969 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008970 case BuiltinType::UShort:
8971 case BuiltinType::UInt:
8972 case BuiltinType::ULong:
8973 case BuiltinType::ULongLong:
8974 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00008975 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008976
Leonard Chanf921d852018-06-04 16:07:52 +00008977 case BuiltinType::UShortAccum:
8978 case BuiltinType::UAccum:
8979 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00008980 case BuiltinType::UShortFract:
8981 case BuiltinType::UFract:
8982 case BuiltinType::ULongFract:
8983 case BuiltinType::SatUShortAccum:
8984 case BuiltinType::SatUAccum:
8985 case BuiltinType::SatULongAccum:
8986 case BuiltinType::SatUShortFract:
8987 case BuiltinType::SatUFract:
8988 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00008989 return GCCTypeClass::None;
8990
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008991 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008992
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008993 case BuiltinType::ObjCId:
8994 case BuiltinType::ObjCClass:
8995 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00008996#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8997 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00008998#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00008999#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9000 case BuiltinType::Id:
9001#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009002 case BuiltinType::OCLSampler:
9003 case BuiltinType::OCLEvent:
9004 case BuiltinType::OCLClkEvent:
9005 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009006 case BuiltinType::OCLReserveID:
Richard Smith08b682b2018-05-23 21:18:00 +00009007 return GCCTypeClass::None;
9008
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009009 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00009010 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009011 };
Richard Smith08b682b2018-05-23 21:18:00 +00009012 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009013
9014 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00009015 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009016
9017 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009018 case Type::ConstantArray:
9019 case Type::VariableArray:
9020 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00009021 case Type::FunctionNoProto:
9022 case Type::FunctionProto:
9023 return GCCTypeClass::Pointer;
9024
9025 case Type::MemberPointer:
9026 return CanTy->isMemberDataPointerType()
9027 ? GCCTypeClass::PointerToDataMember
9028 : GCCTypeClass::PointerToMemberFunction;
9029
9030 case Type::Complex:
9031 return GCCTypeClass::Complex;
9032
9033 case Type::Record:
9034 return CanTy->isUnionType() ? GCCTypeClass::Union
9035 : GCCTypeClass::ClassOrStruct;
9036
9037 case Type::Atomic:
9038 // GCC classifies _Atomic T the same as T.
9039 return EvaluateBuiltinClassifyType(
9040 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009041
9042 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009043 case Type::Vector:
9044 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009045 case Type::ObjCObject:
9046 case Type::ObjCInterface:
9047 case Type::ObjCObjectPointer:
9048 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00009049 // GCC classifies vectors as None. We follow its lead and classify all
9050 // other types that don't fit into the regular classification the same way.
9051 return GCCTypeClass::None;
9052
9053 case Type::LValueReference:
9054 case Type::RValueReference:
9055 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00009056 }
9057
Richard Smith08b682b2018-05-23 21:18:00 +00009058 llvm_unreachable("unexpected type class");
9059}
9060
9061/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9062/// as GCC.
9063static GCCTypeClass
9064EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
9065 // If no argument was supplied, default to None. This isn't
9066 // ideal, however it is what gcc does.
9067 if (E->getNumArgs() == 0)
9068 return GCCTypeClass::None;
9069
9070 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
9071 // being an ICE, but still folds it to a constant using the type of the first
9072 // argument.
9073 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00009074}
9075
Richard Smith5fab0c92011-12-28 19:48:30 +00009076/// EvaluateBuiltinConstantPForLValue - Determine the result of
Richard Smith31cfb312019-04-27 02:58:17 +00009077/// __builtin_constant_p when applied to the given pointer.
Richard Smith5fab0c92011-12-28 19:48:30 +00009078///
Richard Smith31cfb312019-04-27 02:58:17 +00009079/// A pointer is only "constant" if it is null (or a pointer cast to integer)
9080/// or it points to the first character of a string literal.
9081static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
9082 APValue::LValueBase Base = LV.getLValueBase();
9083 if (Base.isNull()) {
9084 // A null base is acceptable.
9085 return true;
9086 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
9087 if (!isa<StringLiteral>(E))
9088 return false;
9089 return LV.getLValueOffset().isZero();
Richard Smithee0ce3022019-05-17 07:06:46 +00009090 } else if (Base.is<TypeInfoLValue>()) {
9091 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
9092 // evaluate to true.
9093 return true;
Richard Smith31cfb312019-04-27 02:58:17 +00009094 } else {
9095 // Any other base is not constant enough for GCC.
9096 return false;
9097 }
Richard Smith5fab0c92011-12-28 19:48:30 +00009098}
9099
9100/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
9101/// GCC as we can manage.
Richard Smith31cfb312019-04-27 02:58:17 +00009102static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
Richard Smith37be3362019-05-04 04:00:45 +00009103 // This evaluation is not permitted to have side-effects, so evaluate it in
9104 // a speculative evaluation context.
9105 SpeculativeEvaluationRAII SpeculativeEval(Info);
9106
Richard Smith31cfb312019-04-27 02:58:17 +00009107 // Constant-folding is always enabled for the operand of __builtin_constant_p
9108 // (even when the enclosing evaluation context otherwise requires a strict
9109 // language-specific constant expression).
9110 FoldConstant Fold(Info, true);
9111
Richard Smith5fab0c92011-12-28 19:48:30 +00009112 QualType ArgType = Arg->getType();
9113
9114 // __builtin_constant_p always has one operand. The rules which gcc follows
9115 // are not precisely documented, but are as follows:
9116 //
9117 // - If the operand is of integral, floating, complex or enumeration type,
9118 // and can be folded to a known value of that type, it returns 1.
Richard Smith31cfb312019-04-27 02:58:17 +00009119 // - If the operand can be folded to a pointer to the first character
9120 // of a string literal (or such a pointer cast to an integral type)
9121 // or to a null pointer or an integer cast to a pointer, it returns 1.
Richard Smith5fab0c92011-12-28 19:48:30 +00009122 //
9123 // Otherwise, it returns 0.
9124 //
9125 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
Richard Smith31cfb312019-04-27 02:58:17 +00009126 // its support for this did not work prior to GCC 9 and is not yet well
9127 // understood.
9128 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
9129 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
9130 ArgType->isNullPtrType()) {
9131 APValue V;
9132 if (!::EvaluateAsRValue(Info, Arg, V)) {
9133 Fold.keepDiagnostics();
Richard Smith5fab0c92011-12-28 19:48:30 +00009134 return false;
Richard Smith31cfb312019-04-27 02:58:17 +00009135 }
Richard Smith5fab0c92011-12-28 19:48:30 +00009136
Richard Smith31cfb312019-04-27 02:58:17 +00009137 // For a pointer (possibly cast to integer), there are special rules.
Richard Smith0c6124b2015-12-03 01:36:22 +00009138 if (V.getKind() == APValue::LValue)
9139 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith31cfb312019-04-27 02:58:17 +00009140
9141 // Otherwise, any constant value is good enough.
Richard Smithe637cbe2019-05-21 23:15:18 +00009142 return V.hasValue();
Richard Smith5fab0c92011-12-28 19:48:30 +00009143 }
9144
9145 // Anything else isn't considered to be sufficiently constant.
9146 return false;
9147}
9148
John McCall95007602010-05-10 23:27:23 +00009149/// Retrieves the "underlying object type" of the given expression,
9150/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00009151static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00009152 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
9153 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00009154 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00009155 } else if (const Expr *E = B.get<const Expr*>()) {
9156 if (isa<CompoundLiteralExpr>(E))
9157 return E->getType();
Richard Smithee0ce3022019-05-17 07:06:46 +00009158 } else if (B.is<TypeInfoLValue>()) {
9159 return B.getTypeInfoType();
John McCall95007602010-05-10 23:27:23 +00009160 }
9161
9162 return QualType();
9163}
9164
George Burgess IV3a03fab2015-09-04 21:28:13 +00009165/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00009166/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00009167/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00009168/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
9169///
9170/// Always returns an RValue with a pointer representation.
9171static const Expr *ignorePointerCastsAndParens(const Expr *E) {
9172 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
9173
9174 auto *NoParens = E->IgnoreParens();
9175 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00009176 if (Cast == nullptr)
9177 return NoParens;
9178
9179 // We only conservatively allow a few kinds of casts, because this code is
9180 // inherently a simple solution that seeks to support the common case.
9181 auto CastKind = Cast->getCastKind();
9182 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
9183 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00009184 return NoParens;
9185
9186 auto *SubExpr = Cast->getSubExpr();
9187 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
9188 return NoParens;
9189 return ignorePointerCastsAndParens(SubExpr);
9190}
9191
George Burgess IVa51c4072015-10-16 01:49:01 +00009192/// Checks to see if the given LValue's Designator is at the end of the LValue's
9193/// record layout. e.g.
9194/// struct { struct { int a, b; } fst, snd; } obj;
9195/// obj.fst // no
9196/// obj.snd // yes
9197/// obj.fst.a // no
9198/// obj.fst.b // no
9199/// obj.snd.a // no
9200/// obj.snd.b // yes
9201///
9202/// Please note: this function is specialized for how __builtin_object_size
9203/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00009204///
Richard Smith6f4f0f12017-10-20 22:56:25 +00009205/// If this encounters an invalid RecordDecl or otherwise cannot determine the
9206/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00009207static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
9208 assert(!LVal.Designator.Invalid);
9209
George Burgess IV4168d752016-06-27 19:40:41 +00009210 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
9211 const RecordDecl *Parent = FD->getParent();
9212 Invalid = Parent->isInvalidDecl();
9213 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00009214 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00009215 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00009216 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
9217 };
9218
9219 auto &Base = LVal.getLValueBase();
9220 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
9221 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00009222 bool Invalid;
9223 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9224 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00009225 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00009226 for (auto *FD : IFD->chain()) {
9227 bool Invalid;
9228 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
9229 return Invalid;
9230 }
George Burgess IVa51c4072015-10-16 01:49:01 +00009231 }
9232 }
9233
George Burgess IVe3763372016-12-22 02:50:20 +00009234 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00009235 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00009236 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00009237 // If we don't know the array bound, conservatively assume we're looking at
9238 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00009239 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00009240 if (BaseType->isIncompleteArrayType())
9241 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
9242 else
9243 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00009244 }
9245
9246 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
9247 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00009248 if (BaseType->isArrayType()) {
9249 // Because __builtin_object_size treats arrays as objects, we can ignore
9250 // the index iff this is the last array in the Designator.
9251 if (I + 1 == E)
9252 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00009253 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
Richard Smith5b5e27a2019-05-10 20:05:31 +00009254 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00009255 if (Index + 1 != CAT->getSize())
9256 return false;
9257 BaseType = CAT->getElementType();
9258 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00009259 const auto *CT = BaseType->castAs<ComplexType>();
Richard Smith5b5e27a2019-05-10 20:05:31 +00009260 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00009261 if (Index != 1)
9262 return false;
9263 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00009264 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00009265 bool Invalid;
9266 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9267 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00009268 BaseType = FD->getType();
9269 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00009270 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00009271 return false;
9272 }
9273 }
9274 return true;
9275}
9276
George Burgess IVe3763372016-12-22 02:50:20 +00009277/// Tests to see if the LValue has a user-specified designator (that isn't
9278/// necessarily valid). Note that this always returns 'true' if the LValue has
9279/// an unsized array as its first designator entry, because there's currently no
9280/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00009281static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00009282 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00009283 return false;
9284
George Burgess IVe3763372016-12-22 02:50:20 +00009285 if (!LVal.Designator.Entries.empty())
9286 return LVal.Designator.isMostDerivedAnUnsizedArray();
9287
George Burgess IVa51c4072015-10-16 01:49:01 +00009288 if (!LVal.InvalidBase)
9289 return true;
9290
George Burgess IVe3763372016-12-22 02:50:20 +00009291 // If `E` is a MemberExpr, then the first part of the designator is hiding in
9292 // the LValueBase.
9293 const auto *E = LVal.Base.dyn_cast<const Expr *>();
9294 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00009295}
9296
George Burgess IVe3763372016-12-22 02:50:20 +00009297/// Attempts to detect a user writing into a piece of memory that's impossible
9298/// to figure out the size of by just using types.
9299static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
9300 const SubobjectDesignator &Designator = LVal.Designator;
9301 // Notes:
9302 // - Users can only write off of the end when we have an invalid base. Invalid
9303 // bases imply we don't know where the memory came from.
9304 // - We used to be a bit more aggressive here; we'd only be conservative if
9305 // the array at the end was flexible, or if it had 0 or 1 elements. This
9306 // broke some common standard library extensions (PR30346), but was
9307 // otherwise seemingly fine. It may be useful to reintroduce this behavior
9308 // with some sort of whitelist. OTOH, it seems that GCC is always
9309 // conservative with the last element in structs (if it's an array), so our
9310 // current behavior is more compatible than a whitelisting approach would
9311 // be.
9312 return LVal.InvalidBase &&
9313 Designator.Entries.size() == Designator.MostDerivedPathLength &&
9314 Designator.MostDerivedIsArrayElement &&
9315 isDesignatorAtObjectEnd(Ctx, LVal);
9316}
9317
9318/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
9319/// Fails if the conversion would cause loss of precision.
9320static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
9321 CharUnits &Result) {
9322 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
9323 if (Int.ugt(CharUnitsMax))
9324 return false;
9325 Result = CharUnits::fromQuantity(Int.getZExtValue());
9326 return true;
9327}
9328
9329/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
9330/// determine how many bytes exist from the beginning of the object to either
9331/// the end of the current subobject, or the end of the object itself, depending
9332/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00009333///
George Burgess IVe3763372016-12-22 02:50:20 +00009334/// If this returns false, the value of Result is undefined.
9335static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
9336 unsigned Type, const LValue &LVal,
9337 CharUnits &EndOffset) {
9338 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009339
George Burgess IV7fb7e362017-01-03 23:35:19 +00009340 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
9341 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
9342 return false;
9343 return HandleSizeof(Info, ExprLoc, Ty, Result);
9344 };
9345
George Burgess IVe3763372016-12-22 02:50:20 +00009346 // We want to evaluate the size of the entire object. This is a valid fallback
9347 // for when Type=1 and the designator is invalid, because we're asked for an
9348 // upper-bound.
9349 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
9350 // Type=3 wants a lower bound, so we can't fall back to this.
9351 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00009352 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00009353
9354 llvm::APInt APEndOffset;
9355 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9356 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9357 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9358
9359 if (LVal.InvalidBase)
9360 return false;
9361
9362 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00009363 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00009364 }
9365
George Burgess IVe3763372016-12-22 02:50:20 +00009366 // We want to evaluate the size of a subobject.
9367 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009368
9369 // The following is a moderately common idiom in C:
9370 //
9371 // struct Foo { int a; char c[1]; };
9372 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
9373 // strcpy(&F->c[0], Bar);
9374 //
George Burgess IVe3763372016-12-22 02:50:20 +00009375 // In order to not break too much legacy code, we need to support it.
9376 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
9377 // If we can resolve this to an alloc_size call, we can hand that back,
9378 // because we know for certain how many bytes there are to write to.
9379 llvm::APInt APEndOffset;
9380 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9381 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9382 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9383
9384 // If we cannot determine the size of the initial allocation, then we can't
9385 // given an accurate upper-bound. However, we are still able to give
9386 // conservative lower-bounds for Type=3.
9387 if (Type == 1)
9388 return false;
9389 }
9390
9391 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00009392 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009393 return false;
9394
George Burgess IVe3763372016-12-22 02:50:20 +00009395 // According to the GCC documentation, we want the size of the subobject
9396 // denoted by the pointer. But that's not quite right -- what we actually
9397 // want is the size of the immediately-enclosing array, if there is one.
9398 int64_t ElemsRemaining;
9399 if (Designator.MostDerivedIsArrayElement &&
9400 Designator.Entries.size() == Designator.MostDerivedPathLength) {
9401 uint64_t ArraySize = Designator.getMostDerivedArraySize();
Richard Smith5b5e27a2019-05-10 20:05:31 +00009402 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00009403 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
9404 } else {
9405 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
9406 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009407
George Burgess IVe3763372016-12-22 02:50:20 +00009408 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
9409 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009410}
9411
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009412/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00009413/// returns true and stores the result in @p Size.
9414///
9415/// If @p WasError is non-null, this will report whether the failure to evaluate
9416/// is to be treated as an Error in IntExprEvaluator.
9417static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
9418 EvalInfo &Info, uint64_t &Size) {
9419 // Determine the denoted object.
9420 LValue LVal;
9421 {
9422 // The operand of __builtin_object_size is never evaluated for side-effects.
9423 // If there are any, but we can determine the pointed-to object anyway, then
9424 // ignore the side-effects.
9425 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00009426 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00009427
9428 if (E->isGLValue()) {
9429 // It's possible for us to be given GLValues if we're called via
9430 // Expr::tryEvaluateObjectSize.
9431 APValue RVal;
9432 if (!EvaluateAsRValue(Info, E, RVal))
9433 return false;
9434 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00009435 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
9436 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00009437 return false;
9438 }
9439
9440 // If we point to before the start of the object, there are no accessible
9441 // bytes.
9442 if (LVal.getLValueOffset().isNegative()) {
9443 Size = 0;
9444 return true;
9445 }
9446
9447 CharUnits EndOffset;
9448 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
9449 return false;
9450
9451 // If we've fallen outside of the end offset, just pretend there's nothing to
9452 // write to/read from.
9453 if (EndOffset <= LVal.getLValueOffset())
9454 Size = 0;
9455 else
9456 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
9457 return true;
John McCall95007602010-05-10 23:27:23 +00009458}
9459
Fangrui Song407659a2018-11-30 23:41:18 +00009460bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
9461 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
Gauthier Harnischdea9d572019-06-21 08:26:21 +00009462 if (E->getResultAPValueKind() != APValue::None)
9463 return Success(E->getAPValueResult(), E);
Fangrui Song407659a2018-11-30 23:41:18 +00009464 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
9465}
9466
Peter Collingbournee9200682011-05-13 03:29:01 +00009467bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00009468 if (unsigned BuiltinOp = E->getBuiltinCallee())
9469 return VisitBuiltinCallExpr(E, BuiltinOp);
9470
9471 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9472}
9473
9474bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9475 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00009476 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009477 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00009478 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00009479
Erik Pilkington9c3b5882019-01-30 20:34:53 +00009480 case Builtin::BI__builtin_dynamic_object_size:
Mike Stump722cedf2009-10-26 18:35:08 +00009481 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00009482 // The type was checked when we built the expression.
9483 unsigned Type =
9484 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9485 assert(Type <= 3 && "unexpected type");
9486
George Burgess IVe3763372016-12-22 02:50:20 +00009487 uint64_t Size;
9488 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
9489 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00009490
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009491 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00009492 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00009493
Richard Smith01ade172012-05-23 04:13:20 +00009494 // Expression had no side effects, but we couldn't statically determine the
9495 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009496 switch (Info.EvalMode) {
9497 case EvalInfo::EM_ConstantExpression:
9498 case EvalInfo::EM_PotentialConstantExpression:
9499 case EvalInfo::EM_ConstantFold:
9500 case EvalInfo::EM_EvaluateForOverflow:
9501 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00009502 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009503 return Error(E);
9504 case EvalInfo::EM_ConstantExpressionUnevaluated:
9505 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00009506 // Reduce it to a constant now.
9507 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009508 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00009509
9510 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00009511 }
9512
Tim Northover314fbfa2018-11-02 13:14:11 +00009513 case Builtin::BI__builtin_os_log_format_buffer_size: {
9514 analyze_os_log::OSLogBufferLayout Layout;
9515 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
9516 return Success(Layout.size().getQuantity(), E);
9517 }
9518
Benjamin Kramera801f4a2012-10-06 14:42:22 +00009519 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00009520 case Builtin::BI__builtin_bswap32:
9521 case Builtin::BI__builtin_bswap64: {
9522 APSInt Val;
9523 if (!EvaluateInteger(E->getArg(0), Val, Info))
9524 return false;
9525
9526 return Success(Val.byteSwap(), E);
9527 }
9528
Richard Smith8889a3d2013-06-13 06:26:32 +00009529 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00009530 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00009531
Craig Topperf95a6d92018-08-08 22:31:12 +00009532 case Builtin::BI__builtin_clrsb:
9533 case Builtin::BI__builtin_clrsbl:
9534 case Builtin::BI__builtin_clrsbll: {
9535 APSInt Val;
9536 if (!EvaluateInteger(E->getArg(0), Val, Info))
9537 return false;
9538
9539 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
9540 }
Richard Smith8889a3d2013-06-13 06:26:32 +00009541
Richard Smith80b3c8e2013-06-13 05:04:16 +00009542 case Builtin::BI__builtin_clz:
9543 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00009544 case Builtin::BI__builtin_clzll:
9545 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00009546 APSInt Val;
9547 if (!EvaluateInteger(E->getArg(0), Val, Info))
9548 return false;
9549 if (!Val)
9550 return Error(E);
9551
9552 return Success(Val.countLeadingZeros(), E);
9553 }
9554
Fangrui Song407659a2018-11-30 23:41:18 +00009555 case Builtin::BI__builtin_constant_p: {
Richard Smith31cfb312019-04-27 02:58:17 +00009556 const Expr *Arg = E->getArg(0);
David Blaikie639b3d12019-05-03 18:11:31 +00009557 if (EvaluateBuiltinConstantP(Info, Arg))
Fangrui Song407659a2018-11-30 23:41:18 +00009558 return Success(true, E);
David Blaikie639b3d12019-05-03 18:11:31 +00009559 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
Richard Smithf7d30482019-05-02 23:21:28 +00009560 // Outside a constant context, eagerly evaluate to false in the presence
9561 // of side-effects in order to avoid -Wunsequenced false-positives in
9562 // a branch on __builtin_constant_p(expr).
Richard Smith31cfb312019-04-27 02:58:17 +00009563 return Success(false, E);
Fangrui Song407659a2018-11-30 23:41:18 +00009564 }
David Blaikie639b3d12019-05-03 18:11:31 +00009565 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9566 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00009567 }
Richard Smith8889a3d2013-06-13 06:26:32 +00009568
Eric Fiselieradd16a82019-04-24 02:23:30 +00009569 case Builtin::BI__builtin_is_constant_evaluated:
9570 return Success(Info.InConstantContext, E);
9571
Richard Smith80b3c8e2013-06-13 05:04:16 +00009572 case Builtin::BI__builtin_ctz:
9573 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00009574 case Builtin::BI__builtin_ctzll:
9575 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00009576 APSInt Val;
9577 if (!EvaluateInteger(E->getArg(0), Val, Info))
9578 return false;
9579 if (!Val)
9580 return Error(E);
9581
9582 return Success(Val.countTrailingZeros(), E);
9583 }
9584
Richard Smith8889a3d2013-06-13 06:26:32 +00009585 case Builtin::BI__builtin_eh_return_data_regno: {
9586 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9587 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
9588 return Success(Operand, E);
9589 }
9590
9591 case Builtin::BI__builtin_expect:
9592 return Visit(E->getArg(0));
9593
9594 case Builtin::BI__builtin_ffs:
9595 case Builtin::BI__builtin_ffsl:
9596 case Builtin::BI__builtin_ffsll: {
9597 APSInt Val;
9598 if (!EvaluateInteger(E->getArg(0), Val, Info))
9599 return false;
9600
9601 unsigned N = Val.countTrailingZeros();
9602 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
9603 }
9604
9605 case Builtin::BI__builtin_fpclassify: {
9606 APFloat Val(0.0);
9607 if (!EvaluateFloat(E->getArg(5), Val, Info))
9608 return false;
9609 unsigned Arg;
9610 switch (Val.getCategory()) {
9611 case APFloat::fcNaN: Arg = 0; break;
9612 case APFloat::fcInfinity: Arg = 1; break;
9613 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
9614 case APFloat::fcZero: Arg = 4; break;
9615 }
9616 return Visit(E->getArg(Arg));
9617 }
9618
9619 case Builtin::BI__builtin_isinf_sign: {
9620 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00009621 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00009622 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
9623 }
9624
Richard Smithea3019d2013-10-15 19:07:14 +00009625 case Builtin::BI__builtin_isinf: {
9626 APFloat Val(0.0);
9627 return EvaluateFloat(E->getArg(0), Val, Info) &&
9628 Success(Val.isInfinity() ? 1 : 0, E);
9629 }
9630
9631 case Builtin::BI__builtin_isfinite: {
9632 APFloat Val(0.0);
9633 return EvaluateFloat(E->getArg(0), Val, Info) &&
9634 Success(Val.isFinite() ? 1 : 0, E);
9635 }
9636
9637 case Builtin::BI__builtin_isnan: {
9638 APFloat Val(0.0);
9639 return EvaluateFloat(E->getArg(0), Val, Info) &&
9640 Success(Val.isNaN() ? 1 : 0, E);
9641 }
9642
9643 case Builtin::BI__builtin_isnormal: {
9644 APFloat Val(0.0);
9645 return EvaluateFloat(E->getArg(0), Val, Info) &&
9646 Success(Val.isNormal() ? 1 : 0, E);
9647 }
9648
Richard Smith8889a3d2013-06-13 06:26:32 +00009649 case Builtin::BI__builtin_parity:
9650 case Builtin::BI__builtin_parityl:
9651 case Builtin::BI__builtin_parityll: {
9652 APSInt Val;
9653 if (!EvaluateInteger(E->getArg(0), Val, Info))
9654 return false;
9655
9656 return Success(Val.countPopulation() % 2, E);
9657 }
9658
Richard Smith80b3c8e2013-06-13 05:04:16 +00009659 case Builtin::BI__builtin_popcount:
9660 case Builtin::BI__builtin_popcountl:
9661 case Builtin::BI__builtin_popcountll: {
9662 APSInt Val;
9663 if (!EvaluateInteger(E->getArg(0), Val, Info))
9664 return false;
9665
9666 return Success(Val.countPopulation(), E);
9667 }
9668
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009669 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00009670 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00009671 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009672 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009673 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00009674 << /*isConstexpr*/0 << /*isConstructor*/0
9675 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00009676 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00009677 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009678 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00009679 case Builtin::BI__builtin_strlen:
9680 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00009681 // As an extension, we support __builtin_strlen() as a constant expression,
9682 // and support folding strlen() to a constant.
9683 LValue String;
9684 if (!EvaluatePointer(E->getArg(0), String, Info))
9685 return false;
9686
Richard Smith8110c9d2016-11-29 19:45:17 +00009687 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
9688
Richard Smithe6c19f22013-11-15 02:10:04 +00009689 // Fast path: if it's a string literal, search the string value.
9690 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
9691 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009692 // The string literal may have embedded null characters. Find the first
9693 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00009694 StringRef Str = S->getBytes();
9695 int64_t Off = String.Offset.getQuantity();
9696 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00009697 S->getCharByteWidth() == 1 &&
9698 // FIXME: Add fast-path for wchar_t too.
9699 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00009700 Str = Str.substr(Off);
9701
9702 StringRef::size_type Pos = Str.find(0);
9703 if (Pos != StringRef::npos)
9704 Str = Str.substr(0, Pos);
9705
9706 return Success(Str.size(), E);
9707 }
9708
9709 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009710 }
Richard Smithe6c19f22013-11-15 02:10:04 +00009711
9712 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00009713 for (uint64_t Strlen = 0; /**/; ++Strlen) {
9714 APValue Char;
9715 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9716 !Char.isInt())
9717 return false;
9718 if (!Char.getInt())
9719 return Success(Strlen, E);
9720 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9721 return false;
9722 }
9723 }
Eli Friedmana4c26022011-10-17 21:44:23 +00009724
Richard Smithe151bab2016-11-11 23:43:35 +00009725 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009726 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009727 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009728 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009729 case Builtin::BImemcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00009730 case Builtin::BIbcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009731 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009732 // A call to strlen is not a constant expression.
9733 if (Info.getLangOpts().CPlusPlus11)
9734 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9735 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00009736 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00009737 else
9738 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009739 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00009740 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009741 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009742 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009743 case Builtin::BI__builtin_wcsncmp:
9744 case Builtin::BI__builtin_memcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00009745 case Builtin::BI__builtin_bcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009746 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00009747 LValue String1, String2;
9748 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9749 !EvaluatePointer(E->getArg(1), String2, Info))
9750 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00009751
Richard Smithe151bab2016-11-11 23:43:35 +00009752 uint64_t MaxLength = uint64_t(-1);
9753 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00009754 BuiltinOp != Builtin::BIwcscmp &&
9755 BuiltinOp != Builtin::BI__builtin_strcmp &&
9756 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00009757 APSInt N;
9758 if (!EvaluateInteger(E->getArg(2), N, Info))
9759 return false;
9760 MaxLength = N.getExtValue();
9761 }
Hubert Tong147b7432018-12-12 16:53:43 +00009762
9763 // Empty substrings compare equal by definition.
9764 if (MaxLength == 0u)
9765 return Success(0, E);
9766
9767 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9768 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9769 String1.Designator.Invalid || String2.Designator.Invalid)
9770 return false;
9771
9772 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9773 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9774
9775 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
Clement Courbet8c3343d2019-02-14 12:00:34 +00009776 BuiltinOp == Builtin::BIbcmp ||
9777 BuiltinOp == Builtin::BI__builtin_memcmp ||
9778 BuiltinOp == Builtin::BI__builtin_bcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00009779
9780 assert(IsRawByte ||
9781 (Info.Ctx.hasSameUnqualifiedType(
9782 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9783 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9784
9785 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9786 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9787 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9788 Char1.isInt() && Char2.isInt();
9789 };
9790 const auto &AdvanceElems = [&] {
9791 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9792 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9793 };
9794
9795 if (IsRawByte) {
9796 uint64_t BytesRemaining = MaxLength;
9797 // Pointers to const void may point to objects of incomplete type.
9798 if (CharTy1->isIncompleteType()) {
9799 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9800 return false;
9801 }
9802 if (CharTy2->isIncompleteType()) {
9803 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9804 return false;
9805 }
9806 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9807 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9808 // Give up on comparing between elements with disparate widths.
9809 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9810 return false;
9811 uint64_t BytesPerElement = CharTy1Size.getQuantity();
9812 assert(BytesRemaining && "BytesRemaining should not be zero: the "
9813 "following loop considers at least one element");
9814 while (true) {
9815 APValue Char1, Char2;
9816 if (!ReadCurElems(Char1, Char2))
9817 return false;
9818 // We have compatible in-memory widths, but a possible type and
9819 // (for `bool`) internal representation mismatch.
9820 // Assuming two's complement representation, including 0 for `false` and
9821 // 1 for `true`, we can check an appropriate number of elements for
9822 // equality even if they are not byte-sized.
9823 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9824 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9825 if (Char1InMem.ne(Char2InMem)) {
9826 // If the elements are byte-sized, then we can produce a three-way
9827 // comparison result in a straightforward manner.
9828 if (BytesPerElement == 1u) {
9829 // memcmp always compares unsigned chars.
9830 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9831 }
9832 // The result is byte-order sensitive, and we have multibyte elements.
9833 // FIXME: We can compare the remaining bytes in the correct order.
9834 return false;
9835 }
9836 if (!AdvanceElems())
9837 return false;
9838 if (BytesRemaining <= BytesPerElement)
9839 break;
9840 BytesRemaining -= BytesPerElement;
9841 }
9842 // Enough elements are equal to account for the memcmp limit.
9843 return Success(0, E);
9844 }
9845
Clement Courbet8c3343d2019-02-14 12:00:34 +00009846 bool StopAtNull =
9847 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9848 BuiltinOp != Builtin::BIwmemcmp &&
9849 BuiltinOp != Builtin::BI__builtin_memcmp &&
9850 BuiltinOp != Builtin::BI__builtin_bcmp &&
9851 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00009852 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9853 BuiltinOp == Builtin::BIwcsncmp ||
9854 BuiltinOp == Builtin::BIwmemcmp ||
9855 BuiltinOp == Builtin::BI__builtin_wcscmp ||
9856 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9857 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00009858
Richard Smithe151bab2016-11-11 23:43:35 +00009859 for (; MaxLength; --MaxLength) {
9860 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +00009861 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +00009862 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00009863 if (Char1.getInt() != Char2.getInt()) {
9864 if (IsWide) // wmemcmp compares with wchar_t signedness.
9865 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9866 // memcmp always compares unsigned chars.
9867 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9868 }
Richard Smithe151bab2016-11-11 23:43:35 +00009869 if (StopAtNull && !Char1.getInt())
9870 return Success(0, E);
9871 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +00009872 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +00009873 return false;
9874 }
9875 // We hit the strncmp / memcmp limit.
9876 return Success(0, E);
9877 }
9878
Richard Smith01ba47d2012-04-13 00:45:38 +00009879 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00009880 case Builtin::BI__atomic_is_lock_free:
9881 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00009882 APSInt SizeVal;
9883 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9884 return false;
9885
9886 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9887 // of two less than the maximum inline atomic width, we know it is
9888 // lock-free. If the size isn't a power of two, or greater than the
9889 // maximum alignment where we promote atomics, we know it is not lock-free
9890 // (at least not in the sense of atomic_is_lock_free). Otherwise,
9891 // the answer can only be determined at runtime; for example, 16-byte
9892 // atomics have lock-free implementations on some, but not all,
9893 // x86-64 processors.
9894
9895 // Check power-of-two.
9896 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00009897 if (Size.isPowerOfTwo()) {
9898 // Check against inlining width.
9899 unsigned InlineWidthBits =
9900 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9901 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9902 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9903 Size == CharUnits::One() ||
9904 E->getArg(1)->isNullPointerConstant(Info.Ctx,
9905 Expr::NPC_NeverValueDependent))
9906 // OK, we will inline appropriately-aligned operations of this size,
9907 // and _Atomic(T) is appropriately-aligned.
9908 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00009909
Richard Smith01ba47d2012-04-13 00:45:38 +00009910 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9911 castAs<PointerType>()->getPointeeType();
9912 if (!PointeeType->isIncompleteType() &&
9913 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9914 // OK, we will inline operations on this object.
9915 return Success(1, E);
9916 }
9917 }
9918 }
Eli Friedmana4c26022011-10-17 21:44:23 +00009919
Richard Smith01ba47d2012-04-13 00:45:38 +00009920 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9921 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00009922 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00009923 case Builtin::BIomp_is_initial_device:
9924 // We can decide statically which value the runtime would return if called.
9925 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00009926 case Builtin::BI__builtin_add_overflow:
9927 case Builtin::BI__builtin_sub_overflow:
9928 case Builtin::BI__builtin_mul_overflow:
9929 case Builtin::BI__builtin_sadd_overflow:
9930 case Builtin::BI__builtin_uadd_overflow:
9931 case Builtin::BI__builtin_uaddl_overflow:
9932 case Builtin::BI__builtin_uaddll_overflow:
9933 case Builtin::BI__builtin_usub_overflow:
9934 case Builtin::BI__builtin_usubl_overflow:
9935 case Builtin::BI__builtin_usubll_overflow:
9936 case Builtin::BI__builtin_umul_overflow:
9937 case Builtin::BI__builtin_umull_overflow:
9938 case Builtin::BI__builtin_umulll_overflow:
9939 case Builtin::BI__builtin_saddl_overflow:
9940 case Builtin::BI__builtin_saddll_overflow:
9941 case Builtin::BI__builtin_ssub_overflow:
9942 case Builtin::BI__builtin_ssubl_overflow:
9943 case Builtin::BI__builtin_ssubll_overflow:
9944 case Builtin::BI__builtin_smul_overflow:
9945 case Builtin::BI__builtin_smull_overflow:
9946 case Builtin::BI__builtin_smulll_overflow: {
9947 LValue ResultLValue;
9948 APSInt LHS, RHS;
9949
9950 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9951 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9952 !EvaluateInteger(E->getArg(1), RHS, Info) ||
9953 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9954 return false;
9955
9956 APSInt Result;
9957 bool DidOverflow = false;
9958
9959 // If the types don't have to match, enlarge all 3 to the largest of them.
9960 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9961 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9962 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9963 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9964 ResultType->isSignedIntegerOrEnumerationType();
9965 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9966 ResultType->isSignedIntegerOrEnumerationType();
9967 uint64_t LHSSize = LHS.getBitWidth();
9968 uint64_t RHSSize = RHS.getBitWidth();
9969 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9970 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9971
9972 // Add an additional bit if the signedness isn't uniformly agreed to. We
9973 // could do this ONLY if there is a signed and an unsigned that both have
9974 // MaxBits, but the code to check that is pretty nasty. The issue will be
9975 // caught in the shrink-to-result later anyway.
9976 if (IsSigned && !AllSigned)
9977 ++MaxBits;
9978
Erich Keanefc3dfd32019-05-30 21:35:32 +00009979 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
9980 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
Erich Keane00958272018-06-13 20:43:27 +00009981 Result = APSInt(MaxBits, !IsSigned);
9982 }
9983
9984 // Find largest int.
9985 switch (BuiltinOp) {
9986 default:
9987 llvm_unreachable("Invalid value for BuiltinOp");
9988 case Builtin::BI__builtin_add_overflow:
9989 case Builtin::BI__builtin_sadd_overflow:
9990 case Builtin::BI__builtin_saddl_overflow:
9991 case Builtin::BI__builtin_saddll_overflow:
9992 case Builtin::BI__builtin_uadd_overflow:
9993 case Builtin::BI__builtin_uaddl_overflow:
9994 case Builtin::BI__builtin_uaddll_overflow:
9995 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
9996 : LHS.uadd_ov(RHS, DidOverflow);
9997 break;
9998 case Builtin::BI__builtin_sub_overflow:
9999 case Builtin::BI__builtin_ssub_overflow:
10000 case Builtin::BI__builtin_ssubl_overflow:
10001 case Builtin::BI__builtin_ssubll_overflow:
10002 case Builtin::BI__builtin_usub_overflow:
10003 case Builtin::BI__builtin_usubl_overflow:
10004 case Builtin::BI__builtin_usubll_overflow:
10005 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
10006 : LHS.usub_ov(RHS, DidOverflow);
10007 break;
10008 case Builtin::BI__builtin_mul_overflow:
10009 case Builtin::BI__builtin_smul_overflow:
10010 case Builtin::BI__builtin_smull_overflow:
10011 case Builtin::BI__builtin_smulll_overflow:
10012 case Builtin::BI__builtin_umul_overflow:
10013 case Builtin::BI__builtin_umull_overflow:
10014 case Builtin::BI__builtin_umulll_overflow:
10015 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
10016 : LHS.umul_ov(RHS, DidOverflow);
10017 break;
10018 }
10019
10020 // In the case where multiple sizes are allowed, truncate and see if
10021 // the values are the same.
10022 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10023 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10024 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10025 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
10026 // since it will give us the behavior of a TruncOrSelf in the case where
10027 // its parameter <= its size. We previously set Result to be at least the
10028 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
10029 // will work exactly like TruncOrSelf.
10030 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
10031 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
10032
10033 if (!APSInt::isSameValue(Temp, Result))
10034 DidOverflow = true;
10035 Result = Temp;
10036 }
10037
10038 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +000010039 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
10040 return false;
Erich Keane00958272018-06-13 20:43:27 +000010041 return Success(DidOverflow, E);
10042 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010043 }
Chris Lattner7174bf32008-07-12 00:38:25 +000010044}
Anders Carlsson4a3585b2008-07-08 15:34:11 +000010045
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010046/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +000010047/// object referred to by the lvalue.
10048static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
10049 const LValue &LV) {
10050 // A null pointer can be viewed as being "past the end" but we don't
10051 // choose to look at it that way here.
10052 if (!LV.getLValueBase())
10053 return false;
10054
10055 // If the designator is valid and refers to a subobject, we're not pointing
10056 // past the end.
10057 if (!LV.getLValueDesignator().Invalid &&
10058 !LV.getLValueDesignator().isOnePastTheEnd())
10059 return false;
10060
David Majnemerc378ca52015-08-29 08:32:55 +000010061 // A pointer to an incomplete type might be past-the-end if the type's size is
10062 // zero. We cannot tell because the type is incomplete.
10063 QualType Ty = getType(LV.getLValueBase());
10064 if (Ty->isIncompleteType())
10065 return true;
10066
Richard Smithd20f1e62014-10-21 23:01:04 +000010067 // We're a past-the-end pointer if we point to the byte after the object,
10068 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +000010069 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +000010070 return LV.getLValueOffset() == Size;
10071}
10072
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010073namespace {
Richard Smith11562c52011-10-28 17:51:58 +000010074
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010075/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010076///
10077/// We use a data recursive algorithm for binary operators so that we are able
10078/// to handle extreme cases of chained binary operators without causing stack
10079/// overflow.
10080class DataRecursiveIntBinOpEvaluator {
10081 struct EvalResult {
10082 APValue Val;
10083 bool Failed;
10084
10085 EvalResult() : Failed(false) { }
10086
10087 void swap(EvalResult &RHS) {
10088 Val.swap(RHS.Val);
10089 Failed = RHS.Failed;
10090 RHS.Failed = false;
10091 }
10092 };
10093
10094 struct Job {
10095 const Expr *E;
10096 EvalResult LHSResult; // meaningful only for binary operator expression.
10097 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +000010098
David Blaikie73726062015-08-12 23:09:24 +000010099 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +000010100 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +000010101
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010102 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +000010103 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010104 }
George Burgess IV8c892b52016-05-25 22:31:54 +000010105
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010106 private:
George Burgess IV8c892b52016-05-25 22:31:54 +000010107 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010108 };
10109
10110 SmallVector<Job, 16> Queue;
10111
10112 IntExprEvaluator &IntEval;
10113 EvalInfo &Info;
10114 APValue &FinalResult;
10115
10116public:
10117 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
10118 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
10119
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010120 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010121 /// data recursively.
10122 /// We handle binary operators that are comma, logical, or that have operands
10123 /// with integral or enumeration type.
10124 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010125 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
10126 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +000010127 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010128 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +000010129 }
10130
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010131 bool Traverse(const BinaryOperator *E) {
10132 enqueue(E);
10133 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +000010134 while (!Queue.empty())
10135 process(PrevResult);
10136
10137 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010138
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010139 FinalResult.swap(PrevResult.Val);
10140 return true;
10141 }
10142
10143private:
10144 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10145 return IntEval.Success(Value, E, Result);
10146 }
10147 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
10148 return IntEval.Success(Value, E, Result);
10149 }
10150 bool Error(const Expr *E) {
10151 return IntEval.Error(E);
10152 }
10153 bool Error(const Expr *E, diag::kind D) {
10154 return IntEval.Error(E, D);
10155 }
10156
10157 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
10158 return Info.CCEDiag(E, D);
10159 }
10160
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010161 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010162 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010163 bool &SuppressRHSDiags);
10164
10165 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10166 const BinaryOperator *E, APValue &Result);
10167
10168 void EvaluateExpr(const Expr *E, EvalResult &Result) {
10169 Result.Failed = !Evaluate(Result.Val, Info, E);
10170 if (Result.Failed)
10171 Result.Val = APValue();
10172 }
10173
Richard Trieuba4d0872012-03-21 23:30:30 +000010174 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010175
10176 void enqueue(const Expr *E) {
10177 E = E->IgnoreParens();
10178 Queue.resize(Queue.size()+1);
10179 Queue.back().E = E;
10180 Queue.back().Kind = Job::AnyExprKind;
10181 }
10182};
10183
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010184}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010185
10186bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010187 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010188 bool &SuppressRHSDiags) {
10189 if (E->getOpcode() == BO_Comma) {
10190 // Ignore LHS but note if we could not evaluate it.
10191 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +000010192 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010193 return true;
10194 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010195
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010196 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +000010197 bool LHSAsBool;
10198 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010199 // We were able to evaluate the LHS, see if we can get away with not
10200 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +000010201 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
10202 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010203 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010204 }
10205 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +000010206 LHSResult.Failed = true;
10207
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010208 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +000010209 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +000010210 if (!Info.noteSideEffect())
10211 return false;
10212
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010213 // We can't evaluate the LHS; however, sometimes the result
10214 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10215 // Don't ignore RHS and suppress diagnostics from this arm.
10216 SuppressRHSDiags = true;
10217 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010218
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010219 return true;
10220 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010221
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010222 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10223 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +000010224
George Burgess IVa145e252016-05-25 22:38:36 +000010225 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010226 return false; // Ignore RHS;
10227
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010228 return true;
10229}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010230
Benjamin Kramerf6021ec2017-03-21 21:35:04 +000010231static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
10232 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +000010233 // Compute the new offset in the appropriate width, wrapping at 64 bits.
10234 // FIXME: When compiling for a 32-bit target, we should use 32-bit
10235 // offsets.
10236 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
10237 CharUnits &Offset = LVal.getLValueOffset();
10238 uint64_t Offset64 = Offset.getQuantity();
10239 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
10240 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
10241 : Offset64 + Index64);
10242}
10243
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010244bool DataRecursiveIntBinOpEvaluator::
10245 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10246 const BinaryOperator *E, APValue &Result) {
10247 if (E->getOpcode() == BO_Comma) {
10248 if (RHSResult.Failed)
10249 return false;
10250 Result = RHSResult.Val;
10251 return true;
10252 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010253
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010254 if (E->isLogicalOp()) {
10255 bool lhsResult, rhsResult;
10256 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
10257 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +000010258
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010259 if (LHSIsOK) {
10260 if (RHSIsOK) {
10261 if (E->getOpcode() == BO_LOr)
10262 return Success(lhsResult || rhsResult, E, Result);
10263 else
10264 return Success(lhsResult && rhsResult, E, Result);
10265 }
10266 } else {
10267 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010268 // We can't evaluate the LHS; however, sometimes the result
10269 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10270 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010271 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010272 }
10273 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010274
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010275 return false;
10276 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010277
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010278 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10279 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +000010280
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010281 if (LHSResult.Failed || RHSResult.Failed)
10282 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010283
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010284 const APValue &LHSVal = LHSResult.Val;
10285 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +000010286
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010287 // Handle cases like (unsigned long)&a + 4.
10288 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
10289 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000010290 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010291 return true;
10292 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010293
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010294 // Handle cases like 4 + (unsigned long)&a
10295 if (E->getOpcode() == BO_Add &&
10296 RHSVal.isLValue() && LHSVal.isInt()) {
10297 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000010298 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010299 return true;
10300 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010301
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010302 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
10303 // Handle (intptr_t)&&A - (intptr_t)&&B.
10304 if (!LHSVal.getLValueOffset().isZero() ||
10305 !RHSVal.getLValueOffset().isZero())
10306 return false;
10307 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
10308 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
10309 if (!LHSExpr || !RHSExpr)
10310 return false;
10311 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10312 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10313 if (!LHSAddrExpr || !RHSAddrExpr)
10314 return false;
10315 // Make sure both labels come from the same function.
10316 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10317 RHSAddrExpr->getLabel()->getDeclContext())
10318 return false;
10319 Result = APValue(LHSAddrExpr, RHSAddrExpr);
10320 return true;
10321 }
Richard Smith43e77732013-05-07 04:50:00 +000010322
10323 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010324 if (!LHSVal.isInt() || !RHSVal.isInt())
10325 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +000010326
10327 // Set up the width and signedness manually, in case it can't be deduced
10328 // from the operation we're performing.
10329 // FIXME: Don't do this in the cases where we can deduce it.
10330 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
10331 E->getType()->isUnsignedIntegerOrEnumerationType());
10332 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
10333 RHSVal.getInt(), Value))
10334 return false;
10335 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010336}
10337
Richard Trieuba4d0872012-03-21 23:30:30 +000010338void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010339 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +000010340
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010341 switch (job.Kind) {
10342 case Job::AnyExprKind: {
10343 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
10344 if (shouldEnqueue(Bop)) {
10345 job.Kind = Job::BinOpKind;
10346 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000010347 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010348 }
10349 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010350
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010351 EvaluateExpr(job.E, Result);
10352 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000010353 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010354 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010355
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010356 case Job::BinOpKind: {
10357 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010358 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010359 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010360 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000010361 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010362 }
10363 if (SuppressRHSDiags)
10364 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010365 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010366 job.Kind = Job::BinOpVisitedLHSKind;
10367 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000010368 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010369 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010370
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010371 case Job::BinOpVisitedLHSKind: {
10372 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10373 EvalResult RHS;
10374 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +000010375 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010376 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000010377 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010378 }
10379 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010380
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010381 llvm_unreachable("Invalid Job::Kind!");
10382}
10383
George Burgess IV8c892b52016-05-25 22:31:54 +000010384namespace {
10385/// Used when we determine that we should fail, but can keep evaluating prior to
10386/// noting that we had a failure.
10387class DelayedNoteFailureRAII {
10388 EvalInfo &Info;
10389 bool NoteFailure;
10390
10391public:
10392 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
10393 : Info(Info), NoteFailure(NoteFailure) {}
10394 ~DelayedNoteFailureRAII() {
10395 if (NoteFailure) {
10396 bool ContinueAfterFailure = Info.noteFailure();
10397 (void)ContinueAfterFailure;
10398 assert(ContinueAfterFailure &&
10399 "Shouldn't have kept evaluating on failure.");
10400 }
10401 }
10402};
10403}
10404
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010405template <class SuccessCB, class AfterCB>
10406static bool
10407EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
10408 SuccessCB &&Success, AfterCB &&DoAfter) {
10409 assert(E->isComparisonOp() && "expected comparison operator");
10410 assert((E->getOpcode() == BO_Cmp ||
10411 E->getType()->isIntegralOrEnumerationType()) &&
10412 "unsupported binary expression evaluation");
10413 auto Error = [&](const Expr *E) {
10414 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10415 return false;
10416 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010417
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010418 using CCR = ComparisonCategoryResult;
10419 bool IsRelational = E->isRelationalOp();
10420 bool IsEquality = E->isEqualityOp();
10421 if (E->getOpcode() == BO_Cmp) {
10422 const ComparisonCategoryInfo &CmpInfo =
10423 Info.Ctx.CompCategories.getInfoForType(E->getType());
10424 IsRelational = CmpInfo.isOrdered();
10425 IsEquality = CmpInfo.isEquality();
10426 }
Eli Friedman5a332ea2008-11-13 06:09:17 +000010427
Anders Carlssonacc79812008-11-16 07:17:21 +000010428 QualType LHSTy = E->getLHS()->getType();
10429 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010430
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010431 if (LHSTy->isIntegralOrEnumerationType() &&
10432 RHSTy->isIntegralOrEnumerationType()) {
10433 APSInt LHS, RHS;
10434 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
10435 if (!LHSOK && !Info.noteFailure())
10436 return false;
10437 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
10438 return false;
10439 if (LHS < RHS)
10440 return Success(CCR::Less, E);
10441 if (LHS > RHS)
10442 return Success(CCR::Greater, E);
10443 return Success(CCR::Equal, E);
10444 }
10445
Leonard Chance1d4f12019-02-21 20:50:09 +000010446 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
10447 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
10448 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
10449
10450 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
10451 if (!LHSOK && !Info.noteFailure())
10452 return false;
10453 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
10454 return false;
10455 if (LHSFX < RHSFX)
10456 return Success(CCR::Less, E);
10457 if (LHSFX > RHSFX)
10458 return Success(CCR::Greater, E);
10459 return Success(CCR::Equal, E);
10460 }
10461
Chandler Carruthb29a7432014-10-11 11:03:30 +000010462 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000010463 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +000010464 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +000010465 if (E->isAssignmentOp()) {
10466 LValue LV;
10467 EvaluateLValue(E->getLHS(), LV, Info);
10468 LHSOK = false;
10469 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +000010470 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
10471 if (LHSOK) {
10472 LHS.makeComplexFloat();
10473 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
10474 }
10475 } else {
10476 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
10477 }
George Burgess IVa145e252016-05-25 22:38:36 +000010478 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010479 return false;
10480
Chandler Carruthb29a7432014-10-11 11:03:30 +000010481 if (E->getRHS()->getType()->isRealFloatingType()) {
10482 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
10483 return false;
10484 RHS.makeComplexFloat();
10485 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
10486 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010487 return false;
10488
10489 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +000010490 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010491 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +000010492 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010493 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010494 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
10495 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010496 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010497 assert(IsEquality && "invalid complex comparison");
10498 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
10499 LHS.getComplexIntImag() == RHS.getComplexIntImag();
10500 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010501 }
10502 }
Mike Stump11289f42009-09-09 15:08:12 +000010503
Anders Carlssonacc79812008-11-16 07:17:21 +000010504 if (LHSTy->isRealFloatingType() &&
10505 RHSTy->isRealFloatingType()) {
10506 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +000010507
Richard Smith253c2a32012-01-27 01:14:48 +000010508 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010509 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +000010510 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010511
Richard Smith253c2a32012-01-27 01:14:48 +000010512 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +000010513 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010514
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010515 assert(E->isComparisonOp() && "Invalid binary operator!");
10516 auto GetCmpRes = [&]() {
10517 switch (LHS.compare(RHS)) {
10518 case APFloat::cmpEqual:
10519 return CCR::Equal;
10520 case APFloat::cmpLessThan:
10521 return CCR::Less;
10522 case APFloat::cmpGreaterThan:
10523 return CCR::Greater;
10524 case APFloat::cmpUnordered:
10525 return CCR::Unordered;
10526 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +000010527 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010528 };
10529 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +000010530 }
Mike Stump11289f42009-09-09 15:08:12 +000010531
Eli Friedmana38da572009-04-28 19:17:36 +000010532 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010533 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +000010534
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010535 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10536 if (!LHSOK && !Info.noteFailure())
10537 return false;
Eli Friedman64004332009-03-23 04:38:34 +000010538
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010539 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10540 return false;
Eli Friedman64004332009-03-23 04:38:34 +000010541
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010542 // Reject differing bases from the normal codepath; we special-case
10543 // comparisons to null.
10544 if (!HasSameBase(LHSValue, RHSValue)) {
10545 // Inequalities and subtractions between unrelated pointers have
10546 // unspecified or undefined behavior.
10547 if (!IsEquality)
10548 return Error(E);
10549 // A constant address may compare equal to the address of a symbol.
10550 // The one exception is that address of an object cannot compare equal
10551 // to a null pointer constant.
10552 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
10553 (!RHSValue.Base && !RHSValue.Offset.isZero()))
10554 return Error(E);
10555 // It's implementation-defined whether distinct literals will have
10556 // distinct addresses. In clang, the result of such a comparison is
10557 // unspecified, so it is not a constant expression. However, we do know
10558 // that the address of a literal will be non-null.
10559 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
10560 LHSValue.Base && RHSValue.Base)
10561 return Error(E);
10562 // We can't tell whether weak symbols will end up pointing to the same
10563 // object.
10564 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
10565 return Error(E);
10566 // We can't compare the address of the start of one object with the
10567 // past-the-end address of another object, per C++ DR1652.
10568 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
10569 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
10570 (RHSValue.Base && RHSValue.Offset.isZero() &&
10571 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
10572 return Error(E);
10573 // We can't tell whether an object is at the same address as another
10574 // zero sized object.
10575 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
10576 (LHSValue.Base && isZeroSized(RHSValue)))
10577 return Error(E);
10578 return Success(CCR::Nonequal, E);
10579 }
Eli Friedman64004332009-03-23 04:38:34 +000010580
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010581 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10582 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +000010583
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010584 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10585 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +000010586
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010587 // C++11 [expr.rel]p3:
10588 // Pointers to void (after pointer conversions) can be compared, with a
10589 // result defined as follows: If both pointers represent the same
10590 // address or are both the null pointer value, the result is true if the
10591 // operator is <= or >= and false otherwise; otherwise the result is
10592 // unspecified.
10593 // We interpret this as applying to pointers to *cv* void.
10594 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
10595 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +000010596
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010597 // C++11 [expr.rel]p2:
10598 // - If two pointers point to non-static data members of the same object,
10599 // or to subobjects or array elements fo such members, recursively, the
10600 // pointer to the later declared member compares greater provided the
10601 // two members have the same access control and provided their class is
10602 // not a union.
10603 // [...]
10604 // - Otherwise pointer comparisons are unspecified.
10605 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
10606 bool WasArrayIndex;
10607 unsigned Mismatch = FindDesignatorMismatch(
10608 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
10609 // At the point where the designators diverge, the comparison has a
10610 // specified value if:
10611 // - we are comparing array indices
10612 // - we are comparing fields of a union, or fields with the same access
10613 // Otherwise, the result is unspecified and thus the comparison is not a
10614 // constant expression.
10615 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
10616 Mismatch < RHSDesignator.Entries.size()) {
10617 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
10618 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
10619 if (!LF && !RF)
10620 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
10621 else if (!LF)
10622 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010623 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
10624 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010625 else if (!RF)
10626 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010627 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
10628 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010629 else if (!LF->getParent()->isUnion() &&
10630 LF->getAccess() != RF->getAccess())
10631 Info.CCEDiag(E,
10632 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010633 << LF << LF->getAccess() << RF << RF->getAccess()
10634 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +000010635 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +000010636 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010637
10638 // The comparison here must be unsigned, and performed with the same
10639 // width as the pointer.
10640 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
10641 uint64_t CompareLHS = LHSOffset.getQuantity();
10642 uint64_t CompareRHS = RHSOffset.getQuantity();
10643 assert(PtrSize <= 64 && "Unexpected pointer width");
10644 uint64_t Mask = ~0ULL >> (64 - PtrSize);
10645 CompareLHS &= Mask;
10646 CompareRHS &= Mask;
10647
10648 // If there is a base and this is a relational operator, we can only
10649 // compare pointers within the object in question; otherwise, the result
10650 // depends on where the object is located in memory.
10651 if (!LHSValue.Base.isNull() && IsRelational) {
10652 QualType BaseTy = getType(LHSValue.Base);
10653 if (BaseTy->isIncompleteType())
10654 return Error(E);
10655 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
10656 uint64_t OffsetLimit = Size.getQuantity();
10657 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
10658 return Error(E);
10659 }
10660
10661 if (CompareLHS < CompareRHS)
10662 return Success(CCR::Less, E);
10663 if (CompareLHS > CompareRHS)
10664 return Success(CCR::Greater, E);
10665 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +000010666 }
Richard Smith7bb00672012-02-01 01:42:44 +000010667
10668 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010669 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +000010670 assert(RHSTy->isMemberPointerType() && "invalid comparison");
10671
10672 MemberPtr LHSValue, RHSValue;
10673
10674 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010675 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +000010676 return false;
10677
10678 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10679 return false;
10680
10681 // C++11 [expr.eq]p2:
10682 // If both operands are null, they compare equal. Otherwise if only one is
10683 // null, they compare unequal.
10684 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
10685 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010686 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000010687 }
10688
10689 // Otherwise if either is a pointer to a virtual member function, the
10690 // result is unspecified.
10691 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
10692 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010693 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000010694 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
10695 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010696 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000010697
10698 // Otherwise they compare equal if and only if they would refer to the
10699 // same member of the same most derived object or the same subobject if
10700 // they were dereferenced with a hypothetical object of the associated
10701 // class type.
10702 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010703 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000010704 }
10705
Richard Smithab44d9b2012-02-14 22:35:28 +000010706 if (LHSTy->isNullPtrType()) {
10707 assert(E->isComparisonOp() && "unexpected nullptr operation");
10708 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10709 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10710 // are compared, the result is true of the operator is <=, >= or ==, and
10711 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010712 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +000010713 }
10714
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010715 return DoAfter();
10716}
10717
10718bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10719 if (!CheckLiteralType(Info, E))
10720 return false;
10721
10722 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10723 const BinaryOperator *E) {
10724 // Evaluation succeeded. Lookup the information for the comparison category
10725 // type and fetch the VarDecl for the result.
10726 const ComparisonCategoryInfo &CmpInfo =
10727 Info.Ctx.CompCategories.getInfoForType(E->getType());
10728 const VarDecl *VD =
10729 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10730 // Check and evaluate the result as a constant expression.
10731 LValue LV;
10732 LV.set(VD);
10733 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10734 return false;
10735 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10736 };
10737 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10738 return ExprEvaluatorBaseTy::VisitBinCmp(E);
10739 });
10740}
10741
10742bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10743 // We don't call noteFailure immediately because the assignment happens after
10744 // we evaluate LHS and RHS.
10745 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10746 return Error(E);
10747
10748 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10749 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10750 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10751
10752 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10753 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010754 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010755
10756 if (E->isComparisonOp()) {
10757 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10758 // comparisons and then translating the result.
10759 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10760 const BinaryOperator *E) {
10761 using CCR = ComparisonCategoryResult;
10762 bool IsEqual = ResKind == CCR::Equal,
10763 IsLess = ResKind == CCR::Less,
10764 IsGreater = ResKind == CCR::Greater;
10765 auto Op = E->getOpcode();
10766 switch (Op) {
10767 default:
10768 llvm_unreachable("unsupported binary operator");
10769 case BO_EQ:
10770 case BO_NE:
10771 return Success(IsEqual == (Op == BO_EQ), E);
10772 case BO_LT: return Success(IsLess, E);
10773 case BO_GT: return Success(IsGreater, E);
10774 case BO_LE: return Success(IsEqual || IsLess, E);
10775 case BO_GE: return Success(IsEqual || IsGreater, E);
10776 }
10777 };
10778 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10779 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10780 });
10781 }
10782
10783 QualType LHSTy = E->getLHS()->getType();
10784 QualType RHSTy = E->getRHS()->getType();
10785
10786 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10787 E->getOpcode() == BO_Sub) {
10788 LValue LHSValue, RHSValue;
10789
10790 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10791 if (!LHSOK && !Info.noteFailure())
10792 return false;
10793
10794 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10795 return false;
10796
10797 // Reject differing bases from the normal codepath; we special-case
10798 // comparisons to null.
10799 if (!HasSameBase(LHSValue, RHSValue)) {
10800 // Handle &&A - &&B.
10801 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10802 return Error(E);
10803 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10804 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10805 if (!LHSExpr || !RHSExpr)
10806 return Error(E);
10807 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10808 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10809 if (!LHSAddrExpr || !RHSAddrExpr)
10810 return Error(E);
10811 // Make sure both labels come from the same function.
10812 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10813 RHSAddrExpr->getLabel()->getDeclContext())
10814 return Error(E);
10815 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10816 }
10817 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10818 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10819
10820 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10821 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10822
10823 // C++11 [expr.add]p6:
10824 // Unless both pointers point to elements of the same array object, or
10825 // one past the last element of the array object, the behavior is
10826 // undefined.
10827 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10828 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10829 RHSDesignator))
10830 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10831
10832 QualType Type = E->getLHS()->getType();
10833 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10834
10835 CharUnits ElementSize;
10836 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10837 return false;
10838
10839 // As an extension, a type may have zero size (empty struct or union in
10840 // C, array of zero length). Pointer subtraction in such cases has
10841 // undefined behavior, so is not constant.
10842 if (ElementSize.isZero()) {
10843 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10844 << ElementType;
10845 return false;
10846 }
10847
10848 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10849 // and produce incorrect results when it overflows. Such behavior
10850 // appears to be non-conforming, but is common, so perhaps we should
10851 // assume the standard intended for such cases to be undefined behavior
10852 // and check for them.
10853
10854 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10855 // overflow in the final conversion to ptrdiff_t.
10856 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10857 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10858 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10859 false);
10860 APSInt TrueResult = (LHS - RHS) / ElemSize;
10861 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
10862
10863 if (Result.extend(65) != TrueResult &&
10864 !HandleOverflow(Info, E, TrueResult, E->getType()))
10865 return false;
10866 return Success(Result, E);
10867 }
10868
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010869 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +000010870}
10871
Peter Collingbournee190dee2011-03-11 19:24:49 +000010872/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10873/// a result as the expression's type.
10874bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10875 const UnaryExprOrTypeTraitExpr *E) {
10876 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +000010877 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +000010878 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +000010879 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +000010880 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10881 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000010882 else
Richard Smith6822bd72018-10-26 19:26:45 +000010883 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10884 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000010885 }
Eli Friedman64004332009-03-23 04:38:34 +000010886
Peter Collingbournee190dee2011-03-11 19:24:49 +000010887 case UETT_VecStep: {
10888 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +000010889
Peter Collingbournee190dee2011-03-11 19:24:49 +000010890 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +000010891 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +000010892
Peter Collingbournee190dee2011-03-11 19:24:49 +000010893 // The vec_step built-in functions that take a 3-component
10894 // vector return 4. (OpenCL 1.1 spec 6.11.12)
10895 if (n == 3)
10896 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +000010897
Peter Collingbournee190dee2011-03-11 19:24:49 +000010898 return Success(n, E);
10899 } else
10900 return Success(1, E);
10901 }
10902
10903 case UETT_SizeOf: {
10904 QualType SrcTy = E->getTypeOfArgument();
10905 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10906 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +000010907 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10908 SrcTy = Ref->getPointeeType();
10909
Richard Smithd62306a2011-11-10 06:34:14 +000010910 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +000010911 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +000010912 return false;
Richard Smithd62306a2011-11-10 06:34:14 +000010913 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000010914 }
Alexey Bataev00396512015-07-02 03:40:19 +000010915 case UETT_OpenMPRequiredSimdAlign:
10916 assert(E->isArgumentType());
10917 return Success(
10918 Info.Ctx.toCharUnitsFromBits(
10919 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10920 .getQuantity(),
10921 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000010922 }
10923
10924 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +000010925}
10926
Peter Collingbournee9200682011-05-13 03:29:01 +000010927bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +000010928 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +000010929 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +000010930 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010931 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +000010932 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +000010933 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +000010934 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +000010935 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +000010936 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +000010937 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +000010938 APSInt IdxResult;
10939 if (!EvaluateInteger(Idx, IdxResult, Info))
10940 return false;
10941 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10942 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010943 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010944 CurrentType = AT->getElementType();
10945 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10946 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +000010947 break;
Douglas Gregor882211c2010-04-28 22:16:22 +000010948 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010949
James Y Knight7281c352015-12-29 22:31:18 +000010950 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +000010951 FieldDecl *MemberDecl = ON.getField();
10952 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000010953 if (!RT)
10954 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010955 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000010956 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +000010957 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +000010958 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +000010959 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +000010960 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +000010961 CurrentType = MemberDecl->getType().getNonReferenceType();
10962 break;
10963 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010964
James Y Knight7281c352015-12-29 22:31:18 +000010965 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +000010966 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +000010967
James Y Knight7281c352015-12-29 22:31:18 +000010968 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +000010969 CXXBaseSpecifier *BaseSpec = ON.getBase();
10970 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +000010971 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000010972
10973 // Find the layout of the class whose base we are looking into.
10974 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000010975 if (!RT)
10976 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000010977 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000010978 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +000010979 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10980
10981 // Find the base class itself.
10982 CurrentType = BaseSpec->getType();
10983 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10984 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010985 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +000010986
Douglas Gregord1702062010-04-29 00:18:15 +000010987 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +000010988 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +000010989 break;
10990 }
Douglas Gregor882211c2010-04-28 22:16:22 +000010991 }
10992 }
Peter Collingbournee9200682011-05-13 03:29:01 +000010993 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010994}
10995
Chris Lattnere13042c2008-07-11 19:10:17 +000010996bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010997 switch (E->getOpcode()) {
10998 default:
10999 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
11000 // See C99 6.6p3.
11001 return Error(E);
11002 case UO_Extension:
11003 // FIXME: Should extension allow i-c-e extension expressions in its scope?
11004 // If so, we could clear the diagnostic ID.
11005 return Visit(E->getSubExpr());
11006 case UO_Plus:
11007 // The result is just the value.
11008 return Visit(E->getSubExpr());
11009 case UO_Minus: {
11010 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +000011011 return false;
11012 if (!Result.isInt()) return Error(E);
11013 const APSInt &Value = Result.getInt();
11014 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
11015 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
11016 E->getType()))
11017 return false;
Richard Smithfe800032012-01-31 04:08:20 +000011018 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011019 }
11020 case UO_Not: {
11021 if (!Visit(E->getSubExpr()))
11022 return false;
11023 if (!Result.isInt()) return Error(E);
11024 return Success(~Result.getInt(), E);
11025 }
11026 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +000011027 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +000011028 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +000011029 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +000011030 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +000011031 }
Anders Carlsson9c181652008-07-08 14:35:21 +000011032 }
Anders Carlsson9c181652008-07-08 14:35:21 +000011033}
Mike Stump11289f42009-09-09 15:08:12 +000011034
Chris Lattner477c4be2008-07-12 01:15:53 +000011035/// HandleCast - This is used to evaluate implicit or explicit casts where the
11036/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +000011037bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
11038 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000011039 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +000011040 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000011041
Eli Friedmanc757de22011-03-25 00:43:55 +000011042 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +000011043 case CK_BaseToDerived:
11044 case CK_DerivedToBase:
11045 case CK_UncheckedDerivedToBase:
11046 case CK_Dynamic:
11047 case CK_ToUnion:
11048 case CK_ArrayToPointerDecay:
11049 case CK_FunctionToPointerDecay:
11050 case CK_NullToPointer:
11051 case CK_NullToMemberPointer:
11052 case CK_BaseToDerivedMemberPointer:
11053 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +000011054 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +000011055 case CK_ConstructorConversion:
11056 case CK_IntegralToPointer:
11057 case CK_ToVoid:
11058 case CK_VectorSplat:
11059 case CK_IntegralToFloating:
11060 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000011061 case CK_CPointerToObjCPointerCast:
11062 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000011063 case CK_AnyPointerToBlockPointerCast:
11064 case CK_ObjCObjectLValueCast:
11065 case CK_FloatingRealToComplex:
11066 case CK_FloatingComplexToReal:
11067 case CK_FloatingComplexCast:
11068 case CK_FloatingComplexToIntegralComplex:
11069 case CK_IntegralRealToComplex:
11070 case CK_IntegralComplexCast:
11071 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +000011072 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000011073 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000011074 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000011075 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000011076 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000011077 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +000011078 case CK_IntegralToFixedPoint:
Eli Friedmanc757de22011-03-25 00:43:55 +000011079 llvm_unreachable("invalid cast kind for integral value");
11080
Eli Friedman9faf2f92011-03-25 19:07:11 +000011081 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000011082 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000011083 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +000011084 case CK_ARCProduceObject:
11085 case CK_ARCConsumeObject:
11086 case CK_ARCReclaimReturnedObject:
11087 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000011088 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011089 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011090
Richard Smith4ef685b2012-01-17 21:17:26 +000011091 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +000011092 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011093 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +000011094 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000011095 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000011096 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011097
11098 case CK_MemberPointerToBoolean:
11099 case CK_PointerToBoolean:
11100 case CK_IntegralToBoolean:
11101 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +000011102 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +000011103 case CK_FloatingComplexToBoolean:
11104 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011105 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +000011106 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +000011107 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +000011108 uint64_t IntResult = BoolResult;
11109 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
11110 IntResult = (uint64_t)-1;
11111 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +000011112 }
11113
Leonard Chan8f7caae2019-03-06 00:28:43 +000011114 case CK_FixedPointToIntegral: {
11115 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
11116 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11117 return false;
11118 bool Overflowed;
11119 llvm::APSInt Result = Src.convertToInt(
11120 Info.Ctx.getIntWidth(DestType),
11121 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
11122 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11123 return false;
11124 return Success(Result, E);
11125 }
11126
Leonard Chanb4ba4672018-10-23 17:55:35 +000011127 case CK_FixedPointToBoolean: {
11128 // Unsigned padding does not affect this.
11129 APValue Val;
11130 if (!Evaluate(Val, Info, SubExpr))
11131 return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000011132 return Success(Val.getFixedPoint().getBoolValue(), E);
Leonard Chanb4ba4672018-10-23 17:55:35 +000011133 }
11134
Eli Friedmanc757de22011-03-25 00:43:55 +000011135 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +000011136 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +000011137 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +000011138
Eli Friedman742421e2009-02-20 01:15:07 +000011139 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +000011140 // Allow casts of address-of-label differences if they are no-ops
11141 // or narrowing. (The narrowing case isn't actually guaranteed to
11142 // be constant-evaluatable except in some narrow cases which are hard
11143 // to detect here. We let it through on the assumption the user knows
11144 // what they are doing.)
11145 if (Result.isAddrLabelDiff())
11146 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +000011147 // Only allow casts of lvalues if they are lossless.
11148 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
11149 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +000011150
Richard Smith911e1422012-01-30 22:27:01 +000011151 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
11152 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +000011153 }
Mike Stump11289f42009-09-09 15:08:12 +000011154
Eli Friedmanc757de22011-03-25 00:43:55 +000011155 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +000011156 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
11157
John McCall45d55e42010-05-07 21:00:08 +000011158 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +000011159 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +000011160 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +000011161
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011162 if (LV.getLValueBase()) {
11163 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +000011164 // FIXME: Allow a larger integer size than the pointer size, and allow
11165 // narrowing back down to pointer width in subsequent integral casts.
11166 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011167 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011168 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +000011169
Richard Smithcf74da72011-11-16 07:18:12 +000011170 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +000011171 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011172 return true;
11173 }
11174
Hans Wennborgdd1ea8a2019-03-06 10:26:19 +000011175 APSInt AsInt;
11176 APValue V;
11177 LV.moveInto(V);
11178 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
11179 llvm_unreachable("Can't cast this!");
Yaxun Liu402804b2016-12-15 08:09:08 +000011180
Richard Smith911e1422012-01-30 22:27:01 +000011181 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +000011182 }
Eli Friedman9a156e52008-11-12 09:44:48 +000011183
Eli Friedmanc757de22011-03-25 00:43:55 +000011184 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +000011185 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000011186 if (!EvaluateComplex(SubExpr, C, Info))
11187 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +000011188 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000011189 }
Eli Friedmanc2b50172009-02-22 11:46:18 +000011190
Eli Friedmanc757de22011-03-25 00:43:55 +000011191 case CK_FloatingToIntegral: {
11192 APFloat F(0.0);
11193 if (!EvaluateFloat(SubExpr, F, Info))
11194 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +000011195
Richard Smith357362d2011-12-13 06:39:58 +000011196 APSInt Value;
11197 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
11198 return false;
11199 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011200 }
11201 }
Mike Stump11289f42009-09-09 15:08:12 +000011202
Eli Friedmanc757de22011-03-25 00:43:55 +000011203 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +000011204}
Anders Carlssonb5ad0212008-07-08 14:30:00 +000011205
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011206bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11207 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011208 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011209 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11210 return false;
11211 if (!LV.isComplexInt())
11212 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011213 return Success(LV.getComplexIntReal(), E);
11214 }
11215
11216 return Visit(E->getSubExpr());
11217}
11218
Eli Friedman4e7a2412009-02-27 04:45:43 +000011219bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011220 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011221 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011222 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11223 return false;
11224 if (!LV.isComplexInt())
11225 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011226 return Success(LV.getComplexIntImag(), E);
11227 }
11228
Richard Smith4a678122011-10-24 18:44:57 +000011229 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +000011230 return Success(0, E);
11231}
11232
Douglas Gregor820ba7b2011-01-04 17:33:58 +000011233bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
11234 return Success(E->getPackLength(), E);
11235}
11236
Sebastian Redl5f0180d2010-09-10 20:55:47 +000011237bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
11238 return Success(E->getValue(), E);
11239}
11240
Leonard Chandb01c3a2018-06-20 17:19:40 +000011241bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11242 switch (E->getOpcode()) {
11243 default:
11244 // Invalid unary operators
11245 return Error(E);
11246 case UO_Plus:
11247 // The result is just the value.
11248 return Visit(E->getSubExpr());
11249 case UO_Minus: {
11250 if (!Visit(E->getSubExpr())) return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000011251 if (!Result.isFixedPoint())
11252 return Error(E);
11253 bool Overflowed;
11254 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
11255 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
11256 return false;
11257 return Success(Negated, E);
Leonard Chandb01c3a2018-06-20 17:19:40 +000011258 }
11259 case UO_LNot: {
11260 bool bres;
11261 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11262 return false;
11263 return Success(!bres, E);
11264 }
11265 }
11266}
11267
Leonard Chand3f3e162019-01-18 21:04:25 +000011268bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
11269 const Expr *SubExpr = E->getSubExpr();
11270 QualType DestType = E->getType();
11271 assert(DestType->isFixedPointType() &&
11272 "Expected destination type to be a fixed point type");
11273 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
11274
11275 switch (E->getCastKind()) {
11276 case CK_FixedPointCast: {
11277 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
11278 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11279 return false;
11280 bool Overflowed;
11281 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
11282 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11283 return false;
11284 return Success(Result, E);
11285 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000011286 case CK_IntegralToFixedPoint: {
11287 APSInt Src;
11288 if (!EvaluateInteger(SubExpr, Src, Info))
11289 return false;
11290
11291 bool Overflowed;
11292 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11293 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
11294
11295 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
11296 return false;
11297
11298 return Success(IntResult, E);
11299 }
Leonard Chand3f3e162019-01-18 21:04:25 +000011300 case CK_NoOp:
11301 case CK_LValueToRValue:
11302 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11303 default:
11304 return Error(E);
11305 }
11306}
11307
11308bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11309 const Expr *LHS = E->getLHS();
11310 const Expr *RHS = E->getRHS();
11311 FixedPointSemantics ResultFXSema =
11312 Info.Ctx.getFixedPointSemantics(E->getType());
11313
11314 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
11315 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
11316 return false;
11317 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
11318 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
11319 return false;
11320
11321 switch (E->getOpcode()) {
11322 case BO_Add: {
11323 bool AddOverflow, ConversionOverflow;
11324 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
11325 .convert(ResultFXSema, &ConversionOverflow);
11326 if ((AddOverflow || ConversionOverflow) &&
11327 !HandleOverflow(Info, E, Result, E->getType()))
11328 return false;
11329 return Success(Result, E);
11330 }
11331 default:
11332 return false;
11333 }
11334 llvm_unreachable("Should've exited before this");
11335}
11336
Chris Lattner05706e882008-07-11 18:11:29 +000011337//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +000011338// Float Evaluation
11339//===----------------------------------------------------------------------===//
11340
11341namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000011342class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000011343 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +000011344 APFloat &Result;
11345public:
11346 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +000011347 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +000011348
Richard Smith2e312c82012-03-03 22:46:17 +000011349 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011350 Result = V.getFloat();
11351 return true;
11352 }
Eli Friedman24c01542008-08-22 00:06:13 +000011353
Richard Smithfddd3842011-12-30 21:15:51 +000011354 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +000011355 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
11356 return true;
11357 }
11358
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011359 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +000011360
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011361 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +000011362 bool VisitBinaryOperator(const BinaryOperator *E);
11363 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000011364 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +000011365
John McCallb1fb0d32010-05-07 22:08:54 +000011366 bool VisitUnaryReal(const UnaryOperator *E);
11367 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +000011368
Richard Smithfddd3842011-12-30 21:15:51 +000011369 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +000011370};
11371} // end anonymous namespace
11372
11373static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000011374 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +000011375 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +000011376}
11377
Jay Foad39c79802011-01-12 09:06:06 +000011378static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +000011379 QualType ResultTy,
11380 const Expr *Arg,
11381 bool SNaN,
11382 llvm::APFloat &Result) {
11383 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
11384 if (!S) return false;
11385
11386 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
11387
11388 llvm::APInt fill;
11389
11390 // Treat empty strings as if they were zero.
11391 if (S->getString().empty())
11392 fill = llvm::APInt(32, 0);
11393 else if (S->getString().getAsInteger(0, fill))
11394 return false;
11395
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +000011396 if (Context.getTargetInfo().isNan2008()) {
11397 if (SNaN)
11398 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11399 else
11400 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11401 } else {
11402 // Prior to IEEE 754-2008, architectures were allowed to choose whether
11403 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
11404 // a different encoding to what became a standard in 2008, and for pre-
11405 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
11406 // sNaN. This is now known as "legacy NaN" encoding.
11407 if (SNaN)
11408 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11409 else
11410 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11411 }
11412
John McCall16291492010-02-28 13:00:19 +000011413 return true;
11414}
11415
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011416bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000011417 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011418 default:
11419 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11420
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011421 case Builtin::BI__builtin_huge_val:
11422 case Builtin::BI__builtin_huge_valf:
11423 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011424 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011425 case Builtin::BI__builtin_inf:
11426 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011427 case Builtin::BI__builtin_infl:
11428 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000011429 const llvm::fltSemantics &Sem =
11430 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000011431 Result = llvm::APFloat::getInf(Sem);
11432 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000011433 }
Mike Stump11289f42009-09-09 15:08:12 +000011434
John McCall16291492010-02-28 13:00:19 +000011435 case Builtin::BI__builtin_nans:
11436 case Builtin::BI__builtin_nansf:
11437 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011438 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011439 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11440 true, Result))
11441 return Error(E);
11442 return true;
John McCall16291492010-02-28 13:00:19 +000011443
Chris Lattner0b7282e2008-10-06 06:31:58 +000011444 case Builtin::BI__builtin_nan:
11445 case Builtin::BI__builtin_nanf:
11446 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011447 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000011448 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000011449 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000011450 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11451 false, Result))
11452 return Error(E);
11453 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011454
11455 case Builtin::BI__builtin_fabs:
11456 case Builtin::BI__builtin_fabsf:
11457 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011458 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011459 if (!EvaluateFloat(E->getArg(0), Result, Info))
11460 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011461
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011462 if (Result.isNegative())
11463 Result.changeSign();
11464 return true;
11465
Richard Smith8889a3d2013-06-13 06:26:32 +000011466 // FIXME: Builtin::BI__builtin_powi
11467 // FIXME: Builtin::BI__builtin_powif
11468 // FIXME: Builtin::BI__builtin_powil
11469
Mike Stump11289f42009-09-09 15:08:12 +000011470 case Builtin::BI__builtin_copysign:
11471 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011472 case Builtin::BI__builtin_copysignl:
11473 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011474 APFloat RHS(0.);
11475 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
11476 !EvaluateFloat(E->getArg(1), RHS, Info))
11477 return false;
11478 Result.copySign(RHS);
11479 return true;
11480 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011481 }
11482}
11483
John McCallb1fb0d32010-05-07 22:08:54 +000011484bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000011485 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11486 ComplexValue CV;
11487 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11488 return false;
11489 Result = CV.FloatReal;
11490 return true;
11491 }
11492
11493 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000011494}
11495
11496bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000011497 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11498 ComplexValue CV;
11499 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11500 return false;
11501 Result = CV.FloatImag;
11502 return true;
11503 }
11504
Richard Smith4a678122011-10-24 18:44:57 +000011505 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000011506 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
11507 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000011508 return true;
11509}
11510
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011511bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011512 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011513 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000011514 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000011515 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000011516 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000011517 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
11518 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011519 Result.changeSign();
11520 return true;
11521 }
11522}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011523
Eli Friedman24c01542008-08-22 00:06:13 +000011524bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000011525 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11526 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000011527
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011528 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000011529 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000011530 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000011531 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000011532 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
11533 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000011534}
11535
11536bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
11537 Result = E->getValue();
11538 return true;
11539}
11540
Peter Collingbournee9200682011-05-13 03:29:01 +000011541bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
11542 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000011543
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011544 switch (E->getCastKind()) {
11545 default:
Richard Smith11562c52011-10-28 17:51:58 +000011546 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011547
11548 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011549 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000011550 return EvaluateInteger(SubExpr, IntResult, Info) &&
11551 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
11552 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000011553 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011554
11555 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011556 if (!Visit(SubExpr))
11557 return false;
Richard Smith357362d2011-12-13 06:39:58 +000011558 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
11559 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000011560 }
John McCalld7646252010-11-14 08:17:51 +000011561
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011562 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000011563 ComplexValue V;
11564 if (!EvaluateComplex(SubExpr, V, Info))
11565 return false;
11566 Result = V.getComplexFloatReal();
11567 return true;
11568 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011569 }
Eli Friedman9a156e52008-11-12 09:44:48 +000011570}
11571
Eli Friedman24c01542008-08-22 00:06:13 +000011572//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011573// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000011574//===----------------------------------------------------------------------===//
11575
11576namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000011577class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000011578 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000011579 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000011580
Anders Carlsson537969c2008-11-16 20:27:53 +000011581public:
John McCall93d91dc2010-05-07 17:22:02 +000011582 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000011583 : ExprEvaluatorBaseTy(info), Result(Result) {}
11584
Richard Smith2e312c82012-03-03 22:46:17 +000011585 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011586 Result.setFrom(V);
11587 return true;
11588 }
Mike Stump11289f42009-09-09 15:08:12 +000011589
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011590 bool ZeroInitialization(const Expr *E);
11591
Anders Carlsson537969c2008-11-16 20:27:53 +000011592 //===--------------------------------------------------------------------===//
11593 // Visitor Methods
11594 //===--------------------------------------------------------------------===//
11595
Peter Collingbournee9200682011-05-13 03:29:01 +000011596 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000011597 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000011598 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011599 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011600 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000011601};
11602} // end anonymous namespace
11603
John McCall93d91dc2010-05-07 17:22:02 +000011604static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
11605 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000011606 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000011607 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000011608}
11609
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011610bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000011611 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011612 if (ElemTy->isRealFloatingType()) {
11613 Result.makeComplexFloat();
11614 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
11615 Result.FloatReal = Zero;
11616 Result.FloatImag = Zero;
11617 } else {
11618 Result.makeComplexInt();
11619 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
11620 Result.IntReal = Zero;
11621 Result.IntImag = Zero;
11622 }
11623 return true;
11624}
11625
Peter Collingbournee9200682011-05-13 03:29:01 +000011626bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
11627 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011628
11629 if (SubExpr->getType()->isRealFloatingType()) {
11630 Result.makeComplexFloat();
11631 APFloat &Imag = Result.FloatImag;
11632 if (!EvaluateFloat(SubExpr, Imag, Info))
11633 return false;
11634
11635 Result.FloatReal = APFloat(Imag.getSemantics());
11636 return true;
11637 } else {
11638 assert(SubExpr->getType()->isIntegerType() &&
11639 "Unexpected imaginary literal.");
11640
11641 Result.makeComplexInt();
11642 APSInt &Imag = Result.IntImag;
11643 if (!EvaluateInteger(SubExpr, Imag, Info))
11644 return false;
11645
11646 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
11647 return true;
11648 }
11649}
11650
Peter Collingbournee9200682011-05-13 03:29:01 +000011651bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011652
John McCallfcef3cf2010-12-14 17:51:41 +000011653 switch (E->getCastKind()) {
11654 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011655 case CK_BaseToDerived:
11656 case CK_DerivedToBase:
11657 case CK_UncheckedDerivedToBase:
11658 case CK_Dynamic:
11659 case CK_ToUnion:
11660 case CK_ArrayToPointerDecay:
11661 case CK_FunctionToPointerDecay:
11662 case CK_NullToPointer:
11663 case CK_NullToMemberPointer:
11664 case CK_BaseToDerivedMemberPointer:
11665 case CK_DerivedToBaseMemberPointer:
11666 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000011667 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000011668 case CK_ConstructorConversion:
11669 case CK_IntegralToPointer:
11670 case CK_PointerToIntegral:
11671 case CK_PointerToBoolean:
11672 case CK_ToVoid:
11673 case CK_VectorSplat:
11674 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000011675 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000011676 case CK_IntegralToBoolean:
11677 case CK_IntegralToFloating:
11678 case CK_FloatingToIntegral:
11679 case CK_FloatingToBoolean:
11680 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000011681 case CK_CPointerToObjCPointerCast:
11682 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011683 case CK_AnyPointerToBlockPointerCast:
11684 case CK_ObjCObjectLValueCast:
11685 case CK_FloatingComplexToReal:
11686 case CK_FloatingComplexToBoolean:
11687 case CK_IntegralComplexToReal:
11688 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000011689 case CK_ARCProduceObject:
11690 case CK_ARCConsumeObject:
11691 case CK_ARCReclaimReturnedObject:
11692 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000011693 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000011694 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000011695 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000011696 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000011697 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000011698 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000011699 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000011700 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +000011701 case CK_FixedPointToIntegral:
11702 case CK_IntegralToFixedPoint:
John McCallfcef3cf2010-12-14 17:51:41 +000011703 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000011704
John McCallfcef3cf2010-12-14 17:51:41 +000011705 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011706 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000011707 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000011708 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000011709 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000011710
11711 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000011712 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011713 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011714 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000011715
11716 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011717 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000011718 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011719 return false;
11720
John McCallfcef3cf2010-12-14 17:51:41 +000011721 Result.makeComplexFloat();
11722 Result.FloatImag = APFloat(Real.getSemantics());
11723 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011724 }
11725
John McCallfcef3cf2010-12-14 17:51:41 +000011726 case CK_FloatingComplexCast: {
11727 if (!Visit(E->getSubExpr()))
11728 return false;
11729
11730 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11731 QualType From
11732 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11733
Richard Smith357362d2011-12-13 06:39:58 +000011734 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11735 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011736 }
11737
11738 case CK_FloatingComplexToIntegralComplex: {
11739 if (!Visit(E->getSubExpr()))
11740 return false;
11741
11742 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11743 QualType From
11744 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11745 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000011746 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11747 To, Result.IntReal) &&
11748 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11749 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011750 }
11751
11752 case CK_IntegralRealToComplex: {
11753 APSInt &Real = Result.IntReal;
11754 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11755 return false;
11756
11757 Result.makeComplexInt();
11758 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11759 return true;
11760 }
11761
11762 case CK_IntegralComplexCast: {
11763 if (!Visit(E->getSubExpr()))
11764 return false;
11765
11766 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11767 QualType From
11768 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11769
Richard Smith911e1422012-01-30 22:27:01 +000011770 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11771 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011772 return true;
11773 }
11774
11775 case CK_IntegralComplexToFloatingComplex: {
11776 if (!Visit(E->getSubExpr()))
11777 return false;
11778
Ted Kremenek28831752012-08-23 20:46:57 +000011779 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000011780 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000011781 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000011782 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000011783 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11784 To, Result.FloatReal) &&
11785 HandleIntToFloatCast(Info, E, From, Result.IntImag,
11786 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011787 }
11788 }
11789
11790 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011791}
11792
John McCall93d91dc2010-05-07 17:22:02 +000011793bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000011794 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000011795 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11796
Chandler Carrutha216cad2014-10-11 00:57:18 +000011797 // Track whether the LHS or RHS is real at the type system level. When this is
11798 // the case we can simplify our evaluation strategy.
11799 bool LHSReal = false, RHSReal = false;
11800
11801 bool LHSOK;
11802 if (E->getLHS()->getType()->isRealFloatingType()) {
11803 LHSReal = true;
11804 APFloat &Real = Result.FloatReal;
11805 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11806 if (LHSOK) {
11807 Result.makeComplexFloat();
11808 Result.FloatImag = APFloat(Real.getSemantics());
11809 }
11810 } else {
11811 LHSOK = Visit(E->getLHS());
11812 }
George Burgess IVa145e252016-05-25 22:38:36 +000011813 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000011814 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011815
John McCall93d91dc2010-05-07 17:22:02 +000011816 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011817 if (E->getRHS()->getType()->isRealFloatingType()) {
11818 RHSReal = true;
11819 APFloat &Real = RHS.FloatReal;
11820 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11821 return false;
11822 RHS.makeComplexFloat();
11823 RHS.FloatImag = APFloat(Real.getSemantics());
11824 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000011825 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011826
Chandler Carrutha216cad2014-10-11 00:57:18 +000011827 assert(!(LHSReal && RHSReal) &&
11828 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011829 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011830 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000011831 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011832 if (Result.isComplexFloat()) {
11833 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11834 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011835 if (LHSReal)
11836 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11837 else if (!RHSReal)
11838 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11839 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011840 } else {
11841 Result.getComplexIntReal() += RHS.getComplexIntReal();
11842 Result.getComplexIntImag() += RHS.getComplexIntImag();
11843 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011844 break;
John McCalle3027922010-08-25 11:45:40 +000011845 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011846 if (Result.isComplexFloat()) {
11847 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11848 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011849 if (LHSReal) {
11850 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11851 Result.getComplexFloatImag().changeSign();
11852 } else if (!RHSReal) {
11853 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11854 APFloat::rmNearestTiesToEven);
11855 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011856 } else {
11857 Result.getComplexIntReal() -= RHS.getComplexIntReal();
11858 Result.getComplexIntImag() -= RHS.getComplexIntImag();
11859 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011860 break;
John McCalle3027922010-08-25 11:45:40 +000011861 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011862 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000011863 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000011864 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000011865 // following naming scheme:
11866 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000011867 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011868 APFloat &A = LHS.getComplexFloatReal();
11869 APFloat &B = LHS.getComplexFloatImag();
11870 APFloat &C = RHS.getComplexFloatReal();
11871 APFloat &D = RHS.getComplexFloatImag();
11872 APFloat &ResR = Result.getComplexFloatReal();
11873 APFloat &ResI = Result.getComplexFloatImag();
11874 if (LHSReal) {
11875 assert(!RHSReal && "Cannot have two real operands for a complex op!");
11876 ResR = A * C;
11877 ResI = A * D;
11878 } else if (RHSReal) {
11879 ResR = C * A;
11880 ResI = C * B;
11881 } else {
11882 // In the fully general case, we need to handle NaNs and infinities
11883 // robustly.
11884 APFloat AC = A * C;
11885 APFloat BD = B * D;
11886 APFloat AD = A * D;
11887 APFloat BC = B * C;
11888 ResR = AC - BD;
11889 ResI = AD + BC;
11890 if (ResR.isNaN() && ResI.isNaN()) {
11891 bool Recalc = false;
11892 if (A.isInfinity() || B.isInfinity()) {
11893 A = APFloat::copySign(
11894 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11895 B = APFloat::copySign(
11896 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11897 if (C.isNaN())
11898 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11899 if (D.isNaN())
11900 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11901 Recalc = true;
11902 }
11903 if (C.isInfinity() || D.isInfinity()) {
11904 C = APFloat::copySign(
11905 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11906 D = APFloat::copySign(
11907 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11908 if (A.isNaN())
11909 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11910 if (B.isNaN())
11911 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11912 Recalc = true;
11913 }
11914 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11915 AD.isInfinity() || BC.isInfinity())) {
11916 if (A.isNaN())
11917 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11918 if (B.isNaN())
11919 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11920 if (C.isNaN())
11921 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11922 if (D.isNaN())
11923 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11924 Recalc = true;
11925 }
11926 if (Recalc) {
11927 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11928 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11929 }
11930 }
11931 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011932 } else {
John McCall93d91dc2010-05-07 17:22:02 +000011933 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000011934 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011935 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11936 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000011937 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011938 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11939 LHS.getComplexIntImag() * RHS.getComplexIntReal());
11940 }
11941 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011942 case BO_Div:
11943 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000011944 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000011945 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000011946 // following naming scheme:
11947 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011948 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011949 APFloat &A = LHS.getComplexFloatReal();
11950 APFloat &B = LHS.getComplexFloatImag();
11951 APFloat &C = RHS.getComplexFloatReal();
11952 APFloat &D = RHS.getComplexFloatImag();
11953 APFloat &ResR = Result.getComplexFloatReal();
11954 APFloat &ResI = Result.getComplexFloatImag();
11955 if (RHSReal) {
11956 ResR = A / C;
11957 ResI = B / C;
11958 } else {
11959 if (LHSReal) {
11960 // No real optimizations we can do here, stub out with zero.
11961 B = APFloat::getZero(A.getSemantics());
11962 }
11963 int DenomLogB = 0;
11964 APFloat MaxCD = maxnum(abs(C), abs(D));
11965 if (MaxCD.isFinite()) {
11966 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000011967 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11968 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011969 }
11970 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000011971 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11972 APFloat::rmNearestTiesToEven);
11973 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11974 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011975 if (ResR.isNaN() && ResI.isNaN()) {
11976 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11977 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11978 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11979 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11980 D.isFinite()) {
11981 A = APFloat::copySign(
11982 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11983 B = APFloat::copySign(
11984 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11985 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11986 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11987 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11988 C = APFloat::copySign(
11989 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11990 D = APFloat::copySign(
11991 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11992 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
11993 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
11994 }
11995 }
11996 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011997 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011998 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
11999 return Error(E, diag::note_expr_divide_by_zero);
12000
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012001 ComplexValue LHS = Result;
12002 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
12003 RHS.getComplexIntImag() * RHS.getComplexIntImag();
12004 Result.getComplexIntReal() =
12005 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
12006 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
12007 Result.getComplexIntImag() =
12008 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
12009 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
12010 }
12011 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000012012 }
12013
John McCall93d91dc2010-05-07 17:22:02 +000012014 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000012015}
12016
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012017bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12018 // Get the operand value into 'Result'.
12019 if (!Visit(E->getSubExpr()))
12020 return false;
12021
12022 switch (E->getOpcode()) {
12023 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000012024 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000012025 case UO_Extension:
12026 return true;
12027 case UO_Plus:
12028 // The result is always just the subexpr.
12029 return true;
12030 case UO_Minus:
12031 if (Result.isComplexFloat()) {
12032 Result.getComplexFloatReal().changeSign();
12033 Result.getComplexFloatImag().changeSign();
12034 }
12035 else {
12036 Result.getComplexIntReal() = -Result.getComplexIntReal();
12037 Result.getComplexIntImag() = -Result.getComplexIntImag();
12038 }
12039 return true;
12040 case UO_Not:
12041 if (Result.isComplexFloat())
12042 Result.getComplexFloatImag().changeSign();
12043 else
12044 Result.getComplexIntImag() = -Result.getComplexIntImag();
12045 return true;
12046 }
12047}
12048
Eli Friedmanc4b251d2012-01-10 04:58:17 +000012049bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
12050 if (E->getNumInits() == 2) {
12051 if (E->getType()->isComplexType()) {
12052 Result.makeComplexFloat();
12053 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
12054 return false;
12055 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
12056 return false;
12057 } else {
12058 Result.makeComplexInt();
12059 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
12060 return false;
12061 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
12062 return false;
12063 }
12064 return true;
12065 }
12066 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
12067}
12068
Anders Carlsson537969c2008-11-16 20:27:53 +000012069//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000012070// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
12071// implicit conversion.
12072//===----------------------------------------------------------------------===//
12073
12074namespace {
12075class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000012076 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000012077 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000012078 APValue &Result;
12079public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000012080 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
12081 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000012082
12083 bool Success(const APValue &V, const Expr *E) {
12084 Result = V;
12085 return true;
12086 }
12087
12088 bool ZeroInitialization(const Expr *E) {
12089 ImplicitValueInitExpr VIE(
12090 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000012091 // For atomic-qualified class (and array) types in C++, initialize the
12092 // _Atomic-wrapped subobject directly, in-place.
12093 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
12094 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000012095 }
12096
12097 bool VisitCastExpr(const CastExpr *E) {
12098 switch (E->getCastKind()) {
12099 default:
12100 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12101 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000012102 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
12103 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000012104 }
12105 }
12106};
12107} // end anonymous namespace
12108
Richard Smith64cb9ca2017-02-22 22:09:50 +000012109static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
12110 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000012111 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000012112 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000012113}
12114
12115//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000012116// Void expression evaluation, primarily for a cast to void on the LHS of a
12117// comma operator
12118//===----------------------------------------------------------------------===//
12119
12120namespace {
12121class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000012122 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000012123public:
12124 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
12125
Richard Smith2e312c82012-03-03 22:46:17 +000012126 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000012127
Richard Smith7cd577b2017-08-17 19:35:50 +000012128 bool ZeroInitialization(const Expr *E) { return true; }
12129
Richard Smith42d3af92011-12-07 00:43:50 +000012130 bool VisitCastExpr(const CastExpr *E) {
12131 switch (E->getCastKind()) {
12132 default:
12133 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12134 case CK_ToVoid:
12135 VisitIgnoredValue(E->getSubExpr());
12136 return true;
12137 }
12138 }
Hal Finkela8443c32014-07-17 14:49:58 +000012139
12140 bool VisitCallExpr(const CallExpr *E) {
12141 switch (E->getBuiltinCallee()) {
12142 default:
12143 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12144 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000012145 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000012146 // The argument is not evaluated!
12147 return true;
12148 }
12149 }
Richard Smith42d3af92011-12-07 00:43:50 +000012150};
12151} // end anonymous namespace
12152
12153static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
12154 assert(E->isRValue() && E->getType()->isVoidType());
12155 return VoidExprEvaluator(Info).Visit(E);
12156}
12157
12158//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000012159// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000012160//===----------------------------------------------------------------------===//
12161
Richard Smith2e312c82012-03-03 22:46:17 +000012162static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000012163 // In C, function designators are not lvalues, but we evaluate them as if they
12164 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000012165 QualType T = E->getType();
12166 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000012167 LValue LV;
12168 if (!EvaluateLValue(E, LV, Info))
12169 return false;
12170 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000012171 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000012172 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000012173 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012174 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000012175 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012176 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012177 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000012178 LValue LV;
12179 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012180 return false;
Richard Smith725810a2011-10-16 21:26:27 +000012181 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000012182 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000012183 llvm::APFloat F(0.0);
12184 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012185 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000012186 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000012187 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000012188 ComplexValue C;
12189 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012190 return false;
Richard Smith725810a2011-10-16 21:26:27 +000012191 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000012192 } else if (T->isFixedPointType()) {
12193 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012194 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000012195 MemberPtr P;
12196 if (!EvaluateMemberPointer(E, P, Info))
12197 return false;
12198 P.moveInto(Result);
12199 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000012200 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000012201 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000012202 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000012203 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000012204 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000012205 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000012206 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000012207 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000012208 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000012209 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000012210 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000012211 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000012212 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012213 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000012214 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000012215 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000012216 if (!EvaluateVoid(E, Info))
12217 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012218 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000012219 QualType Unqual = T.getAtomicUnqualifiedType();
12220 if (Unqual->isArrayType() || Unqual->isRecordType()) {
12221 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000012222 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012223 if (!EvaluateAtomic(E, &LV, Value, Info))
12224 return false;
12225 } else {
12226 if (!EvaluateAtomic(E, nullptr, Result, Info))
12227 return false;
12228 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012229 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000012230 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000012231 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012232 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000012233 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000012234 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012235 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012236
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000012237 return true;
12238}
12239
Richard Smithb228a862012-02-15 02:18:13 +000012240/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
12241/// cases, the in-place evaluation is essential, since later initializers for
12242/// an object can indirectly refer to subobjects which were initialized earlier.
12243static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000012244 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000012245 assert(!E->isValueDependent());
12246
Richard Smith7525ff62013-05-09 07:14:00 +000012247 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000012248 return false;
12249
12250 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000012251 // Evaluate arrays and record types in-place, so that later initializers can
12252 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000012253 QualType T = E->getType();
12254 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000012255 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012256 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000012257 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012258 else if (T->isAtomicType()) {
12259 QualType Unqual = T.getAtomicUnqualifiedType();
12260 if (Unqual->isArrayType() || Unqual->isRecordType())
12261 return EvaluateAtomic(E, &This, Result, Info);
12262 }
Richard Smithed5165f2011-11-04 05:33:44 +000012263 }
12264
12265 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000012266 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000012267}
12268
Richard Smithf57d8cb2011-12-09 22:58:01 +000012269/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
12270/// lvalue-to-rvalue cast if it is an lvalue.
12271static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000012272 if (E->getType().isNull())
12273 return false;
12274
Nick Lewyckyc190f962017-05-02 01:06:16 +000012275 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000012276 return false;
12277
Richard Smith2e312c82012-03-03 22:46:17 +000012278 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000012279 return false;
12280
12281 if (E->isGLValue()) {
12282 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000012283 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000012284 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000012285 return false;
12286 }
12287
Richard Smith2e312c82012-03-03 22:46:17 +000012288 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000012289 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000012290}
Richard Smith11562c52011-10-28 17:51:58 +000012291
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012292static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000012293 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012294 // Fast-path evaluations of integer literals, since we sometimes see files
12295 // containing vast quantities of these.
12296 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
12297 Result.Val = APValue(APSInt(L->getValue(),
12298 L->getType()->isUnsignedIntegerType()));
12299 IsConst = true;
12300 return true;
12301 }
James Dennett0492ef02014-03-14 17:44:10 +000012302
12303 // This case should be rare, but we need to check it before we check on
12304 // the type below.
12305 if (Exp->getType().isNull()) {
12306 IsConst = false;
12307 return true;
12308 }
Fangrui Song6907ce22018-07-30 19:24:48 +000012309
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012310 // FIXME: Evaluating values of large array and record types can cause
12311 // performance problems. Only do so in C++11 for now.
12312 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
12313 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000012314 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012315 IsConst = false;
12316 return true;
12317 }
12318 return false;
12319}
12320
Fangrui Song407659a2018-11-30 23:41:18 +000012321static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
12322 Expr::SideEffectsKind SEK) {
12323 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
12324 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
12325}
12326
12327static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
12328 const ASTContext &Ctx, EvalInfo &Info) {
12329 bool IsConst;
12330 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
12331 return IsConst;
12332
12333 return EvaluateAsRValue(Info, E, Result.Val);
12334}
12335
12336static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
12337 const ASTContext &Ctx,
12338 Expr::SideEffectsKind AllowSideEffects,
12339 EvalInfo &Info) {
12340 if (!E->getType()->isIntegralOrEnumerationType())
12341 return false;
12342
12343 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
12344 !ExprResult.Val.isInt() ||
12345 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12346 return false;
12347
12348 return true;
12349}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012350
Leonard Chand3f3e162019-01-18 21:04:25 +000012351static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
12352 const ASTContext &Ctx,
12353 Expr::SideEffectsKind AllowSideEffects,
12354 EvalInfo &Info) {
12355 if (!E->getType()->isFixedPointType())
12356 return false;
12357
12358 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
12359 return false;
12360
12361 if (!ExprResult.Val.isFixedPoint() ||
12362 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12363 return false;
12364
12365 return true;
12366}
12367
Richard Smith7b553f12011-10-29 00:50:52 +000012368/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000012369/// any crazy technique (that has nothing to do with language standards) that
12370/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000012371/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
12372/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000012373bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
12374 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012375 assert(!isValueDependent() &&
12376 "Expression evaluator can't be called on a dependent expression.");
Richard Smith6d4c6582013-11-05 22:18:15 +000012377 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000012378 Info.InConstantContext = InConstantContext;
12379 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000012380}
12381
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012382bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
12383 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012384 assert(!isValueDependent() &&
12385 "Expression evaluator can't be called on a dependent expression.");
Richard Smith11562c52011-10-28 17:51:58 +000012386 EvalResult Scratch;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012387 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
Richard Smith2e312c82012-03-03 22:46:17 +000012388 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000012389}
12390
Fangrui Song407659a2018-11-30 23:41:18 +000012391bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012392 SideEffectsKind AllowSideEffects,
12393 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012394 assert(!isValueDependent() &&
12395 "Expression evaluator can't be called on a dependent expression.");
Fangrui Song407659a2018-11-30 23:41:18 +000012396 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012397 Info.InConstantContext = InConstantContext;
Fangrui Song407659a2018-11-30 23:41:18 +000012398 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000012399}
12400
Leonard Chand3f3e162019-01-18 21:04:25 +000012401bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012402 SideEffectsKind AllowSideEffects,
12403 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012404 assert(!isValueDependent() &&
12405 "Expression evaluator can't be called on a dependent expression.");
Leonard Chand3f3e162019-01-18 21:04:25 +000012406 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012407 Info.InConstantContext = InConstantContext;
Leonard Chand3f3e162019-01-18 21:04:25 +000012408 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
12409}
12410
Richard Trieube234c32016-04-21 21:04:55 +000012411bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012412 SideEffectsKind AllowSideEffects,
12413 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012414 assert(!isValueDependent() &&
12415 "Expression evaluator can't be called on a dependent expression.");
12416
Richard Trieube234c32016-04-21 21:04:55 +000012417 if (!getType()->isRealFloatingType())
12418 return false;
12419
12420 EvalResult ExprResult;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012421 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
12422 !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000012423 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000012424 return false;
12425
12426 Result = ExprResult.Val.getFloat();
12427 return true;
12428}
12429
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012430bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
12431 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012432 assert(!isValueDependent() &&
12433 "Expression evaluator can't be called on a dependent expression.");
12434
Richard Smith6d4c6582013-11-05 22:18:15 +000012435 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012436 Info.InConstantContext = InConstantContext;
John McCall45d55e42010-05-07 21:00:08 +000012437 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000012438 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
12439 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000012440 Ctx.getLValueReferenceType(getType()), LV,
12441 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000012442 return false;
12443
Richard Smith2e312c82012-03-03 22:46:17 +000012444 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000012445 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000012446}
12447
Reid Kleckner1a840d22018-05-10 18:57:35 +000012448bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
12449 const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012450 assert(!isValueDependent() &&
12451 "Expression evaluator can't be called on a dependent expression.");
12452
Reid Kleckner1a840d22018-05-10 18:57:35 +000012453 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
12454 EvalInfo Info(Ctx, Result, EM);
Eric Fiselier680e8652019-03-08 22:06:48 +000012455 Info.InConstantContext = true;
Eric Fiselieradd16a82019-04-24 02:23:30 +000012456
Reid Kleckner1a840d22018-05-10 18:57:35 +000012457 if (!::Evaluate(Result.Val, Info, this))
12458 return false;
12459
12460 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
12461 Usage);
12462}
12463
Richard Smithd0b4dd62011-12-19 06:19:21 +000012464bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
12465 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012466 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012467 assert(!isValueDependent() &&
12468 "Expression evaluator can't be called on a dependent expression.");
12469
Richard Smithdafff942012-01-14 04:30:29 +000012470 // FIXME: Evaluating initializers for large array and record types can cause
12471 // performance problems. Only do so in C++11 for now.
12472 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012473 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000012474 return false;
12475
Richard Smithd0b4dd62011-12-19 06:19:21 +000012476 Expr::EvalStatus EStatus;
12477 EStatus.Diag = &Notes;
12478
Richard Smith0c6124b2015-12-03 01:36:22 +000012479 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
12480 ? EvalInfo::EM_ConstantExpression
12481 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000012482 InitInfo.setEvaluatingDecl(VD, Value);
Fangrui Song407659a2018-11-30 23:41:18 +000012483 InitInfo.InConstantContext = true;
Richard Smithd0b4dd62011-12-19 06:19:21 +000012484
12485 LValue LVal;
12486 LVal.set(VD);
12487
Richard Smithfddd3842011-12-30 21:15:51 +000012488 // C++11 [basic.start.init]p2:
12489 // Variables with static storage duration or thread storage duration shall be
12490 // zero-initialized before any other initialization takes place.
12491 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012492 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000012493 !VD->getType()->isReferenceType()) {
12494 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000012495 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000012496 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000012497 return false;
12498 }
12499
Richard Smith7525ff62013-05-09 07:14:00 +000012500 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
12501 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000012502 EStatus.HasSideEffects)
12503 return false;
12504
12505 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
12506 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000012507}
12508
Richard Smith7b553f12011-10-29 00:50:52 +000012509/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
12510/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000012511bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012512 assert(!isValueDependent() &&
12513 "Expression evaluator can't be called on a dependent expression.");
12514
Anders Carlsson5b3638b2008-12-01 06:44:05 +000012515 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000012516 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000012517 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000012518}
Anders Carlsson59689ed2008-11-22 21:04:56 +000012519
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000012520APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012521 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012522 assert(!isValueDependent() &&
12523 "Expression evaluator can't be called on a dependent expression.");
12524
Fangrui Song407659a2018-11-30 23:41:18 +000012525 EvalResult EVResult;
12526 EVResult.Diag = Diag;
12527 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12528 Info.InConstantContext = true;
12529
12530 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000012531 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000012532 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000012533 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000012534
Fangrui Song407659a2018-11-30 23:41:18 +000012535 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000012536}
John McCall864e3962010-05-07 05:32:02 +000012537
David Bolvansky3b6ae572018-10-18 20:49:06 +000012538APSInt Expr::EvaluateKnownConstIntCheckOverflow(
12539 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012540 assert(!isValueDependent() &&
12541 "Expression evaluator can't be called on a dependent expression.");
12542
Fangrui Song407659a2018-11-30 23:41:18 +000012543 EvalResult EVResult;
12544 EVResult.Diag = Diag;
12545 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12546 Info.InConstantContext = true;
12547
12548 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000012549 (void)Result;
12550 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000012551 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000012552
Fangrui Song407659a2018-11-30 23:41:18 +000012553 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000012554}
12555
Richard Smithe9ff7702013-11-05 22:23:30 +000012556void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012557 assert(!isValueDependent() &&
12558 "Expression evaluator can't be called on a dependent expression.");
12559
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012560 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000012561 EvalResult EVResult;
12562 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
12563 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12564 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012565 }
12566}
12567
Richard Smithe6c01442013-06-05 00:46:14 +000012568bool Expr::EvalResult::isGlobalLValue() const {
12569 assert(Val.isLValue());
12570 return IsGlobalLValue(Val.getLValueBase());
12571}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000012572
12573
John McCall864e3962010-05-07 05:32:02 +000012574/// isIntegerConstantExpr - this recursive routine will test if an expression is
12575/// an integer constant expression.
12576
12577/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
12578/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000012579
12580// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000012581// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
12582// and a (possibly null) SourceLocation indicating the location of the problem.
12583//
John McCall864e3962010-05-07 05:32:02 +000012584// Note that to reduce code duplication, this helper does no evaluation
12585// itself; the caller checks whether the expression is evaluatable, and
12586// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000012587// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000012588
Dan Gohman28ade552010-07-26 21:25:24 +000012589namespace {
12590
Richard Smith9e575da2012-12-28 13:25:52 +000012591enum ICEKind {
12592 /// This expression is an ICE.
12593 IK_ICE,
12594 /// This expression is not an ICE, but if it isn't evaluated, it's
12595 /// a legal subexpression for an ICE. This return value is used to handle
12596 /// the comma operator in C99 mode, and non-constant subexpressions.
12597 IK_ICEIfUnevaluated,
12598 /// This expression is not an ICE, and is not a legal subexpression for one.
12599 IK_NotICE
12600};
12601
John McCall864e3962010-05-07 05:32:02 +000012602struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000012603 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000012604 SourceLocation Loc;
12605
Richard Smith9e575da2012-12-28 13:25:52 +000012606 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000012607};
12608
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012609}
Dan Gohman28ade552010-07-26 21:25:24 +000012610
Richard Smith9e575da2012-12-28 13:25:52 +000012611static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
12612
12613static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000012614
Craig Toppera31a8822013-08-22 07:09:37 +000012615static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000012616 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000012617 Expr::EvalStatus Status;
12618 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12619
12620 Info.InConstantContext = true;
12621 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000012622 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012623 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000012624
John McCall864e3962010-05-07 05:32:02 +000012625 return NoDiag();
12626}
12627
Craig Toppera31a8822013-08-22 07:09:37 +000012628static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000012629 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000012630 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012631 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012632
12633 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000012634#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000012635#define STMT(Node, Base) case Expr::Node##Class:
12636#define EXPR(Node, Base)
12637#include "clang/AST/StmtNodes.inc"
12638 case Expr::PredefinedExprClass:
12639 case Expr::FloatingLiteralClass:
12640 case Expr::ImaginaryLiteralClass:
12641 case Expr::StringLiteralClass:
12642 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000012643 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000012644 case Expr::MemberExprClass:
12645 case Expr::CompoundAssignOperatorClass:
12646 case Expr::CompoundLiteralExprClass:
12647 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000012648 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000012649 case Expr::ArrayInitLoopExprClass:
12650 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000012651 case Expr::NoInitExprClass:
12652 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000012653 case Expr::ImplicitValueInitExprClass:
12654 case Expr::ParenListExprClass:
12655 case Expr::VAArgExprClass:
12656 case Expr::AddrLabelExprClass:
12657 case Expr::StmtExprClass:
12658 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000012659 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000012660 case Expr::CXXDynamicCastExprClass:
12661 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000012662 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000012663 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000012664 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000012665 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000012666 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012667 case Expr::CXXThisExprClass:
12668 case Expr::CXXThrowExprClass:
12669 case Expr::CXXNewExprClass:
12670 case Expr::CXXDeleteExprClass:
12671 case Expr::CXXPseudoDestructorExprClass:
12672 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000012673 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000012674 case Expr::DependentScopeDeclRefExprClass:
12675 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000012676 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000012677 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000012678 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000012679 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000012680 case Expr::CXXTemporaryObjectExprClass:
12681 case Expr::CXXUnresolvedConstructExprClass:
12682 case Expr::CXXDependentScopeMemberExprClass:
12683 case Expr::UnresolvedMemberExprClass:
12684 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000012685 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012686 case Expr::ObjCArrayLiteralClass:
12687 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012688 case Expr::ObjCEncodeExprClass:
12689 case Expr::ObjCMessageExprClass:
12690 case Expr::ObjCSelectorExprClass:
12691 case Expr::ObjCProtocolExprClass:
12692 case Expr::ObjCIvarRefExprClass:
12693 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012694 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000012695 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000012696 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000012697 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000012698 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000012699 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000012700 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000012701 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000012702 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000012703 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000012704 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000012705 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000012706 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000012707 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000012708 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000012709 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000012710 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000012711 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000012712 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000012713 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000012714 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012715 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000012716
Richard Smithf137f932014-01-25 20:50:08 +000012717 case Expr::InitListExprClass: {
12718 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
12719 // form "T x = { a };" is equivalent to "T x = a;".
12720 // Unless we're initializing a reference, T is a scalar as it is known to be
12721 // of integral or enumeration type.
12722 if (E->isRValue())
12723 if (cast<InitListExpr>(E)->getNumInits() == 1)
12724 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012725 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000012726 }
12727
Douglas Gregor820ba7b2011-01-04 17:33:58 +000012728 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000012729 case Expr::GNUNullExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +000012730 case Expr::SourceLocExprClass:
John McCall864e3962010-05-07 05:32:02 +000012731 return NoDiag();
12732
John McCall7c454bb2011-07-15 05:09:51 +000012733 case Expr::SubstNonTypeTemplateParmExprClass:
12734 return
12735 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12736
Bill Wendling7c44da22018-10-31 03:48:47 +000012737 case Expr::ConstantExprClass:
12738 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12739
John McCall864e3962010-05-07 05:32:02 +000012740 case Expr::ParenExprClass:
12741 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000012742 case Expr::GenericSelectionExprClass:
12743 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012744 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000012745 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012746 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012747 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000012748 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000012749 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000012750 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000012751 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000012752 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000012753 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000012754 return NoDiag();
12755 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000012756 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000012757 // C99 6.6/3 allows function calls within unevaluated subexpressions of
12758 // constant expressions, but they can never be ICEs because an ICE cannot
12759 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000012760 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000012761 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000012762 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012763 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012764 }
Richard Smith6365c912012-02-24 22:12:32 +000012765 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000012766 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12767 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000012768 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012769 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000012770 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000012771 // Parameter variables are never constants. Without this check,
12772 // getAnyInitializer() can find a default argument, which leads
12773 // to chaos.
12774 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000012775 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000012776
12777 // C++ 7.1.5.1p2
12778 // A variable of non-volatile const-qualified integral or enumeration
12779 // type initialized by an ICE can be used in ICEs.
12780 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000012781 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000012782 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000012783
Richard Smithd0b4dd62011-12-19 06:19:21 +000012784 const VarDecl *VD;
12785 // Look for a declaration of this variable that has an initializer, and
12786 // check whether it is an ICE.
12787 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12788 return NoDiag();
12789 else
Richard Smith9e575da2012-12-28 13:25:52 +000012790 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000012791 }
12792 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012793 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000012794 }
John McCall864e3962010-05-07 05:32:02 +000012795 case Expr::UnaryOperatorClass: {
12796 const UnaryOperator *Exp = cast<UnaryOperator>(E);
12797 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000012798 case UO_PostInc:
12799 case UO_PostDec:
12800 case UO_PreInc:
12801 case UO_PreDec:
12802 case UO_AddrOf:
12803 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000012804 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000012805 // C99 6.6/3 allows increment and decrement within unevaluated
12806 // subexpressions of constant expressions, but they can never be ICEs
12807 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012808 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000012809 case UO_Extension:
12810 case UO_LNot:
12811 case UO_Plus:
12812 case UO_Minus:
12813 case UO_Not:
12814 case UO_Real:
12815 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000012816 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012817 }
Reid Klecknere540d972018-11-01 17:51:48 +000012818 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000012819 }
12820 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000012821 // Note that per C99, offsetof must be an ICE. And AFAIK, using
12822 // EvaluateAsRValue matches the proposed gcc behavior for cases like
12823 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
12824 // compliance: we should warn earlier for offsetof expressions with
12825 // array subscripts that aren't ICEs, and if the array subscripts
12826 // are ICEs, the value of the offsetof must be an integer constant.
12827 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000012828 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000012829 case Expr::UnaryExprOrTypeTraitExprClass: {
12830 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12831 if ((Exp->getKind() == UETT_SizeOf) &&
12832 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012833 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012834 return NoDiag();
12835 }
12836 case Expr::BinaryOperatorClass: {
12837 const BinaryOperator *Exp = cast<BinaryOperator>(E);
12838 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000012839 case BO_PtrMemD:
12840 case BO_PtrMemI:
12841 case BO_Assign:
12842 case BO_MulAssign:
12843 case BO_DivAssign:
12844 case BO_RemAssign:
12845 case BO_AddAssign:
12846 case BO_SubAssign:
12847 case BO_ShlAssign:
12848 case BO_ShrAssign:
12849 case BO_AndAssign:
12850 case BO_XorAssign:
12851 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000012852 // C99 6.6/3 allows assignments within unevaluated subexpressions of
12853 // constant expressions, but they can never be ICEs because an ICE cannot
12854 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012855 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012856
John McCalle3027922010-08-25 11:45:40 +000012857 case BO_Mul:
12858 case BO_Div:
12859 case BO_Rem:
12860 case BO_Add:
12861 case BO_Sub:
12862 case BO_Shl:
12863 case BO_Shr:
12864 case BO_LT:
12865 case BO_GT:
12866 case BO_LE:
12867 case BO_GE:
12868 case BO_EQ:
12869 case BO_NE:
12870 case BO_And:
12871 case BO_Xor:
12872 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000012873 case BO_Comma:
12874 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000012875 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12876 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000012877 if (Exp->getOpcode() == BO_Div ||
12878 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000012879 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000012880 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000012881 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000012882 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000012883 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012884 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012885 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000012886 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000012887 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012888 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012889 }
12890 }
12891 }
John McCalle3027922010-08-25 11:45:40 +000012892 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012893 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000012894 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12895 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000012896 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012897 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012898 } else {
12899 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012900 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012901 }
12902 }
Richard Smith9e575da2012-12-28 13:25:52 +000012903 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000012904 }
John McCalle3027922010-08-25 11:45:40 +000012905 case BO_LAnd:
12906 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000012907 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12908 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012909 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000012910 // Rare case where the RHS has a comma "side-effect"; we need
12911 // to actually check the condition to see whether the side
12912 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000012913 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000012914 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000012915 return RHSResult;
12916 return NoDiag();
12917 }
12918
Richard Smith9e575da2012-12-28 13:25:52 +000012919 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000012920 }
12921 }
Reid Klecknere540d972018-11-01 17:51:48 +000012922 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000012923 }
12924 case Expr::ImplicitCastExprClass:
12925 case Expr::CStyleCastExprClass:
12926 case Expr::CXXFunctionalCastExprClass:
12927 case Expr::CXXStaticCastExprClass:
12928 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000012929 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000012930 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000012931 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000012932 if (isa<ExplicitCastExpr>(E)) {
12933 if (const FloatingLiteral *FL
12934 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12935 unsigned DestWidth = Ctx.getIntWidth(E->getType());
12936 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12937 APSInt IgnoredVal(DestWidth, !DestSigned);
12938 bool Ignored;
12939 // If the value does not fit in the destination type, the behavior is
12940 // undefined, so we are not required to treat it as a constant
12941 // expression.
12942 if (FL->getValue().convertToInteger(IgnoredVal,
12943 llvm::APFloat::rmTowardZero,
12944 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012945 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000012946 return NoDiag();
12947 }
12948 }
Eli Friedman76d4e432011-09-29 21:49:34 +000012949 switch (cast<CastExpr>(E)->getCastKind()) {
12950 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000012951 case CK_AtomicToNonAtomic:
12952 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000012953 case CK_NoOp:
12954 case CK_IntegralToBoolean:
12955 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000012956 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000012957 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012958 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000012959 }
John McCall864e3962010-05-07 05:32:02 +000012960 }
John McCallc07a0c72011-02-17 10:25:35 +000012961 case Expr::BinaryConditionalOperatorClass: {
12962 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12963 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012964 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000012965 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012966 if (FalseResult.Kind == IK_NotICE) return FalseResult;
12967 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12968 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000012969 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000012970 return FalseResult;
12971 }
John McCall864e3962010-05-07 05:32:02 +000012972 case Expr::ConditionalOperatorClass: {
12973 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12974 // If the condition (ignoring parens) is a __builtin_constant_p call,
12975 // then only the true side is actually considered in an integer constant
12976 // expression, and it is fully evaluated. This is an important GNU
12977 // extension. See GCC PR38377 for discussion.
12978 if (const CallExpr *CallCE
12979 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000012980 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000012981 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000012982 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012983 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012984 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000012985
Richard Smithf57d8cb2011-12-09 22:58:01 +000012986 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12987 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000012988
Richard Smith9e575da2012-12-28 13:25:52 +000012989 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012990 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012991 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012992 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012993 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000012994 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012995 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000012996 return NoDiag();
12997 // Rare case where the diagnostics depend on which side is evaluated
12998 // Note that if we get here, CondResult is 0, and at least one of
12999 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000013000 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000013001 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000013002 return TrueResult;
13003 }
13004 case Expr::CXXDefaultArgExprClass:
13005 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000013006 case Expr::CXXDefaultInitExprClass:
13007 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013008 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000013009 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000013010 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000013011 case Expr::BuiltinBitCastExprClass: {
13012 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
13013 return ICEDiag(IK_NotICE, E->getBeginLoc());
13014 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
13015 }
John McCall864e3962010-05-07 05:32:02 +000013016 }
13017
David Blaikiee4d798f2012-01-20 21:50:17 +000013018 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000013019}
13020
Richard Smithf57d8cb2011-12-09 22:58:01 +000013021/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000013022static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000013023 const Expr *E,
13024 llvm::APSInt *Value,
13025 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000013026 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000013027 if (Loc) *Loc = E->getExprLoc();
13028 return false;
13029 }
13030
Richard Smith66e05fe2012-01-18 05:21:49 +000013031 APValue Result;
13032 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000013033 return false;
13034
Richard Smith98710fc2014-11-13 23:03:19 +000013035 if (!Result.isInt()) {
13036 if (Loc) *Loc = E->getExprLoc();
13037 return false;
13038 }
13039
Richard Smith66e05fe2012-01-18 05:21:49 +000013040 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000013041 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000013042}
13043
Craig Toppera31a8822013-08-22 07:09:37 +000013044bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
13045 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013046 assert(!isValueDependent() &&
13047 "Expression evaluator can't be called on a dependent expression.");
13048
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013049 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000013050 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000013051
Richard Smith9e575da2012-12-28 13:25:52 +000013052 ICEDiag D = CheckICE(this, Ctx);
13053 if (D.Kind != IK_ICE) {
13054 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000013055 return false;
13056 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000013057 return true;
13058}
13059
Craig Toppera31a8822013-08-22 07:09:37 +000013060bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000013061 SourceLocation *Loc, bool isEvaluated) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013062 assert(!isValueDependent() &&
13063 "Expression evaluator can't be called on a dependent expression.");
13064
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013065 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000013066 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
13067
13068 if (!isIntegerConstantExpr(Ctx, Loc))
13069 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000013070
Richard Smith5c40f092015-12-04 03:00:44 +000013071 // The only possible side-effects here are due to UB discovered in the
13072 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
13073 // required to treat the expression as an ICE, so we produce the folded
13074 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000013075 EvalResult ExprResult;
13076 Expr::EvalStatus Status;
13077 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
13078 Info.InConstantContext = true;
13079
13080 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000013081 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000013082
13083 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000013084 return true;
13085}
Richard Smith66e05fe2012-01-18 05:21:49 +000013086
Craig Toppera31a8822013-08-22 07:09:37 +000013087bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013088 assert(!isValueDependent() &&
13089 "Expression evaluator can't be called on a dependent expression.");
13090
Richard Smith9e575da2012-12-28 13:25:52 +000013091 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000013092}
13093
Craig Toppera31a8822013-08-22 07:09:37 +000013094bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000013095 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013096 assert(!isValueDependent() &&
13097 "Expression evaluator can't be called on a dependent expression.");
13098
Richard Smith66e05fe2012-01-18 05:21:49 +000013099 // We support this checking in C++98 mode in order to diagnose compatibility
13100 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013101 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000013102
Richard Smith98a0a492012-02-14 21:38:30 +000013103 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000013104 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013105 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000013106 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000013107 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000013108
13109 APValue Scratch;
13110 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
13111
13112 if (!Diags.empty()) {
13113 IsConstExpr = false;
13114 if (Loc) *Loc = Diags[0].first;
13115 } else if (!IsConstExpr) {
13116 // FIXME: This shouldn't happen.
13117 if (Loc) *Loc = getExprLoc();
13118 }
13119
13120 return IsConstExpr;
13121}
Richard Smith253c2a32012-01-27 01:14:48 +000013122
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013123bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
13124 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000013125 ArrayRef<const Expr*> Args,
13126 const Expr *This) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013127 assert(!isValueDependent() &&
13128 "Expression evaluator can't be called on a dependent expression.");
13129
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013130 Expr::EvalStatus Status;
13131 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000013132 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013133
George Burgess IV177399e2017-01-09 04:12:14 +000013134 LValue ThisVal;
13135 const LValue *ThisPtr = nullptr;
13136 if (This) {
13137#ifndef NDEBUG
13138 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
13139 assert(MD && "Don't provide `this` for non-methods.");
13140 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
13141#endif
13142 if (EvaluateObjectArgument(Info, This, ThisVal))
13143 ThisPtr = &ThisVal;
13144 if (Info.EvalStatus.HasSideEffects)
13145 return false;
13146 }
13147
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013148 ArgVector ArgValues(Args.size());
13149 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
13150 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000013151 if ((*I)->isValueDependent() ||
13152 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013153 // If evaluation fails, throw away the argument entirely.
13154 ArgValues[I - Args.begin()] = APValue();
13155 if (Info.EvalStatus.HasSideEffects)
13156 return false;
13157 }
13158
13159 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000013160 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013161 ArgValues.data());
13162 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
13163}
13164
Richard Smith253c2a32012-01-27 01:14:48 +000013165bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013166 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000013167 PartialDiagnosticAt> &Diags) {
13168 // FIXME: It would be useful to check constexpr function templates, but at the
13169 // moment the constant expression evaluator cannot cope with the non-rigorous
13170 // ASTs which we build for dependent expressions.
13171 if (FD->isDependentContext())
13172 return true;
13173
13174 Expr::EvalStatus Status;
13175 Status.Diag = &Diags;
13176
Richard Smith6d4c6582013-11-05 22:18:15 +000013177 EvalInfo Info(FD->getASTContext(), Status,
13178 EvalInfo::EM_PotentialConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000013179 Info.InConstantContext = true;
Richard Smith253c2a32012-01-27 01:14:48 +000013180
13181 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000013182 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000013183
Richard Smith7525ff62013-05-09 07:14:00 +000013184 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000013185 // is a temporary being used as the 'this' pointer.
13186 LValue This;
13187 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000013188 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000013189
Richard Smith253c2a32012-01-27 01:14:48 +000013190 ArrayRef<const Expr*> Args;
13191
Richard Smith2e312c82012-03-03 22:46:17 +000013192 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000013193 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
13194 // Evaluate the call as a constant initializer, to allow the construction
13195 // of objects of non-literal types.
13196 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000013197 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
13198 } else {
13199 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000013200 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000013201 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000013202 }
Richard Smith253c2a32012-01-27 01:14:48 +000013203
13204 return Diags.empty();
13205}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013206
13207bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
13208 const FunctionDecl *FD,
13209 SmallVectorImpl<
13210 PartialDiagnosticAt> &Diags) {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013211 assert(!E->isValueDependent() &&
13212 "Expression evaluator can't be called on a dependent expression.");
13213
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013214 Expr::EvalStatus Status;
13215 Status.Diag = &Diags;
13216
13217 EvalInfo Info(FD->getASTContext(), Status,
13218 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000013219 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013220
13221 // Fabricate a call stack frame to give the arguments a plausible cover story.
13222 ArrayRef<const Expr*> Args;
13223 ArgVector ArgValues(0);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013224 bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013225 (void)Success;
13226 assert(Success &&
13227 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000013228 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013229
13230 APValue ResultScratch;
13231 Evaluate(ResultScratch, Info, E);
13232 return Diags.empty();
13233}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000013234
13235bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
13236 unsigned Type) const {
13237 if (!getType()->isPointerType())
13238 return false;
13239
13240 Expr::EvalStatus Status;
13241 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000013242 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000013243}