blob: 39d0943b45ec15e184233d1b3b414391d7ff9af3 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson7a241ba2008-07-03 04:20:39 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
Richard Smith253c2a32012-01-27 01:14:48 +000011// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000025// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000027//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000033//===----------------------------------------------------------------------===//
34
Nandor Licker950b70d2019-09-13 09:46:16 +000035#include <cstring>
36#include <functional>
37#include "Interp/Context.h"
38#include "Interp/Frame.h"
39#include "Interp/State.h"
Anders Carlsson7a241ba2008-07-03 04:20:39 +000040#include "clang/AST/APValue.h"
41#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000042#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000043#include "clang/AST/ASTLambda.h"
Nandor Licker7bd0a782019-08-29 21:57:47 +000044#include "clang/AST/CXXInheritance.h"
Ken Dyck40775002010-01-11 17:06:35 +000045#include "clang/AST/CharUnits.h"
Eric Fiselier708afb52019-05-16 21:04:15 +000046#include "clang/AST/CurrentSourceLocExprScope.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "clang/AST/Expr.h"
Tim Northover314fbfa2018-11-02 13:14:11 +000048#include "clang/AST/OSLog.h"
Nandor Licker950b70d2019-09-13 09:46:16 +000049#include "clang/AST/OptionalDiagnostic.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000050#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000051#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000052#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000053#include "clang/Basic/Builtins.h"
Leonard Chand3f3e162019-01-18 21:04:25 +000054#include "clang/Basic/FixedPoint.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000055#include "clang/Basic/TargetInfo.h"
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000056#include "llvm/ADT/Optional.h"
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000057#include "llvm/ADT/SmallBitVector.h"
Fangrui Song407659a2018-11-30 23:41:18 +000058#include "llvm/Support/SaveAndRestore.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000059#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000060
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000061#define DEBUG_TYPE "exprconstant"
62
Anders Carlsson7a241ba2008-07-03 04:20:39 +000063using namespace clang;
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000064using llvm::APInt;
Chris Lattner05706e882008-07-11 18:11:29 +000065using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000066using llvm::APFloat;
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000067using llvm::Optional;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000068
Richard Smithb228a862012-02-15 02:18:13 +000069static bool IsGlobalLValue(APValue::LValueBase B);
70
John McCall93d91dc2010-05-07 17:22:02 +000071namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000072 struct LValue;
Nandor Licker950b70d2019-09-13 09:46:16 +000073 class CallStackFrame;
74 class EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000075
Eric Fiselier708afb52019-05-16 21:04:15 +000076 using SourceLocExprScopeGuard =
77 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
78
Richard Smithb228a862012-02-15 02:18:13 +000079 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000080 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000081 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000082 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000083 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000084 //
85 // extern int arr[]; void f() { extern int arr[3]; };
86 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000087 //
88 // For now, we take the array bound from the most recent declaration.
89 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
90 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
91 QualType T = Redecl->getType();
92 if (!T->isIncompleteArrayType())
93 return T;
94 }
95 return D->getType();
96 }
Richard Smith84401042013-06-03 05:03:02 +000097
Mikael Holmen3b6b2e32019-05-20 11:38:33 +000098 if (B.is<TypeInfoLValue>())
Richard Smithee0ce3022019-05-17 07:06:46 +000099 return B.getTypeInfoType();
100
Richard Smith84401042013-06-03 05:03:02 +0000101 const Expr *Base = B.get<const Expr*>();
102
103 // For a materialized temporary, the type of the temporary we materialized
104 // may not be the type of the expression.
105 if (const MaterializeTemporaryExpr *MTE =
106 dyn_cast<MaterializeTemporaryExpr>(Base)) {
107 SmallVector<const Expr *, 2> CommaLHSs;
108 SmallVector<SubobjectAdjustment, 2> Adjustments;
109 const Expr *Temp = MTE->GetTemporaryExpr();
110 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
111 Adjustments);
112 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +0000113 // for it directly. Otherwise use the type after adjustment.
114 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +0000115 return Inner->getType();
116 }
117
118 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000119 }
120
Richard Smithd62306a2011-11-10 06:34:14 +0000121 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000122 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000123 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000124 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000125 }
126 /// Get an LValue path entry, which is known to not be an array index, as a
127 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000128 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000129 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000130 }
131 /// Determine whether this LValue path entry for a base class names a virtual
132 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000133 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000134 return E.getAsBaseOrMember().getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000135 }
136
George Burgess IVe3763372016-12-22 02:50:20 +0000137 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
138 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
139 const FunctionDecl *Callee = CE->getDirectCallee();
140 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
141 }
142
143 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
144 /// This will look through a single cast.
145 ///
146 /// Returns null if we couldn't unwrap a function with alloc_size.
147 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
148 if (!E->getType()->isPointerType())
149 return nullptr;
150
151 E = E->IgnoreParens();
152 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000153 // probably be a cast of some kind. In exotic cases, we might also see a
154 // top-level ExprWithCleanups. Ignore them either way.
Bill Wendling7c44da22018-10-31 03:48:47 +0000155 if (const auto *FE = dyn_cast<FullExpr>(E))
156 E = FE->getSubExpr()->IgnoreParens();
George Burgess IV47638762018-03-07 04:52:34 +0000157
George Burgess IVe3763372016-12-22 02:50:20 +0000158 if (const auto *Cast = dyn_cast<CastExpr>(E))
159 E = Cast->getSubExpr()->IgnoreParens();
160
161 if (const auto *CE = dyn_cast<CallExpr>(E))
162 return getAllocSizeAttr(CE) ? CE : nullptr;
163 return nullptr;
164 }
165
166 /// Determines whether or not the given Base contains a call to a function
167 /// with the alloc_size attribute.
168 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
169 const auto *E = Base.dyn_cast<const Expr *>();
170 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
171 }
172
Richard Smith6f4f0f12017-10-20 22:56:25 +0000173 /// The bound to claim that an array of unknown bound has.
174 /// The value in MostDerivedArraySize is undefined in this case. So, set it
175 /// to an arbitrary value that's likely to loudly break things if it's used.
176 static const uint64_t AssumedSizeForUnsizedArray =
177 std::numeric_limits<uint64_t>::max() / 2;
178
George Burgess IVe3763372016-12-22 02:50:20 +0000179 /// Determines if an LValue with the given LValueBase will have an unsized
180 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000181 /// Find the path length and type of the most-derived subobject in the given
182 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000183 static unsigned
184 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
185 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000186 uint64_t &ArraySize, QualType &Type, bool &IsArray,
187 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000188 // This only accepts LValueBases from APValues, and APValues don't support
189 // arrays that lack size info.
190 assert(!isBaseAnAllocSizeCall(Base) &&
191 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000192 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000193 Type = getType(Base);
194
Richard Smith80815602011-11-07 05:07:52 +0000195 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000196 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000197 const ArrayType *AT = Ctx.getAsArrayType(Type);
198 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000199 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000200 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000201
202 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
203 ArraySize = CAT->getSize().getZExtValue();
204 } else {
205 assert(I == 0 && "unexpected unsized array designator");
206 FirstEntryIsUnsizedArray = true;
207 ArraySize = AssumedSizeForUnsizedArray;
208 }
Richard Smith66c96992012-02-18 22:04:06 +0000209 } else if (Type->isAnyComplexType()) {
210 const ComplexType *CT = Type->castAs<ComplexType>();
211 Type = CT->getElementType();
212 ArraySize = 2;
213 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000214 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000215 } else if (const FieldDecl *FD = getAsField(Path[I])) {
216 Type = FD->getType();
217 ArraySize = 0;
218 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000219 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 } else {
Richard Smith80815602011-11-07 05:07:52 +0000221 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000222 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000223 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000224 }
Richard Smith80815602011-11-07 05:07:52 +0000225 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000226 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000227 }
228
Richard Smith96e0c102011-11-04 02:25:55 +0000229 /// A path from a glvalue to a subobject of that glvalue.
230 struct SubobjectDesignator {
231 /// True if the subobject was named in a manner not supported by C++11. Such
232 /// lvalues can still be folded, but they are not core constant expressions
233 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000234 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000235
Richard Smitha8105bc2012-01-06 16:39:00 +0000236 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000237 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000238
Daniel Jasperffdee092017-05-02 19:21:42 +0000239 /// Indicator of whether the first entry is an unsized array.
240 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000241
George Burgess IVa51c4072015-10-16 01:49:01 +0000242 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000243 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000244
Richard Smitha8105bc2012-01-06 16:39:00 +0000245 /// The length of the path to the most-derived object of which this is a
246 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000247 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000248
George Burgess IVa51c4072015-10-16 01:49:01 +0000249 /// The size of the array of which the most-derived object is an element.
250 /// This will always be 0 if the most-derived object is not an array
251 /// element. 0 is not an indicator of whether or not the most-derived object
252 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000253 ///
254 /// If the current array is an unsized array, the value of this is
255 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000256 uint64_t MostDerivedArraySize;
257
258 /// The type of the most derived object referred to by this address.
259 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000260
Richard Smith80815602011-11-07 05:07:52 +0000261 typedef APValue::LValuePathEntry PathEntry;
262
Richard Smith96e0c102011-11-04 02:25:55 +0000263 /// The entries on the path from the glvalue to the designated subobject.
264 SmallVector<PathEntry, 8> Entries;
265
Richard Smitha8105bc2012-01-06 16:39:00 +0000266 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000267
Richard Smitha8105bc2012-01-06 16:39:00 +0000268 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000269 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000270 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000271 MostDerivedPathLength(0), MostDerivedArraySize(0),
272 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000273
274 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000275 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000276 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000277 MostDerivedPathLength(0), MostDerivedArraySize(0) {
278 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000279 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000280 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000281 ArrayRef<PathEntry> VEntries = V.getLValuePath();
282 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000283 if (V.getLValueBase()) {
284 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000285 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000286 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000287 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000288 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000289 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000290 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000291 }
Richard Smith80815602011-11-07 05:07:52 +0000292 }
293 }
294
Richard Smith31c69a32019-05-21 23:15:20 +0000295 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
296 unsigned NewLength) {
297 if (Invalid)
298 return;
299
300 assert(Base && "cannot truncate path for null pointer");
301 assert(NewLength <= Entries.size() && "not a truncation");
302
303 if (NewLength == Entries.size())
304 return;
305 Entries.resize(NewLength);
306
307 bool IsArray = false;
308 bool FirstIsUnsizedArray = false;
309 MostDerivedPathLength = findMostDerivedSubobject(
310 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
311 FirstIsUnsizedArray);
312 MostDerivedIsArrayElement = IsArray;
313 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
314 }
315
Richard Smith96e0c102011-11-04 02:25:55 +0000316 void setInvalid() {
317 Invalid = true;
318 Entries.clear();
319 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000320
George Burgess IVe3763372016-12-22 02:50:20 +0000321 /// Determine whether the most derived subobject is an array without a
322 /// known bound.
323 bool isMostDerivedAnUnsizedArray() const {
324 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000325 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000326 }
327
328 /// Determine what the most derived array's size is. Results in an assertion
329 /// failure if the most derived array lacks a size.
330 uint64_t getMostDerivedArraySize() const {
331 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
332 return MostDerivedArraySize;
333 }
334
Richard Smitha8105bc2012-01-06 16:39:00 +0000335 /// Determine whether this is a one-past-the-end pointer.
336 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000337 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000338 if (IsOnePastTheEnd)
339 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000340 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smith5b5e27a2019-05-10 20:05:31 +0000341 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
342 MostDerivedArraySize)
Richard Smitha8105bc2012-01-06 16:39:00 +0000343 return true;
344 return false;
345 }
346
Richard Smith06f71b52018-08-04 00:57:17 +0000347 /// Get the range of valid index adjustments in the form
348 /// {maximum value that can be subtracted from this pointer,
349 /// maximum value that can be added to this pointer}
350 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
351 if (Invalid || isMostDerivedAnUnsizedArray())
352 return {0, 0};
353
354 // [expr.add]p4: For the purposes of these operators, a pointer to a
355 // nonarray object behaves the same as a pointer to the first element of
356 // an array of length one with the type of the object as its element type.
357 bool IsArray = MostDerivedPathLength == Entries.size() &&
358 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000359 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
360 : (uint64_t)IsOnePastTheEnd;
Richard Smith06f71b52018-08-04 00:57:17 +0000361 uint64_t ArraySize =
362 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
363 return {ArrayIndex, ArraySize - ArrayIndex};
364 }
365
Richard Smitha8105bc2012-01-06 16:39:00 +0000366 /// Check that this refers to a valid subobject.
367 bool isValidSubobject() const {
368 if (Invalid)
369 return false;
370 return !isOnePastTheEnd();
371 }
372 /// Check that this refers to a valid subobject, and if not, produce a
373 /// relevant diagnostic and set the designator as invalid.
374 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
375
Richard Smith06f71b52018-08-04 00:57:17 +0000376 /// Get the type of the designated object.
377 QualType getType(ASTContext &Ctx) const {
378 assert(!Invalid && "invalid designator has no subobject type");
379 return MostDerivedPathLength == Entries.size()
380 ? MostDerivedType
381 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
382 }
383
Richard Smitha8105bc2012-01-06 16:39:00 +0000384 /// Update this designator to refer to the first element within this array.
385 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000386 Entries.push_back(PathEntry::ArrayIndex(0));
Richard Smitha8105bc2012-01-06 16:39:00 +0000387
388 // This is a most-derived object.
389 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000390 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000391 MostDerivedArraySize = CAT->getSize().getZExtValue();
392 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000393 }
George Burgess IVe3763372016-12-22 02:50:20 +0000394 /// Update this designator to refer to the first element within the array of
395 /// elements of type T. This is an array of unknown size.
396 void addUnsizedArrayUnchecked(QualType ElemTy) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000397 Entries.push_back(PathEntry::ArrayIndex(0));
George Burgess IVe3763372016-12-22 02:50:20 +0000398
399 MostDerivedType = ElemTy;
400 MostDerivedIsArrayElement = true;
401 // The value in MostDerivedArraySize is undefined in this case. So, set it
402 // to an arbitrary value that's likely to loudly break things if it's
403 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000404 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000405 MostDerivedPathLength = Entries.size();
406 }
Richard Smith96e0c102011-11-04 02:25:55 +0000407 /// Update this designator to refer to the given base or member of this
408 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000409 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000410 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
Richard Smitha8105bc2012-01-06 16:39:00 +0000411
412 // If this isn't a base class, it's a new most-derived object.
413 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
414 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000415 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000416 MostDerivedArraySize = 0;
417 MostDerivedPathLength = Entries.size();
418 }
Richard Smith96e0c102011-11-04 02:25:55 +0000419 }
Richard Smith66c96992012-02-18 22:04:06 +0000420 /// Update this designator to refer to the given complex component.
421 void addComplexUnchecked(QualType EltTy, bool Imag) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000422 Entries.push_back(PathEntry::ArrayIndex(Imag));
Richard Smith66c96992012-02-18 22:04:06 +0000423
424 // This is technically a most-derived object, though in practice this
425 // is unlikely to matter.
426 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000427 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000428 MostDerivedArraySize = 2;
429 MostDerivedPathLength = Entries.size();
430 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000431 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000432 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
433 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000434 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000435 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
436 if (Invalid || !N) return;
437 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
438 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000439 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000440 // Can't verify -- trust that the user is doing the right thing (or if
441 // not, trust that the caller will catch the bad behavior).
442 // FIXME: Should we reject if this overflows, at least?
Richard Smith5b5e27a2019-05-10 20:05:31 +0000443 Entries.back() = PathEntry::ArrayIndex(
444 Entries.back().getAsArrayIndex() + TruncatedN);
Daniel Jasperffdee092017-05-02 19:21:42 +0000445 return;
446 }
447
448 // [expr.add]p4: For the purposes of these operators, a pointer to a
449 // nonarray object behaves the same as a pointer to the first element of
450 // an array of length one with the type of the object as its element type.
451 bool IsArray = MostDerivedPathLength == Entries.size() &&
452 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000453 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
454 : (uint64_t)IsOnePastTheEnd;
Daniel Jasperffdee092017-05-02 19:21:42 +0000455 uint64_t ArraySize =
456 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
457
458 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
459 // Calculate the actual index in a wide enough type, so we can include
460 // it in the note.
461 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
462 (llvm::APInt&)N += ArrayIndex;
463 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
464 diagnosePointerArithmetic(Info, E, N);
465 setInvalid();
466 return;
467 }
468
469 ArrayIndex += TruncatedN;
470 assert(ArrayIndex <= ArraySize &&
471 "bounds check succeeded for out-of-bounds index");
472
473 if (IsArray)
Richard Smith5b5e27a2019-05-10 20:05:31 +0000474 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
Daniel Jasperffdee092017-05-02 19:21:42 +0000475 else
476 IsOnePastTheEnd = (ArrayIndex != 0);
477 }
Richard Smith96e0c102011-11-04 02:25:55 +0000478 };
479
Richard Smith254a73d2011-10-28 22:34:42 +0000480 /// A stack frame in the constexpr call stack.
Nandor Licker950b70d2019-09-13 09:46:16 +0000481 class CallStackFrame : public interp::Frame {
482 public:
Richard Smith254a73d2011-10-28 22:34:42 +0000483 EvalInfo &Info;
484
485 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000486 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000487
Richard Smithf6f003a2011-12-16 19:06:07 +0000488 /// Callee - The function which was called.
489 const FunctionDecl *Callee;
490
Richard Smithd62306a2011-11-10 06:34:14 +0000491 /// This - The binding for the this pointer in this call, if any.
492 const LValue *This;
493
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000494 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000495 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000496 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000497
Eric Fiselier708afb52019-05-16 21:04:15 +0000498 /// Source location information about the default argument or default
499 /// initializer expression we're evaluating, if any.
500 CurrentSourceLocExprScope CurSourceLocExprScope;
501
Eli Friedman4830ec82012-06-25 21:21:08 +0000502 // Note that we intentionally use std::map here so that references to
503 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000504 typedef std::pair<const void *, unsigned> MapKeyTy;
505 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000506 /// Temporaries - Temporary lvalues materialized within this stack frame.
507 MapTy Temporaries;
508
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000509 /// CallLoc - The location of the call expression for this call.
510 SourceLocation CallLoc;
511
512 /// Index - The call index of this call.
513 unsigned Index;
514
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000515 /// The stack of integers for tracking version numbers for temporaries.
516 SmallVector<unsigned, 2> TempVersionStack = {1};
517 unsigned CurTempVersion = TempVersionStack.back();
518
519 unsigned getTempVersion() const { return TempVersionStack.back(); }
520
521 void pushTempVersion() {
522 TempVersionStack.push_back(++CurTempVersion);
523 }
524
525 void popTempVersion() {
526 TempVersionStack.pop_back();
527 }
528
Faisal Vali051e3a22017-02-16 04:12:21 +0000529 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000530 // on the overall stack usage of deeply-recursing constexpr evaluations.
Faisal Vali051e3a22017-02-16 04:12:21 +0000531 // (We should cache this map rather than recomputing it repeatedly.)
532 // But let's try this and see how it goes; we can look into caching the map
533 // as a later change.
534
535 /// LambdaCaptureFields - Mapping from captured variables/this to
536 /// corresponding data members in the closure class.
537 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
538 FieldDecl *LambdaThisCaptureField;
539
Richard Smithf6f003a2011-12-16 19:06:07 +0000540 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
541 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000542 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000543 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000544
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000545 // Return the temporary for Key whose version number is Version.
546 APValue *getTemporary(const void *Key, unsigned Version) {
547 MapKeyTy KV(Key, Version);
548 auto LB = Temporaries.lower_bound(KV);
549 if (LB != Temporaries.end() && LB->first == KV)
550 return &LB->second;
551 // Pair (Key,Version) wasn't found in the map. Check that no elements
552 // in the map have 'Key' as their key.
553 assert((LB == Temporaries.end() || LB->first.first != Key) &&
554 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
555 "Element with key 'Key' found in map");
556 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000557 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000558
559 // Return the current temporary for Key in the map.
560 APValue *getCurrentTemporary(const void *Key) {
561 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
562 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
563 return &std::prev(UB)->second;
564 return nullptr;
565 }
566
567 // Return the version number of the current temporary for Key.
568 unsigned getCurrentTemporaryVersion(const void *Key) const {
569 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
570 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
571 return std::prev(UB)->first.second;
572 return 0;
573 }
574
Richard Smith08d6a2c2013-07-24 07:11:57 +0000575 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Nandor Licker950b70d2019-09-13 09:46:16 +0000576
577 void describe(llvm::raw_ostream &OS) override;
578
579 Frame *getCaller() const override { return Caller; }
580 SourceLocation getCallLocation() const override { return CallLoc; }
581 const FunctionDecl *getCallee() const override { return Callee; }
Richard Smith254a73d2011-10-28 22:34:42 +0000582 };
583
Richard Smith852c9db2013-04-20 22:23:05 +0000584 /// Temporarily override 'this'.
585 class ThisOverrideRAII {
586 public:
587 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
588 : Frame(Frame), OldThis(Frame.This) {
589 if (Enable)
590 Frame.This = NewThis;
591 }
592 ~ThisOverrideRAII() {
593 Frame.This = OldThis;
594 }
595 private:
596 CallStackFrame &Frame;
597 const LValue *OldThis;
598 };
599
Richard Smith08d6a2c2013-07-24 07:11:57 +0000600 /// A cleanup, and a flag indicating whether it is lifetime-extended.
601 class Cleanup {
602 llvm::PointerIntPair<APValue*, 1, bool> Value;
603
604 public:
605 Cleanup(APValue *Val, bool IsLifetimeExtended)
606 : Value(Val, IsLifetimeExtended) {}
607
608 bool isLifetimeExtended() const { return Value.getInt(); }
609 void endLifetime() {
610 *Value.getPointer() = APValue();
611 }
612 };
613
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000614 /// A reference to an object whose construction we are currently evaluating.
615 struct ObjectUnderConstruction {
616 APValue::LValueBase Base;
617 ArrayRef<APValue::LValuePathEntry> Path;
618 friend bool operator==(const ObjectUnderConstruction &LHS,
619 const ObjectUnderConstruction &RHS) {
620 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
621 }
622 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
623 return llvm::hash_combine(Obj.Base, Obj.Path);
624 }
625 };
626 enum class ConstructionPhase { None, Bases, AfterBases };
627}
628
629namespace llvm {
630template<> struct DenseMapInfo<ObjectUnderConstruction> {
631 using Base = DenseMapInfo<APValue::LValueBase>;
632 static ObjectUnderConstruction getEmptyKey() {
633 return {Base::getEmptyKey(), {}}; }
634 static ObjectUnderConstruction getTombstoneKey() {
635 return {Base::getTombstoneKey(), {}};
636 }
637 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
638 return hash_value(Object);
639 }
640 static bool isEqual(const ObjectUnderConstruction &LHS,
641 const ObjectUnderConstruction &RHS) {
642 return LHS == RHS;
643 }
644};
645}
646
647namespace {
Richard Smithb228a862012-02-15 02:18:13 +0000648 /// EvalInfo - This is a private struct used by the evaluator to capture
649 /// information about a subexpression as it is folded. It retains information
650 /// about the AST context, but also maintains information about the folded
651 /// expression.
652 ///
653 /// If an expression could be evaluated, it is still possible it is not a C
654 /// "integer constant expression" or constant expression. If not, this struct
655 /// captures information about how and why not.
656 ///
657 /// One bit of information passed *into* the request for constant folding
658 /// indicates whether the subexpression is "evaluated" or not according to C
659 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
660 /// evaluate the expression regardless of what the RHS is, but C only allows
661 /// certain things in certain situations.
Nandor Licker950b70d2019-09-13 09:46:16 +0000662 class EvalInfo : public interp::State {
663 public:
Richard Smith92b1ce02011-12-12 09:28:41 +0000664 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000665
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000666 /// EvalStatus - Contains information about the evaluation.
667 Expr::EvalStatus &EvalStatus;
668
669 /// CurrentCall - The top of the constexpr call stack.
670 CallStackFrame *CurrentCall;
671
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000672 /// CallStackDepth - The number of calls in the call stack right now.
673 unsigned CallStackDepth;
674
Richard Smithb228a862012-02-15 02:18:13 +0000675 /// NextCallIndex - The next call index to assign.
676 unsigned NextCallIndex;
677
Richard Smitha3d3bd22013-05-08 02:12:03 +0000678 /// StepsLeft - The remaining number of evaluation steps we're permitted
679 /// to perform. This is essentially a limit for the number of statements
680 /// we will evaluate.
681 unsigned StepsLeft;
682
Nandor Licker950b70d2019-09-13 09:46:16 +0000683 /// Force the use of the experimental new constant interpreter, bailing out
684 /// with an error if a feature is not supported.
685 bool ForceNewConstInterp;
686
687 /// Enable the experimental new constant interpreter.
688 bool EnableNewConstInterp;
689
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000690 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000691 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000692 CallStackFrame BottomFrame;
693
Richard Smith08d6a2c2013-07-24 07:11:57 +0000694 /// A stack of values whose lifetimes end at the end of some surrounding
695 /// evaluation frame.
696 llvm::SmallVector<Cleanup, 16> CleanupStack;
697
Richard Smithd62306a2011-11-10 06:34:14 +0000698 /// EvaluatingDecl - This is the declaration whose initializer is being
699 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000700 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000701
702 /// EvaluatingDeclValue - This is the value being constructed for the
703 /// declaration whose initializer is being evaluated, if any.
704 APValue *EvaluatingDeclValue;
705
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000706 /// Set of objects that are currently being constructed.
707 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
708 ObjectsUnderConstruction;
Erik Pilkington42925492017-10-04 00:18:55 +0000709
710 struct EvaluatingConstructorRAII {
711 EvalInfo &EI;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000712 ObjectUnderConstruction Object;
Erik Pilkington42925492017-10-04 00:18:55 +0000713 bool DidInsert;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000714 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
715 bool HasBases)
Erik Pilkington42925492017-10-04 00:18:55 +0000716 : EI(EI), Object(Object) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000717 DidInsert =
718 EI.ObjectsUnderConstruction
719 .insert({Object, HasBases ? ConstructionPhase::Bases
720 : ConstructionPhase::AfterBases})
721 .second;
722 }
723 void finishedConstructingBases() {
724 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
Erik Pilkington42925492017-10-04 00:18:55 +0000725 }
726 ~EvaluatingConstructorRAII() {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000727 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
Erik Pilkington42925492017-10-04 00:18:55 +0000728 }
729 };
730
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000731 ConstructionPhase
732 isEvaluatingConstructor(APValue::LValueBase Base,
733 ArrayRef<APValue::LValuePathEntry> Path) {
734 return ObjectsUnderConstruction.lookup({Base, Path});
Erik Pilkington42925492017-10-04 00:18:55 +0000735 }
736
Richard Smith37be3362019-05-04 04:00:45 +0000737 /// If we're currently speculatively evaluating, the outermost call stack
738 /// depth at which we can mutate state, otherwise 0.
739 unsigned SpeculativeEvaluationDepth = 0;
740
Richard Smith410306b2016-12-12 02:53:20 +0000741 /// The current array initialization index, if we're performing array
742 /// initialization.
743 uint64_t ArrayInitIndex = -1;
744
Richard Smith357362d2011-12-13 06:39:58 +0000745 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
746 /// notes attached to it will also be stored, otherwise they will not be.
747 bool HasActiveDiagnostic;
748
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000749 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000750 /// fold (not just why it's not strictly a constant expression)?
751 bool HasFoldFailureDiagnostic;
752
Fangrui Song407659a2018-11-30 23:41:18 +0000753 /// Whether or not we're in a context where the front end requires a
754 /// constant value.
755 bool InConstantContext;
756
Richard Smith045b2272019-09-10 21:24:09 +0000757 /// Whether we're checking that an expression is a potential constant
758 /// expression. If so, do not fail on constructs that could become constant
759 /// later on (such as a use of an undefined global).
760 bool CheckingPotentialConstantExpression = false;
761
762 /// Whether we're checking for an expression that has undefined behavior.
763 /// If so, we will produce warnings if we encounter an operation that is
764 /// always undefined.
765 bool CheckingForUndefinedBehavior = false;
766
Richard Smith6d4c6582013-11-05 22:18:15 +0000767 enum EvaluationMode {
768 /// Evaluate as a constant expression. Stop if we find that the expression
769 /// is not a constant expression.
770 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000771
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000772 /// Evaluate as a constant expression. Stop if we find that the expression
773 /// is not a constant expression. Some expressions can be retried in the
774 /// optimizer if we don't constant fold them here, but in an unevaluated
775 /// context we try to fold them immediately since the optimizer never
776 /// gets a chance to look at it.
777 EM_ConstantExpressionUnevaluated,
778
Richard Smith045b2272019-09-10 21:24:09 +0000779 /// Fold the expression to a constant. Stop if we hit a side-effect that
780 /// we can't model.
781 EM_ConstantFold,
782
783 /// Evaluate in any way we know how. Don't worry about side-effects that
784 /// can't be modeled.
785 EM_IgnoreSideEffects,
Richard Smith6d4c6582013-11-05 22:18:15 +0000786 } EvalMode;
787
788 /// Are we checking whether the expression is a potential constant
789 /// expression?
Nandor Licker950b70d2019-09-13 09:46:16 +0000790 bool checkingPotentialConstantExpression() const override {
Richard Smith045b2272019-09-10 21:24:09 +0000791 return CheckingPotentialConstantExpression;
Richard Smith6d4c6582013-11-05 22:18:15 +0000792 }
793
794 /// Are we checking an expression for overflow?
795 // FIXME: We should check for any kind of undefined or suspicious behavior
796 // in such constructs, not just overflow.
Nandor Licker950b70d2019-09-13 09:46:16 +0000797 bool checkingForUndefinedBehavior() const override {
798 return CheckingForUndefinedBehavior;
799 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000800
801 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Nandor Licker950b70d2019-09-13 09:46:16 +0000802 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
803 CallStackDepth(0), NextCallIndex(1),
804 StepsLeft(getLangOpts().ConstexprStepLimit),
805 ForceNewConstInterp(getLangOpts().ForceNewConstInterp),
806 EnableNewConstInterp(ForceNewConstInterp ||
807 getLangOpts().EnableNewConstInterp),
808 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
809 EvaluatingDecl((const ValueDecl *)nullptr),
810 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
811 HasFoldFailureDiagnostic(false), InConstantContext(false),
812 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000813
Richard Smith7525ff62013-05-09 07:14:00 +0000814 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
815 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000816 EvaluatingDeclValue = &Value;
817 }
818
Richard Smith357362d2011-12-13 06:39:58 +0000819 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000820 // Don't perform any constexpr calls (other than the call we're checking)
821 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000822 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000823 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000824 if (NextCallIndex == 0) {
825 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000826 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000827 return false;
828 }
Richard Smith357362d2011-12-13 06:39:58 +0000829 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
830 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000831 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000832 << getLangOpts().ConstexprCallDepth;
833 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000834 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000835
Richard Smith37be3362019-05-04 04:00:45 +0000836 std::pair<CallStackFrame *, unsigned>
837 getCallFrameAndDepth(unsigned CallIndex) {
838 assert(CallIndex && "no call index in getCallFrameAndDepth");
Richard Smithb228a862012-02-15 02:18:13 +0000839 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
840 // be null in this loop.
Richard Smith37be3362019-05-04 04:00:45 +0000841 unsigned Depth = CallStackDepth;
Richard Smithb228a862012-02-15 02:18:13 +0000842 CallStackFrame *Frame = CurrentCall;
Richard Smith37be3362019-05-04 04:00:45 +0000843 while (Frame->Index > CallIndex) {
Richard Smithb228a862012-02-15 02:18:13 +0000844 Frame = Frame->Caller;
Richard Smith37be3362019-05-04 04:00:45 +0000845 --Depth;
846 }
847 if (Frame->Index == CallIndex)
848 return {Frame, Depth};
849 return {nullptr, 0};
Richard Smithb228a862012-02-15 02:18:13 +0000850 }
851
Richard Smitha3d3bd22013-05-08 02:12:03 +0000852 bool nextStep(const Stmt *S) {
853 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000854 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000855 return false;
856 }
857 --StepsLeft;
858 return true;
859 }
860
Richard Smith357362d2011-12-13 06:39:58 +0000861 private:
Nandor Licker950b70d2019-09-13 09:46:16 +0000862 interp::Frame *getCurrentFrame() override { return CurrentCall; }
863 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
864
865 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
866 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
867
868 void setFoldFailureDiagnostic(bool Flag) override {
869 HasFoldFailureDiagnostic = Flag;
Richard Smith357362d2011-12-13 06:39:58 +0000870 }
871
Nandor Licker950b70d2019-09-13 09:46:16 +0000872 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
Richard Smithf6f003a2011-12-16 19:06:07 +0000873
Nandor Licker950b70d2019-09-13 09:46:16 +0000874 ASTContext &getCtx() const override { return Ctx; }
Fangrui Song6907ce22018-07-30 19:24:48 +0000875
Nandor Licker950b70d2019-09-13 09:46:16 +0000876 // If we have a prior diagnostic, it will be noting that the expression
877 // isn't a constant expression. This diagnostic is more important,
878 // unless we require this evaluation to produce a constant expression.
879 //
880 // FIXME: We might want to show both diagnostics to the user in
881 // EM_ConstantFold mode.
882 bool hasPriorDiagnostic() override {
883 if (!EvalStatus.Diag->empty()) {
884 switch (EvalMode) {
885 case EM_ConstantFold:
886 case EM_IgnoreSideEffects:
887 if (!HasFoldFailureDiagnostic)
888 break;
889 // We've already failed to fold something. Keep that diagnostic.
890 LLVM_FALLTHROUGH;
891 case EM_ConstantExpression:
892 case EM_ConstantExpressionUnevaluated:
893 setActiveDiagnostic(false);
894 return true;
Richard Smith6d4c6582013-11-05 22:18:15 +0000895 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000896 }
Nandor Licker950b70d2019-09-13 09:46:16 +0000897 return false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000898 }
Nandor Licker950b70d2019-09-13 09:46:16 +0000899
900 unsigned getCallStackDepth() override { return CallStackDepth; }
901
Faisal Valie690b7a2016-07-02 22:34:24 +0000902 public:
Richard Smith6d4c6582013-11-05 22:18:15 +0000903 /// Should we continue evaluation after encountering a side-effect that we
904 /// couldn't model?
905 bool keepEvaluatingAfterSideEffect() {
906 switch (EvalMode) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000907 case EM_IgnoreSideEffects:
908 return true;
909
Richard Smith6d4c6582013-11-05 22:18:15 +0000910 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000911 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000912 case EM_ConstantFold:
Richard Smith045b2272019-09-10 21:24:09 +0000913 // By default, assume any side effect might be valid in some other
914 // evaluation of this expression from a different context.
915 return checkingPotentialConstantExpression() ||
916 checkingForUndefinedBehavior();
Richard Smith6d4c6582013-11-05 22:18:15 +0000917 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000918 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000919 }
920
921 /// Note that we have had a side-effect, and determine whether we should
922 /// keep evaluating.
923 bool noteSideEffect() {
924 EvalStatus.HasSideEffects = true;
925 return keepEvaluatingAfterSideEffect();
926 }
927
Richard Smithce8eca52015-12-08 03:21:47 +0000928 /// Should we continue evaluation after encountering undefined behavior?
929 bool keepEvaluatingAfterUndefinedBehavior() {
930 switch (EvalMode) {
Richard Smithce8eca52015-12-08 03:21:47 +0000931 case EM_IgnoreSideEffects:
932 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000933 return true;
934
Richard Smithce8eca52015-12-08 03:21:47 +0000935 case EM_ConstantExpression:
936 case EM_ConstantExpressionUnevaluated:
Richard Smith045b2272019-09-10 21:24:09 +0000937 return checkingForUndefinedBehavior();
Richard Smithce8eca52015-12-08 03:21:47 +0000938 }
939 llvm_unreachable("Missed EvalMode case");
940 }
941
942 /// Note that we hit something that was technically undefined behavior, but
943 /// that we can evaluate past it (such as signed overflow or floating-point
944 /// division by zero.)
Nandor Licker950b70d2019-09-13 09:46:16 +0000945 bool noteUndefinedBehavior() override {
Richard Smithce8eca52015-12-08 03:21:47 +0000946 EvalStatus.HasUndefinedBehavior = true;
947 return keepEvaluatingAfterUndefinedBehavior();
948 }
949
Richard Smith253c2a32012-01-27 01:14:48 +0000950 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000951 /// construct which can't be reduced to a value?
Nandor Licker950b70d2019-09-13 09:46:16 +0000952 bool keepEvaluatingAfterFailure() const override {
Richard Smith6d4c6582013-11-05 22:18:15 +0000953 if (!StepsLeft)
954 return false;
955
956 switch (EvalMode) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000957 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000958 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000959 case EM_ConstantFold:
960 case EM_IgnoreSideEffects:
Richard Smith045b2272019-09-10 21:24:09 +0000961 return checkingPotentialConstantExpression() ||
962 checkingForUndefinedBehavior();
Richard Smith6d4c6582013-11-05 22:18:15 +0000963 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000964 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000965 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000966
George Burgess IV8c892b52016-05-25 22:31:54 +0000967 /// Notes that we failed to evaluate an expression that other expressions
968 /// directly depend on, and determine if we should keep evaluating. This
969 /// should only be called if we actually intend to keep evaluating.
970 ///
971 /// Call noteSideEffect() instead if we may be able to ignore the value that
972 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
973 ///
974 /// (Foo(), 1) // use noteSideEffect
975 /// (Foo() || true) // use noteSideEffect
976 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000977 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000978 // Failure when evaluating some expression often means there is some
979 // subexpression whose evaluation was skipped. Therefore, (because we
980 // don't track whether we skipped an expression when unwinding after an
981 // evaluation failure) every evaluation failure that bubbles up from a
982 // subexpression implies that a side-effect has potentially happened. We
983 // skip setting the HasSideEffects flag to true until we decide to
984 // continue evaluating after that point, which happens here.
985 bool KeepGoing = keepEvaluatingAfterFailure();
986 EvalStatus.HasSideEffects |= KeepGoing;
987 return KeepGoing;
988 }
989
Richard Smith410306b2016-12-12 02:53:20 +0000990 class ArrayInitLoopIndex {
991 EvalInfo &Info;
992 uint64_t OuterIndex;
993
994 public:
995 ArrayInitLoopIndex(EvalInfo &Info)
996 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
997 Info.ArrayInitIndex = 0;
998 }
999 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1000
1001 operator uint64_t&() { return Info.ArrayInitIndex; }
1002 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001003 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001004
1005 /// Object used to treat all foldable expressions as constant expressions.
1006 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001007 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001008 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001009 bool HadNoPriorDiags;
1010 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001011
Richard Smith6d4c6582013-11-05 22:18:15 +00001012 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1013 : Info(Info),
1014 Enabled(Enabled),
1015 HadNoPriorDiags(Info.EvalStatus.Diag &&
1016 Info.EvalStatus.Diag->empty() &&
1017 !Info.EvalStatus.HasSideEffects),
1018 OldMode(Info.EvalMode) {
Richard Smith045b2272019-09-10 21:24:09 +00001019 if (Enabled)
Richard Smith6d4c6582013-11-05 22:18:15 +00001020 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001021 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001022 void keepDiagnostics() { Enabled = false; }
1023 ~FoldConstant() {
1024 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001025 !Info.EvalStatus.HasSideEffects)
1026 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001027 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001028 }
1029 };
Richard Smith17100ba2012-02-16 02:46:34 +00001030
James Y Knight892b09b2018-10-10 02:53:43 +00001031 /// RAII object used to set the current evaluation mode to ignore
1032 /// side-effects.
1033 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001034 EvalInfo &Info;
1035 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001036 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001037 : Info(Info), OldMode(Info.EvalMode) {
Richard Smith045b2272019-09-10 21:24:09 +00001038 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001039 }
1040
James Y Knight892b09b2018-10-10 02:53:43 +00001041 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001042 };
1043
George Burgess IV8c892b52016-05-25 22:31:54 +00001044 /// RAII object used to optionally suppress diagnostics and side-effects from
1045 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001046 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001047 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001048 Expr::EvalStatus OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001049 unsigned OldSpeculativeEvaluationDepth;
Richard Smith17100ba2012-02-16 02:46:34 +00001050
George Burgess IV8c892b52016-05-25 22:31:54 +00001051 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001052 Info = Other.Info;
1053 OldStatus = Other.OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001054 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001055 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001056 }
1057
1058 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001059 if (!Info)
1060 return;
1061
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001062 Info->EvalStatus = OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001063 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
George Burgess IV8c892b52016-05-25 22:31:54 +00001064 }
1065
Richard Smith17100ba2012-02-16 02:46:34 +00001066 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001067 SpeculativeEvaluationRAII() = default;
1068
1069 SpeculativeEvaluationRAII(
1070 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001071 : Info(&Info), OldStatus(Info.EvalStatus),
Richard Smith37be3362019-05-04 04:00:45 +00001072 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
Richard Smith17100ba2012-02-16 02:46:34 +00001073 Info.EvalStatus.Diag = NewDiag;
Richard Smith37be3362019-05-04 04:00:45 +00001074 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
Richard Smith17100ba2012-02-16 02:46:34 +00001075 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001076
1077 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1078 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1079 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001080 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001081
1082 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1083 maybeRestoreState();
1084 moveFromAndCancel(std::move(Other));
1085 return *this;
1086 }
1087
1088 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001089 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001090
1091 /// RAII object wrapping a full-expression or block scope, and handling
1092 /// the ending of the lifetime of temporaries created within it.
1093 template<bool IsFullExpression>
1094 class ScopeRAII {
1095 EvalInfo &Info;
1096 unsigned OldStackSize;
1097 public:
1098 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001099 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1100 // Push a new temporary version. This is needed to distinguish between
1101 // temporaries created in different iterations of a loop.
1102 Info.CurrentCall->pushTempVersion();
1103 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001104 ~ScopeRAII() {
1105 // Body moved to a static method to encourage the compiler to inline away
1106 // instances of this class.
1107 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001108 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001109 }
1110 private:
1111 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1112 unsigned NewEnd = OldStackSize;
1113 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1114 I != N; ++I) {
1115 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1116 // Full-expression cleanup of a lifetime-extended temporary: nothing
1117 // to do, just move this cleanup to the right place in the stack.
1118 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1119 ++NewEnd;
1120 } else {
1121 // End the lifetime of the object.
1122 Info.CleanupStack[I].endLifetime();
1123 }
1124 }
1125 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1126 Info.CleanupStack.end());
1127 }
1128 };
1129 typedef ScopeRAII<false> BlockScopeRAII;
1130 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001131}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001132
Richard Smitha8105bc2012-01-06 16:39:00 +00001133bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1134 CheckSubobjectKind CSK) {
1135 if (Invalid)
1136 return false;
1137 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001138 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001139 << CSK;
1140 setInvalid();
1141 return false;
1142 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001143 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1144 // must actually be at least one array element; even a VLA cannot have a
1145 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001146 return true;
1147}
1148
Richard Smith6f4f0f12017-10-20 22:56:25 +00001149void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1150 const Expr *E) {
1151 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1152 // Do not set the designator as invalid: we can represent this situation,
1153 // and correct handling of __builtin_object_size requires us to do so.
1154}
1155
Richard Smitha8105bc2012-01-06 16:39:00 +00001156void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001157 const Expr *E,
1158 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001159 // If we're complaining, we must be able to statically determine the size of
1160 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001161 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001162 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001163 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001164 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001165 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001166 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001167 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001168 setInvalid();
1169}
1170
Richard Smithf6f003a2011-12-16 19:06:07 +00001171CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1172 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001173 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001174 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1175 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001176 Info.CurrentCall = this;
1177 ++Info.CallStackDepth;
1178}
1179
1180CallStackFrame::~CallStackFrame() {
1181 assert(Info.CurrentCall == this && "calls retired out of order");
1182 --Info.CallStackDepth;
1183 Info.CurrentCall = Caller;
1184}
1185
Richard Smith08d6a2c2013-07-24 07:11:57 +00001186APValue &CallStackFrame::createTemporary(const void *Key,
1187 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001188 unsigned Version = Info.CurrentCall->getTempVersion();
1189 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smithe637cbe2019-05-21 23:15:18 +00001190 assert(Result.isAbsent() && "temporary created multiple times");
Richard Smith08d6a2c2013-07-24 07:11:57 +00001191 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1192 return Result;
1193}
1194
Richard Smithc667cdc2019-09-18 17:37:44 +00001195static bool isRead(AccessKinds AK) {
1196 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1197}
1198
Richard Smithdebad642019-05-12 09:39:08 +00001199static bool isModification(AccessKinds AK) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00001200 switch (AK) {
1201 case AK_Read:
Richard Smithc667cdc2019-09-18 17:37:44 +00001202 case AK_ReadObjectRepresentation:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001203 case AK_MemberCall:
1204 case AK_DynamicCast:
Richard Smitha9330302019-05-17 19:19:28 +00001205 case AK_TypeId:
Richard Smith7bd54ab2019-05-15 20:22:21 +00001206 return false;
1207 case AK_Assign:
1208 case AK_Increment:
1209 case AK_Decrement:
1210 return true;
1211 }
1212 llvm_unreachable("unknown access kind");
1213}
1214
1215/// Is this an access per the C++ definition?
1216static bool isFormalAccess(AccessKinds AK) {
Richard Smithc667cdc2019-09-18 17:37:44 +00001217 return isRead(AK) || isModification(AK);
Richard Smithdebad642019-05-12 09:39:08 +00001218}
1219
Richard Smithf6f003a2011-12-16 19:06:07 +00001220namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001221 struct ComplexValue {
1222 private:
1223 bool IsInt;
1224
1225 public:
1226 APSInt IntReal, IntImag;
1227 APFloat FloatReal, FloatImag;
1228
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001229 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001230
1231 void makeComplexFloat() { IsInt = false; }
1232 bool isComplexFloat() const { return !IsInt; }
1233 APFloat &getComplexFloatReal() { return FloatReal; }
1234 APFloat &getComplexFloatImag() { return FloatImag; }
1235
1236 void makeComplexInt() { IsInt = true; }
1237 bool isComplexInt() const { return IsInt; }
1238 APSInt &getComplexIntReal() { return IntReal; }
1239 APSInt &getComplexIntImag() { return IntImag; }
1240
Richard Smith2e312c82012-03-03 22:46:17 +00001241 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001242 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001243 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001244 else
Richard Smith2e312c82012-03-03 22:46:17 +00001245 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001246 }
Richard Smith2e312c82012-03-03 22:46:17 +00001247 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001248 assert(v.isComplexFloat() || v.isComplexInt());
1249 if (v.isComplexFloat()) {
1250 makeComplexFloat();
1251 FloatReal = v.getComplexFloatReal();
1252 FloatImag = v.getComplexFloatImag();
1253 } else {
1254 makeComplexInt();
1255 IntReal = v.getComplexIntReal();
1256 IntImag = v.getComplexIntImag();
1257 }
1258 }
John McCall93d91dc2010-05-07 17:22:02 +00001259 };
John McCall45d55e42010-05-07 21:00:08 +00001260
1261 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001262 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001263 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001264 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001265 bool IsNullPtr : 1;
1266 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001267
Richard Smithce40ad62011-11-12 22:28:03 +00001268 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001269 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001270 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001271 SubobjectDesignator &getLValueDesignator() { return Designator; }
1272 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001273 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001274
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001275 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1276 unsigned getLValueVersion() const { return Base.getVersion(); }
1277
Richard Smith2e312c82012-03-03 22:46:17 +00001278 void moveInto(APValue &V) const {
1279 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001280 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001281 else {
1282 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001283 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001284 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001285 }
John McCall45d55e42010-05-07 21:00:08 +00001286 }
Richard Smith2e312c82012-03-03 22:46:17 +00001287 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001288 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001289 Base = V.getLValueBase();
1290 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001291 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001292 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001293 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001294 }
1295
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001296 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001297#ifndef NDEBUG
1298 // We only allow a few types of invalid bases. Enforce that here.
1299 if (BInvalid) {
1300 const auto *E = B.get<const Expr *>();
1301 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1302 "Unexpected type of invalid base");
1303 }
1304#endif
1305
Richard Smithce40ad62011-11-12 22:28:03 +00001306 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001307 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001308 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001309 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001310 IsNullPtr = false;
1311 }
1312
1313 void setNull(QualType PointerTy, uint64_t TargetVal) {
1314 Base = (Expr *)nullptr;
1315 Offset = CharUnits::fromQuantity(TargetVal);
1316 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001317 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1318 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001319 }
1320
George Burgess IV3a03fab2015-09-04 21:28:13 +00001321 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001322 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001323 }
1324
Hubert Tong147b7432018-12-12 16:53:43 +00001325 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001326 // Check that this LValue is not based on a null pointer. If it is, produce
1327 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001328 template <typename GenDiagType>
1329 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001330 if (Designator.Invalid)
1331 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001332 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001333 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001334 Designator.setInvalid();
1335 return false;
1336 }
1337 return true;
1338 }
1339
Hubert Tong147b7432018-12-12 16:53:43 +00001340 public:
1341 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1342 CheckSubobjectKind CSK) {
1343 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1344 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1345 });
1346 }
1347
1348 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1349 AccessKinds AK) {
1350 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1351 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1352 });
1353 }
1354
Richard Smitha8105bc2012-01-06 16:39:00 +00001355 // Check this LValue refers to an object. If not, set the designator to be
1356 // invalid and emit a diagnostic.
1357 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001358 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001359 Designator.checkSubobject(Info, E, CSK);
1360 }
1361
1362 void addDecl(EvalInfo &Info, const Expr *E,
1363 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001364 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1365 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001366 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001367 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1368 if (!Designator.Entries.empty()) {
1369 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1370 Designator.setInvalid();
1371 return;
1372 }
Richard Smithefdb5032017-11-15 03:03:56 +00001373 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1374 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1375 Designator.FirstEntryIsAnUnsizedArray = true;
1376 Designator.addUnsizedArrayUnchecked(ElemTy);
1377 }
George Burgess IVe3763372016-12-22 02:50:20 +00001378 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001379 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001380 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1381 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001382 }
Richard Smith66c96992012-02-18 22:04:06 +00001383 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001384 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1385 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001386 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001387 void clearIsNullPointer() {
1388 IsNullPtr = false;
1389 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001390 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1391 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001392 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1393 // but we're not required to diagnose it and it's valid in C++.)
1394 if (!Index)
1395 return;
1396
1397 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1398 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1399 // offsets.
1400 uint64_t Offset64 = Offset.getQuantity();
1401 uint64_t ElemSize64 = ElementSize.getQuantity();
1402 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1403 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1404
1405 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001406 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001407 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001408 }
1409 void adjustOffset(CharUnits N) {
1410 Offset += N;
1411 if (N.getQuantity())
1412 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001413 }
John McCall45d55e42010-05-07 21:00:08 +00001414 };
Richard Smith027bf112011-11-17 22:56:20 +00001415
1416 struct MemberPtr {
1417 MemberPtr() {}
1418 explicit MemberPtr(const ValueDecl *Decl) :
1419 DeclAndIsDerivedMember(Decl, false), Path() {}
1420
1421 /// The member or (direct or indirect) field referred to by this member
1422 /// pointer, or 0 if this is a null member pointer.
1423 const ValueDecl *getDecl() const {
1424 return DeclAndIsDerivedMember.getPointer();
1425 }
1426 /// Is this actually a member of some type derived from the relevant class?
1427 bool isDerivedMember() const {
1428 return DeclAndIsDerivedMember.getInt();
1429 }
1430 /// Get the class which the declaration actually lives in.
1431 const CXXRecordDecl *getContainingRecord() const {
1432 return cast<CXXRecordDecl>(
1433 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1434 }
1435
Richard Smith2e312c82012-03-03 22:46:17 +00001436 void moveInto(APValue &V) const {
1437 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001438 }
Richard Smith2e312c82012-03-03 22:46:17 +00001439 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001440 assert(V.isMemberPointer());
1441 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1442 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1443 Path.clear();
1444 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1445 Path.insert(Path.end(), P.begin(), P.end());
1446 }
1447
1448 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1449 /// whether the member is a member of some class derived from the class type
1450 /// of the member pointer.
1451 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1452 /// Path - The path of base/derived classes from the member declaration's
1453 /// class (exclusive) to the class type of the member pointer (inclusive).
1454 SmallVector<const CXXRecordDecl*, 4> Path;
1455
1456 /// Perform a cast towards the class of the Decl (either up or down the
1457 /// hierarchy).
1458 bool castBack(const CXXRecordDecl *Class) {
1459 assert(!Path.empty());
1460 const CXXRecordDecl *Expected;
1461 if (Path.size() >= 2)
1462 Expected = Path[Path.size() - 2];
1463 else
1464 Expected = getContainingRecord();
1465 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1466 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1467 // if B does not contain the original member and is not a base or
1468 // derived class of the class containing the original member, the result
1469 // of the cast is undefined.
1470 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1471 // (D::*). We consider that to be a language defect.
1472 return false;
1473 }
1474 Path.pop_back();
1475 return true;
1476 }
1477 /// Perform a base-to-derived member pointer cast.
1478 bool castToDerived(const CXXRecordDecl *Derived) {
1479 if (!getDecl())
1480 return true;
1481 if (!isDerivedMember()) {
1482 Path.push_back(Derived);
1483 return true;
1484 }
1485 if (!castBack(Derived))
1486 return false;
1487 if (Path.empty())
1488 DeclAndIsDerivedMember.setInt(false);
1489 return true;
1490 }
1491 /// Perform a derived-to-base member pointer cast.
1492 bool castToBase(const CXXRecordDecl *Base) {
1493 if (!getDecl())
1494 return true;
1495 if (Path.empty())
1496 DeclAndIsDerivedMember.setInt(true);
1497 if (isDerivedMember()) {
1498 Path.push_back(Base);
1499 return true;
1500 }
1501 return castBack(Base);
1502 }
1503 };
Richard Smith357362d2011-12-13 06:39:58 +00001504
Richard Smith7bb00672012-02-01 01:42:44 +00001505 /// Compare two member pointers, which are assumed to be of the same type.
1506 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1507 if (!LHS.getDecl() || !RHS.getDecl())
1508 return !LHS.getDecl() && !RHS.getDecl();
1509 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1510 return false;
1511 return LHS.Path == RHS.Path;
1512 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001513}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001514
Richard Smith2e312c82012-03-03 22:46:17 +00001515static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001516static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1517 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001518 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001519static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1520 bool InvalidBaseOK = false);
1521static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1522 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001523static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1524 EvalInfo &Info);
1525static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001526static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001527static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001528 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001529static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001530static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001531static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1532 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001533static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001534
Leonard Chand3f3e162019-01-18 21:04:25 +00001535/// Evaluate an integer or fixed point expression into an APResult.
1536static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1537 EvalInfo &Info);
1538
1539/// Evaluate only a fixed point expression into an APResult.
1540static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1541 EvalInfo &Info);
1542
Chris Lattner05706e882008-07-11 18:11:29 +00001543//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001544// Misc utilities
1545//===----------------------------------------------------------------------===//
1546
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001547/// A helper function to create a temporary and set an LValue.
1548template <class KeyTy>
1549static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1550 LValue &LV, CallStackFrame &Frame) {
1551 LV.set({Key, Frame.Info.CurrentCall->Index,
1552 Frame.Info.CurrentCall->getTempVersion()});
1553 return Frame.createTemporary(Key, IsLifetimeExtended);
1554}
1555
Richard Smithd6cc1982017-01-31 02:23:02 +00001556/// Negate an APSInt in place, converting it to a signed form if necessary, and
1557/// preserving its value (by extending by up to one bit as needed).
1558static void negateAsSigned(APSInt &Int) {
1559 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1560 Int = Int.extend(Int.getBitWidth() + 1);
1561 Int.setIsSigned(true);
1562 }
1563 Int = -Int;
1564}
1565
Richard Smith84401042013-06-03 05:03:02 +00001566/// Produce a string describing the given constexpr call.
Nandor Licker950b70d2019-09-13 09:46:16 +00001567void CallStackFrame::describe(raw_ostream &Out) {
Richard Smith84401042013-06-03 05:03:02 +00001568 unsigned ArgIndex = 0;
Nandor Licker950b70d2019-09-13 09:46:16 +00001569 bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1570 !isa<CXXConstructorDecl>(Callee) &&
1571 cast<CXXMethodDecl>(Callee)->isInstance();
Richard Smith84401042013-06-03 05:03:02 +00001572
1573 if (!IsMemberCall)
Nandor Licker950b70d2019-09-13 09:46:16 +00001574 Out << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001575
Nandor Licker950b70d2019-09-13 09:46:16 +00001576 if (This && IsMemberCall) {
Richard Smith84401042013-06-03 05:03:02 +00001577 APValue Val;
Nandor Licker950b70d2019-09-13 09:46:16 +00001578 This->moveInto(Val);
1579 Val.printPretty(Out, Info.Ctx,
1580 This->Designator.MostDerivedType);
Richard Smith84401042013-06-03 05:03:02 +00001581 // FIXME: Add parens around Val if needed.
Nandor Licker950b70d2019-09-13 09:46:16 +00001582 Out << "->" << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001583 IsMemberCall = false;
1584 }
1585
Nandor Licker950b70d2019-09-13 09:46:16 +00001586 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1587 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
Richard Smith84401042013-06-03 05:03:02 +00001588 if (ArgIndex > (unsigned)IsMemberCall)
1589 Out << ", ";
1590
1591 const ParmVarDecl *Param = *I;
Nandor Licker950b70d2019-09-13 09:46:16 +00001592 const APValue &Arg = Arguments[ArgIndex];
1593 Arg.printPretty(Out, Info.Ctx, Param->getType());
Richard Smith84401042013-06-03 05:03:02 +00001594
1595 if (ArgIndex == 0 && IsMemberCall)
Nandor Licker950b70d2019-09-13 09:46:16 +00001596 Out << "->" << *Callee << '(';
Richard Smith84401042013-06-03 05:03:02 +00001597 }
1598
1599 Out << ')';
1600}
1601
Richard Smithd9f663b2013-04-22 15:31:51 +00001602/// Evaluate an expression to see if it had side-effects, and discard its
1603/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001604/// \return \c true if the caller should keep evaluating.
1605static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001606 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001607 if (!Evaluate(Scratch, Info, E))
1608 // We don't need the value, but we might have skipped a side effect here.
1609 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001610 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001611}
1612
Richard Smithd62306a2011-11-10 06:34:14 +00001613/// Should this call expression be treated as a string literal?
1614static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001615 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001616 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1617 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1618}
1619
Richard Smithce40ad62011-11-12 22:28:03 +00001620static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001621 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1622 // constant expression of pointer type that evaluates to...
1623
1624 // ... a null pointer value, or a prvalue core constant expression of type
1625 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001626 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001627
Richard Smithce40ad62011-11-12 22:28:03 +00001628 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1629 // ... the address of an object with static storage duration,
1630 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1631 return VD->hasGlobalStorage();
1632 // ... the address of a function,
1633 return isa<FunctionDecl>(D);
1634 }
1635
Richard Smithee0ce3022019-05-17 07:06:46 +00001636 if (B.is<TypeInfoLValue>())
1637 return true;
1638
Richard Smithce40ad62011-11-12 22:28:03 +00001639 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001640 switch (E->getStmtClass()) {
1641 default:
1642 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001643 case Expr::CompoundLiteralExprClass: {
1644 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1645 return CLE->isFileScope() && CLE->isLValue();
1646 }
Richard Smithe6c01442013-06-05 00:46:14 +00001647 case Expr::MaterializeTemporaryExprClass:
1648 // A materialized temporary might have been lifetime-extended to static
1649 // storage duration.
1650 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001651 // A string literal has static storage duration.
1652 case Expr::StringLiteralClass:
1653 case Expr::PredefinedExprClass:
1654 case Expr::ObjCStringLiteralClass:
1655 case Expr::ObjCEncodeExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001656 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001657 return true;
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001658 case Expr::ObjCBoxedExprClass:
1659 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
Richard Smithd62306a2011-11-10 06:34:14 +00001660 case Expr::CallExprClass:
1661 return IsStringLiteralCall(cast<CallExpr>(E));
1662 // For GCC compatibility, &&label has static storage duration.
1663 case Expr::AddrLabelExprClass:
1664 return true;
1665 // A Block literal expression may be used as the initialization value for
1666 // Block variables at global or local static scope.
1667 case Expr::BlockExprClass:
1668 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001669 case Expr::ImplicitValueInitExprClass:
1670 // FIXME:
1671 // We can never form an lvalue with an implicit value initialization as its
1672 // base through expression evaluation, so these only appear in one case: the
1673 // implicit variable declaration we invent when checking whether a constexpr
1674 // constructor can produce a constant expression. We must assume that such
1675 // an expression might be a global lvalue.
1676 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001677 }
John McCall95007602010-05-10 23:27:23 +00001678}
1679
Richard Smith06f71b52018-08-04 00:57:17 +00001680static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1681 return LVal.Base.dyn_cast<const ValueDecl*>();
1682}
1683
1684static bool IsLiteralLValue(const LValue &Value) {
1685 if (Value.getLValueCallIndex())
1686 return false;
1687 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1688 return E && !isa<MaterializeTemporaryExpr>(E);
1689}
1690
1691static bool IsWeakLValue(const LValue &Value) {
1692 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1693 return Decl && Decl->isWeak();
1694}
1695
1696static bool isZeroSized(const LValue &Value) {
1697 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1698 if (Decl && isa<VarDecl>(Decl)) {
1699 QualType Ty = Decl->getType();
1700 if (Ty->isArrayType())
1701 return Ty->isIncompleteType() ||
1702 Decl->getASTContext().getTypeSize(Ty) == 0;
1703 }
1704 return false;
1705}
1706
1707static bool HasSameBase(const LValue &A, const LValue &B) {
1708 if (!A.getLValueBase())
1709 return !B.getLValueBase();
1710 if (!B.getLValueBase())
1711 return false;
1712
1713 if (A.getLValueBase().getOpaqueValue() !=
1714 B.getLValueBase().getOpaqueValue()) {
1715 const Decl *ADecl = GetLValueBaseDecl(A);
1716 if (!ADecl)
1717 return false;
1718 const Decl *BDecl = GetLValueBaseDecl(B);
1719 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1720 return false;
1721 }
1722
1723 return IsGlobalLValue(A.getLValueBase()) ||
1724 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1725 A.getLValueVersion() == B.getLValueVersion());
1726}
1727
Richard Smithb228a862012-02-15 02:18:13 +00001728static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1729 assert(Base && "no location for a null lvalue");
1730 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1731 if (VD)
1732 Info.Note(VD->getLocation(), diag::note_declared_at);
Richard Smithee0ce3022019-05-17 07:06:46 +00001733 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1734 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1735 // We have no information to show for a typeid(T) object.
Richard Smithb228a862012-02-15 02:18:13 +00001736}
1737
Richard Smith80815602011-11-07 05:07:52 +00001738/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001739/// value for an address or reference constant expression. Return true if we
1740/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001741static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001742 QualType Type, const LValue &LVal,
1743 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001744 bool IsReferenceType = Type->isReferenceType();
1745
Richard Smith357362d2011-12-13 06:39:58 +00001746 APValue::LValueBase Base = LVal.getLValueBase();
1747 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1748
Richard Smith0dea49e2012-02-18 04:58:18 +00001749 // Check that the object is a global. Note that the fake 'this' object we
1750 // manufacture when checking potential constant expressions is conservatively
1751 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001752 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001753 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001754 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001755 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001756 << IsReferenceType << !Designator.Entries.empty()
1757 << !!VD << VD;
1758 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001759 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001760 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001761 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001762 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001763 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001764 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001765 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001766 LVal.getLValueCallIndex() == 0) &&
1767 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001768
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001769 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1770 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001771 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001772 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001773 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001774
Hans Wennborg82dd8772014-06-25 22:19:48 +00001775 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001776 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001777 return false;
1778 }
1779 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1780 // __declspec(dllimport) must be handled very carefully:
1781 // We must never initialize an expression with the thunk in C++.
1782 // Doing otherwise would allow the same id-expression to yield
1783 // different addresses for the same function in different translation
1784 // units. However, this means that we must dynamically initialize the
1785 // expression with the contents of the import address table at runtime.
1786 //
1787 // The C language has no notion of ODR; furthermore, it has no notion of
1788 // dynamic initialization. This means that we are permitted to
1789 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001790 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1791 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001792 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001793 }
1794 }
1795
Richard Smitha8105bc2012-01-06 16:39:00 +00001796 // Allow address constant expressions to be past-the-end pointers. This is
1797 // an extension: the standard requires them to point to an object.
1798 if (!IsReferenceType)
1799 return true;
1800
1801 // A reference constant expression must refer to an object.
1802 if (!Base) {
1803 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001804 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001805 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001806 }
1807
Richard Smith357362d2011-12-13 06:39:58 +00001808 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001809 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001810 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001811 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001812 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001813 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001814 }
1815
Richard Smith80815602011-11-07 05:07:52 +00001816 return true;
1817}
1818
Reid Klecknercd016d82017-07-07 22:04:29 +00001819/// Member pointers are constant expressions unless they point to a
1820/// non-virtual dllimport member function.
1821static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1822 SourceLocation Loc,
1823 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001824 const APValue &Value,
1825 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00001826 const ValueDecl *Member = Value.getMemberPointerDecl();
1827 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1828 if (!FD)
1829 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001830 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1831 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00001832}
1833
Richard Smithfddd3842011-12-30 21:15:51 +00001834/// Check that this core constant expression is of literal type, and if not,
1835/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001836static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001837 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001838 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001839 return true;
1840
Richard Smith7525ff62013-05-09 07:14:00 +00001841 // C++1y: A constant initializer for an object o [...] may also invoke
1842 // constexpr constructors for o and its subobjects even if those objects
1843 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001844 //
1845 // C++11 missed this detail for aggregates, so classes like this:
1846 // struct foo_t { union { int i; volatile int j; } u; };
1847 // are not (obviously) initializable like so:
1848 // __attribute__((__require_constant_initialization__))
1849 // static const foo_t x = {{0}};
1850 // because "i" is a subobject with non-literal initialization (due to the
1851 // volatile member of the union). See:
1852 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1853 // Therefore, we use the C++1y behavior.
1854 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001855 return true;
1856
Richard Smithfddd3842011-12-30 21:15:51 +00001857 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001858 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001859 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001860 << E->getType();
1861 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001862 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001863 return false;
1864}
1865
Richard Smithc667cdc2019-09-18 17:37:44 +00001866enum class CheckEvaluationResultKind {
1867 ConstantExpression,
1868 FullyInitialized,
1869};
1870
Reid Kleckner1a840d22018-05-10 18:57:35 +00001871static bool
Richard Smithc667cdc2019-09-18 17:37:44 +00001872CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info,
1873 SourceLocation DiagLoc, QualType Type,
1874 const APValue &Value, Expr::ConstExprUsage Usage,
1875 SourceLocation SubobjectLoc = SourceLocation()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00001876 if (!Value.hasValue()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001877 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001878 << true << Type;
Richard Smith31c69a32019-05-21 23:15:20 +00001879 if (SubobjectLoc.isValid())
1880 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
Richard Smith1a90f592013-06-18 17:51:51 +00001881 return false;
1882 }
1883
Richard Smith77be48a2014-07-31 06:31:19 +00001884 // We allow _Atomic(T) to be initialized from anything that T can be
1885 // initialized from.
1886 if (const AtomicType *AT = Type->getAs<AtomicType>())
1887 Type = AT->getValueType();
1888
Richard Smithb228a862012-02-15 02:18:13 +00001889 // Core issue 1454: For a literal constant expression of array or class type,
1890 // each subobject of its value shall have been initialized by a constant
1891 // expression.
1892 if (Value.isArray()) {
1893 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1894 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
Richard Smithc667cdc2019-09-18 17:37:44 +00001895 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
1896 Value.getArrayInitializedElt(I), Usage,
1897 SubobjectLoc))
Richard Smithb228a862012-02-15 02:18:13 +00001898 return false;
1899 }
1900 if (!Value.hasArrayFiller())
1901 return true;
Richard Smithc667cdc2019-09-18 17:37:44 +00001902 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
1903 Value.getArrayFiller(), Usage, SubobjectLoc);
Richard Smith80815602011-11-07 05:07:52 +00001904 }
Richard Smithb228a862012-02-15 02:18:13 +00001905 if (Value.isUnion() && Value.getUnionField()) {
Richard Smithc667cdc2019-09-18 17:37:44 +00001906 return CheckEvaluationResult(
1907 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
1908 Value.getUnionValue(), Usage, Value.getUnionField()->getLocation());
Richard Smithb228a862012-02-15 02:18:13 +00001909 }
1910 if (Value.isStruct()) {
1911 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1912 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1913 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001914 for (const CXXBaseSpecifier &BS : CD->bases()) {
Richard Smithc667cdc2019-09-18 17:37:44 +00001915 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
1916 Value.getStructBase(BaseIndex), Usage,
1917 BS.getBeginLoc()))
Richard Smithb228a862012-02-15 02:18:13 +00001918 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001919 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00001920 }
1921 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001922 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001923 if (I->isUnnamedBitfield())
1924 continue;
1925
Richard Smithc667cdc2019-09-18 17:37:44 +00001926 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
1927 Value.getStructField(I->getFieldIndex()),
1928 Usage, I->getLocation()))
Richard Smithb228a862012-02-15 02:18:13 +00001929 return false;
1930 }
1931 }
1932
Richard Smithc667cdc2019-09-18 17:37:44 +00001933 if (Value.isLValue() &&
1934 CERK == CheckEvaluationResultKind::ConstantExpression) {
Richard Smithb228a862012-02-15 02:18:13 +00001935 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001936 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00001937 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001938 }
1939
Richard Smithc667cdc2019-09-18 17:37:44 +00001940 if (Value.isMemberPointer() &&
1941 CERK == CheckEvaluationResultKind::ConstantExpression)
Reid Kleckner1a840d22018-05-10 18:57:35 +00001942 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00001943
Richard Smithb228a862012-02-15 02:18:13 +00001944 // Everything else is fine.
1945 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001946}
1947
Richard Smithc667cdc2019-09-18 17:37:44 +00001948/// Check that this core constant expression value is a valid value for a
1949/// constant expression. If not, report an appropriate diagnostic. Does not
1950/// check that the expression is of literal type.
1951static bool
1952CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1953 const APValue &Value,
1954 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
1955 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
1956 Info, DiagLoc, Type, Value, Usage);
1957}
1958
1959/// Check that this evaluated value is fully-initialized and can be loaded by
1960/// an lvalue-to-rvalue conversion.
1961static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
1962 QualType Type, const APValue &Value) {
1963 return CheckEvaluationResult(CheckEvaluationResultKind::FullyInitialized,
1964 Info, DiagLoc, Type, Value,
1965 Expr::EvaluateForCodeGen);
1966}
1967
Richard Smith2e312c82012-03-03 22:46:17 +00001968static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001969 // A null base expression indicates a null pointer. These are always
1970 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001971 if (!Value.getLValueBase()) {
1972 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001973 return true;
1974 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001975
Richard Smith027bf112011-11-17 22:56:20 +00001976 // We have a non-null base. These are generally known to be true, but if it's
1977 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001978 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001979 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001980 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001981}
1982
Richard Smith2e312c82012-03-03 22:46:17 +00001983static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001984 switch (Val.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00001985 case APValue::None:
1986 case APValue::Indeterminate:
Richard Smith11562c52011-10-28 17:51:58 +00001987 return false;
1988 case APValue::Int:
1989 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001990 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00001991 case APValue::FixedPoint:
1992 Result = Val.getFixedPoint().getBoolValue();
1993 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001994 case APValue::Float:
1995 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001996 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001997 case APValue::ComplexInt:
1998 Result = Val.getComplexIntReal().getBoolValue() ||
1999 Val.getComplexIntImag().getBoolValue();
2000 return true;
2001 case APValue::ComplexFloat:
2002 Result = !Val.getComplexFloatReal().isZero() ||
2003 !Val.getComplexFloatImag().isZero();
2004 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002005 case APValue::LValue:
2006 return EvalPointerValueAsBool(Val, Result);
2007 case APValue::MemberPointer:
2008 Result = Val.getMemberPointerDecl();
2009 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002010 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002011 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002012 case APValue::Struct:
2013 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002014 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002015 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002016 }
2017
Richard Smith11562c52011-10-28 17:51:58 +00002018 llvm_unreachable("unknown APValue kind");
2019}
2020
2021static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2022 EvalInfo &Info) {
2023 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002024 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002025 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002026 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002027 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002028}
2029
Richard Smith357362d2011-12-13 06:39:58 +00002030template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002031static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002032 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002033 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002034 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002035 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002036}
2037
2038static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2039 QualType SrcType, const APFloat &Value,
2040 QualType DestType, APSInt &Result) {
2041 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002042 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002043 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002044
Richard Smith357362d2011-12-13 06:39:58 +00002045 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002046 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002047 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2048 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002049 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002050 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002051}
2052
Richard Smith357362d2011-12-13 06:39:58 +00002053static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2054 QualType SrcType, QualType DestType,
2055 APFloat &Result) {
2056 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002057 bool ignored;
Richard Smith9e52c432019-07-06 21:05:52 +00002058 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2059 APFloat::rmNearestTiesToEven, &ignored);
Richard Smith357362d2011-12-13 06:39:58 +00002060 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002061}
2062
Richard Smith911e1422012-01-30 22:27:01 +00002063static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2064 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002065 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002066 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002067 // Figure out if this is a truncate, extend or noop cast.
2068 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002069 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002070 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002071 if (DestType->isBooleanType())
2072 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002073 return Result;
2074}
2075
Richard Smith357362d2011-12-13 06:39:58 +00002076static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2077 QualType SrcType, const APSInt &Value,
2078 QualType DestType, APFloat &Result) {
2079 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
Richard Smith9e52c432019-07-06 21:05:52 +00002080 Result.convertFromAPInt(Value, Value.isSigned(),
2081 APFloat::rmNearestTiesToEven);
Richard Smith357362d2011-12-13 06:39:58 +00002082 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002083}
2084
Richard Smith49ca8aa2013-08-06 07:09:20 +00002085static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2086 APValue &Value, const FieldDecl *FD) {
2087 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2088
2089 if (!Value.isInt()) {
2090 // Trying to store a pointer-cast-to-integer into a bitfield.
2091 // FIXME: In this case, we should provide the diagnostic for casting
2092 // a pointer to an integer.
2093 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002094 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002095 return false;
2096 }
2097
2098 APSInt &Int = Value.getInt();
2099 unsigned OldBitWidth = Int.getBitWidth();
2100 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2101 if (NewBitWidth < OldBitWidth)
2102 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2103 return true;
2104}
2105
Eli Friedman803acb32011-12-22 03:51:45 +00002106static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2107 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002108 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002109 if (!Evaluate(SVal, Info, E))
2110 return false;
2111 if (SVal.isInt()) {
2112 Res = SVal.getInt();
2113 return true;
2114 }
2115 if (SVal.isFloat()) {
2116 Res = SVal.getFloat().bitcastToAPInt();
2117 return true;
2118 }
2119 if (SVal.isVector()) {
2120 QualType VecTy = E->getType();
2121 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2122 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2123 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2124 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2125 Res = llvm::APInt::getNullValue(VecSize);
2126 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2127 APValue &Elt = SVal.getVectorElt(i);
2128 llvm::APInt EltAsInt;
2129 if (Elt.isInt()) {
2130 EltAsInt = Elt.getInt();
2131 } else if (Elt.isFloat()) {
2132 EltAsInt = Elt.getFloat().bitcastToAPInt();
2133 } else {
2134 // Don't try to handle vectors of anything other than int or float
2135 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002136 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002137 return false;
2138 }
2139 unsigned BaseEltSize = EltAsInt.getBitWidth();
2140 if (BigEndian)
2141 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2142 else
2143 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2144 }
2145 return true;
2146 }
2147 // Give up if the input isn't an int, float, or vector. For example, we
2148 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002149 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002150 return false;
2151}
2152
Richard Smith43e77732013-05-07 04:50:00 +00002153/// Perform the given integer operation, which is known to need at most BitWidth
2154/// bits, and check for overflow in the original type (if that type was not an
2155/// unsigned type).
2156template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002157static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2158 const APSInt &LHS, const APSInt &RHS,
2159 unsigned BitWidth, Operation Op,
2160 APSInt &Result) {
2161 if (LHS.isUnsigned()) {
2162 Result = Op(LHS, RHS);
2163 return true;
2164 }
Richard Smith43e77732013-05-07 04:50:00 +00002165
2166 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002167 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002168 if (Result.extend(BitWidth) != Value) {
Richard Smith045b2272019-09-10 21:24:09 +00002169 if (Info.checkingForUndefinedBehavior())
Richard Smith43e77732013-05-07 04:50:00 +00002170 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002171 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002172 << Result.toString(10) << E->getType();
2173 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002174 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002175 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002176 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002177}
2178
2179/// Perform the given binary integer operation.
2180static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2181 BinaryOperatorKind Opcode, APSInt RHS,
2182 APSInt &Result) {
2183 switch (Opcode) {
2184 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002185 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002186 return false;
2187 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002188 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2189 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002190 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002191 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2192 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002193 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002194 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2195 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002196 case BO_And: Result = LHS & RHS; return true;
2197 case BO_Xor: Result = LHS ^ RHS; return true;
2198 case BO_Or: Result = LHS | RHS; return true;
2199 case BO_Div:
2200 case BO_Rem:
2201 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002202 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002203 return false;
2204 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002205 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2206 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2207 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002208 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2209 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002210 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2211 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002212 return true;
2213 case BO_Shl: {
2214 if (Info.getLangOpts().OpenCL)
2215 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2216 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2217 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2218 RHS.isUnsigned());
2219 else if (RHS.isSigned() && RHS.isNegative()) {
2220 // During constant-folding, a negative shift is an opposite shift. Such
2221 // a shift is not a constant expression.
2222 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2223 RHS = -RHS;
2224 goto shift_right;
2225 }
2226 shift_left:
2227 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2228 // the shifted type.
2229 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2230 if (SA != RHS) {
2231 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2232 << RHS << E->getType() << LHS.getBitWidth();
Richard Smith7939ba02019-06-25 01:45:26 +00002233 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
Richard Smith43e77732013-05-07 04:50:00 +00002234 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2235 // operand, and must not overflow the corresponding unsigned type.
Richard Smith7939ba02019-06-25 01:45:26 +00002236 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2237 // E1 x 2^E2 module 2^N.
Richard Smith43e77732013-05-07 04:50:00 +00002238 if (LHS.isNegative())
2239 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2240 else if (LHS.countLeadingZeros() < SA)
2241 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2242 }
2243 Result = LHS << SA;
2244 return true;
2245 }
2246 case BO_Shr: {
2247 if (Info.getLangOpts().OpenCL)
2248 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2249 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2250 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2251 RHS.isUnsigned());
2252 else if (RHS.isSigned() && RHS.isNegative()) {
2253 // During constant-folding, a negative shift is an opposite shift. Such a
2254 // shift is not a constant expression.
2255 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2256 RHS = -RHS;
2257 goto shift_left;
2258 }
2259 shift_right:
2260 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2261 // shifted type.
2262 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2263 if (SA != RHS)
2264 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2265 << RHS << E->getType() << LHS.getBitWidth();
2266 Result = LHS >> SA;
2267 return true;
2268 }
2269
2270 case BO_LT: Result = LHS < RHS; return true;
2271 case BO_GT: Result = LHS > RHS; return true;
2272 case BO_LE: Result = LHS <= RHS; return true;
2273 case BO_GE: Result = LHS >= RHS; return true;
2274 case BO_EQ: Result = LHS == RHS; return true;
2275 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002276 case BO_Cmp:
2277 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002278 }
2279}
2280
Richard Smith861b5b52013-05-07 23:34:45 +00002281/// Perform the given binary floating-point operation, in-place, on LHS.
2282static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2283 APFloat &LHS, BinaryOperatorKind Opcode,
2284 const APFloat &RHS) {
2285 switch (Opcode) {
2286 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002287 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002288 return false;
2289 case BO_Mul:
2290 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2291 break;
2292 case BO_Add:
2293 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2294 break;
2295 case BO_Sub:
2296 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2297 break;
2298 case BO_Div:
Richard Smith9e52c432019-07-06 21:05:52 +00002299 // [expr.mul]p4:
2300 // If the second operand of / or % is zero the behavior is undefined.
2301 if (RHS.isZero())
2302 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
Richard Smith861b5b52013-05-07 23:34:45 +00002303 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2304 break;
2305 }
2306
Richard Smith9e52c432019-07-06 21:05:52 +00002307 // [expr.pre]p4:
2308 // If during the evaluation of an expression, the result is not
2309 // mathematically defined [...], the behavior is undefined.
2310 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2311 if (LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002312 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002313 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002314 }
Richard Smith861b5b52013-05-07 23:34:45 +00002315 return true;
2316}
2317
Richard Smitha8105bc2012-01-06 16:39:00 +00002318/// Cast an lvalue referring to a base subobject to a derived class, by
2319/// truncating the lvalue's path to the given length.
2320static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2321 const RecordDecl *TruncatedType,
2322 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002323 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002324
2325 // Check we actually point to a derived class object.
2326 if (TruncatedElements == D.Entries.size())
2327 return true;
2328 assert(TruncatedElements >= D.MostDerivedPathLength &&
2329 "not casting to a derived class");
2330 if (!Result.checkSubobject(Info, E, CSK_Derived))
2331 return false;
2332
2333 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002334 const RecordDecl *RD = TruncatedType;
2335 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002336 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002337 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2338 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002339 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002340 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002341 else
Richard Smithd62306a2011-11-10 06:34:14 +00002342 Result.Offset -= Layout.getBaseClassOffset(Base);
2343 RD = Base;
2344 }
Richard Smith027bf112011-11-17 22:56:20 +00002345 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002346 return true;
2347}
2348
John McCalld7bca762012-05-01 00:38:49 +00002349static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002350 const CXXRecordDecl *Derived,
2351 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002352 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002353 if (!RL) {
2354 if (Derived->isInvalidDecl()) return false;
2355 RL = &Info.Ctx.getASTRecordLayout(Derived);
2356 }
2357
Richard Smithd62306a2011-11-10 06:34:14 +00002358 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002359 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002360 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002361}
2362
Richard Smitha8105bc2012-01-06 16:39:00 +00002363static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002364 const CXXRecordDecl *DerivedDecl,
2365 const CXXBaseSpecifier *Base) {
2366 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2367
John McCalld7bca762012-05-01 00:38:49 +00002368 if (!Base->isVirtual())
2369 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002370
Richard Smitha8105bc2012-01-06 16:39:00 +00002371 SubobjectDesignator &D = Obj.Designator;
2372 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002373 return false;
2374
Richard Smitha8105bc2012-01-06 16:39:00 +00002375 // Extract most-derived object and corresponding type.
2376 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2377 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2378 return false;
2379
2380 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002381 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002382 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2383 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002384 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002385 return true;
2386}
2387
Richard Smith84401042013-06-03 05:03:02 +00002388static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2389 QualType Type, LValue &Result) {
2390 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2391 PathE = E->path_end();
2392 PathI != PathE; ++PathI) {
2393 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2394 *PathI))
2395 return false;
2396 Type = (*PathI)->getType();
2397 }
2398 return true;
2399}
2400
Richard Smith921f1322019-05-13 23:35:21 +00002401/// Cast an lvalue referring to a derived class to a known base subobject.
2402static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2403 const CXXRecordDecl *DerivedRD,
2404 const CXXRecordDecl *BaseRD) {
2405 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2406 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2407 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2408 llvm_unreachable("Class must be derived from the passed in base class!");
2409
2410 for (CXXBasePathElement &Elem : Paths.front())
2411 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2412 return false;
2413 return true;
2414}
2415
Richard Smithd62306a2011-11-10 06:34:14 +00002416/// Update LVal to refer to the given field, which must be a member of the type
2417/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002418static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002419 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002420 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002421 if (!RL) {
2422 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002423 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002424 }
Richard Smithd62306a2011-11-10 06:34:14 +00002425
2426 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002427 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002428 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002429 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002430}
2431
Richard Smith1b78b3d2012-01-25 22:15:11 +00002432/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002433static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002434 LValue &LVal,
2435 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002436 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002437 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002438 return false;
2439 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002440}
2441
Richard Smithd62306a2011-11-10 06:34:14 +00002442/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002443static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2444 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002445 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2446 // extension.
2447 if (Type->isVoidType() || Type->isFunctionType()) {
2448 Size = CharUnits::One();
2449 return true;
2450 }
2451
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002452 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002453 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002454 return false;
2455 }
2456
Richard Smithd62306a2011-11-10 06:34:14 +00002457 if (!Type->isConstantSizeType()) {
2458 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002459 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002460 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002461 return false;
2462 }
2463
2464 Size = Info.Ctx.getTypeSizeInChars(Type);
2465 return true;
2466}
2467
2468/// Update a pointer value to model pointer arithmetic.
2469/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002470/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002471/// \param LVal - The pointer value to be updated.
2472/// \param EltTy - The pointee type represented by LVal.
2473/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002474static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2475 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002476 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002477 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002478 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002479 return false;
2480
Yaxun Liu402804b2016-12-15 08:09:08 +00002481 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002482 return true;
2483}
2484
Richard Smithd6cc1982017-01-31 02:23:02 +00002485static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2486 LValue &LVal, QualType EltTy,
2487 int64_t Adjustment) {
2488 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2489 APSInt::get(Adjustment));
2490}
2491
Richard Smith66c96992012-02-18 22:04:06 +00002492/// Update an lvalue to refer to a component of a complex number.
2493/// \param Info - Information about the ongoing evaluation.
2494/// \param LVal - The lvalue to be updated.
2495/// \param EltTy - The complex number's component type.
2496/// \param Imag - False for the real component, true for the imaginary.
2497static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2498 LValue &LVal, QualType EltTy,
2499 bool Imag) {
2500 if (Imag) {
2501 CharUnits SizeOfComponent;
2502 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2503 return false;
2504 LVal.Offset += SizeOfComponent;
2505 }
2506 LVal.addComplex(Info, E, EltTy, Imag);
2507 return true;
2508}
2509
Richard Smith27908702011-10-24 17:54:18 +00002510/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002511///
2512/// \param Info Information about the ongoing evaluation.
2513/// \param E An expression to be used when printing diagnostics.
2514/// \param VD The variable whose initializer should be obtained.
2515/// \param Frame The frame in which the variable was created. Must be null
2516/// if this variable is not local to the evaluation.
2517/// \param Result Filled in with a pointer to the value of the variable.
2518static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2519 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002520 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002521
Richard Smith254a73d2011-10-28 22:34:42 +00002522 // If this is a parameter to an active constexpr function call, perform
2523 // argument substitution.
2524 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002525 // Assume arguments of a potential constant expression are unknown
2526 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002527 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002528 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002529 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002530 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002531 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002532 }
Richard Smith3229b742013-05-05 21:17:10 +00002533 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002534 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002535 }
Richard Smith27908702011-10-24 17:54:18 +00002536
Richard Smithd9f663b2013-04-22 15:31:51 +00002537 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002538 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002539 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2540 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002541 if (!Result) {
2542 // Assume variables referenced within a lambda's call operator that were
2543 // not declared within the call operator are captures and during checking
2544 // of a potential constant expression, assume they are unknown constant
2545 // expressions.
2546 assert(isLambdaCallOperator(Frame->Callee) &&
2547 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2548 "missing value for local variable");
2549 if (Info.checkingPotentialConstantExpression())
2550 return false;
2551 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002552 Info.FFDiag(E->getBeginLoc(),
2553 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002554 << "captures not currently allowed";
2555 return false;
2556 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002557 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002558 }
2559
Richard Smithd0b4dd62011-12-19 06:19:21 +00002560 // Dig out the initializer, and use the declaration which it's attached to.
2561 const Expr *Init = VD->getAnyInitializer(VD);
2562 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002563 // If we're checking a potential constant expression, the variable could be
2564 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002565 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002566 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002567 return false;
2568 }
2569
Richard Smithd62306a2011-11-10 06:34:14 +00002570 // If we're currently evaluating the initializer of this declaration, use that
2571 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002572 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002573 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002574 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002575 }
2576
Richard Smithcecf1842011-11-01 21:06:14 +00002577 // Never evaluate the initializer of a weak variable. We can't be sure that
2578 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002579 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002580 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002581 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002582 }
Richard Smithcecf1842011-11-01 21:06:14 +00002583
Richard Smithd0b4dd62011-12-19 06:19:21 +00002584 // Check that we can fold the initializer. In C++, we will have already done
2585 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002586 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002587 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002588 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002589 Notes.size() + 1) << VD;
2590 Info.Note(VD->getLocation(), diag::note_declared_at);
2591 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002592 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002593 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002594 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002595 Notes.size() + 1) << VD;
2596 Info.Note(VD->getLocation(), diag::note_declared_at);
2597 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002598 }
Richard Smith27908702011-10-24 17:54:18 +00002599
Richard Smith3229b742013-05-05 21:17:10 +00002600 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002601 return true;
Richard Smith27908702011-10-24 17:54:18 +00002602}
2603
Richard Smith11562c52011-10-28 17:51:58 +00002604static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002605 Qualifiers Quals = T.getQualifiers();
2606 return Quals.hasConst() && !Quals.hasVolatile();
2607}
2608
Richard Smithe97cbd72011-11-11 04:05:33 +00002609/// Get the base index of the given base class within an APValue representing
2610/// the given derived class.
2611static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2612 const CXXRecordDecl *Base) {
2613 Base = Base->getCanonicalDecl();
2614 unsigned Index = 0;
2615 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2616 E = Derived->bases_end(); I != E; ++I, ++Index) {
2617 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2618 return Index;
2619 }
2620
2621 llvm_unreachable("base class missing from derived class's bases list");
2622}
2623
Richard Smith3da88fa2013-04-26 14:36:30 +00002624/// Extract the value of a character from a string literal.
2625static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2626 uint64_t Index) {
Eric Fiselier708afb52019-05-16 21:04:15 +00002627 assert(!isa<SourceLocExpr>(Lit) &&
2628 "SourceLocExpr should have already been converted to a StringLiteral");
2629
Akira Hatanakabc332642017-01-31 02:31:39 +00002630 // FIXME: Support MakeStringConstant
2631 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2632 std::string Str;
2633 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2634 assert(Index <= Str.size() && "Index too large");
2635 return APSInt::getUnsigned(Str.c_str()[Index]);
2636 }
2637
Alexey Bataevec474782014-10-09 08:45:04 +00002638 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2639 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002640 const StringLiteral *S = cast<StringLiteral>(Lit);
2641 const ConstantArrayType *CAT =
2642 Info.Ctx.getAsConstantArrayType(S->getType());
2643 assert(CAT && "string literal isn't an array");
2644 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002645 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002646
2647 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002648 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002649 if (Index < S->getLength())
2650 Value = S->getCodeUnit(Index);
2651 return Value;
2652}
2653
Richard Smith3da88fa2013-04-26 14:36:30 +00002654// Expand a string literal into an array of characters.
Eli Friedman3bf72d72019-02-08 21:18:46 +00002655//
2656// FIXME: This is inefficient; we should probably introduce something similar
2657// to the LLVM ConstantDataArray to make this cheaper.
2658static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
Richard Smith3da88fa2013-04-26 14:36:30 +00002659 APValue &Result) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002660 const ConstantArrayType *CAT =
2661 Info.Ctx.getAsConstantArrayType(S->getType());
2662 assert(CAT && "string literal isn't an array");
2663 QualType CharType = CAT->getElementType();
2664 assert(CharType->isIntegerType() && "unexpected character type");
2665
2666 unsigned Elts = CAT->getSize().getZExtValue();
2667 Result = APValue(APValue::UninitArray(),
2668 std::min(S->getLength(), Elts), Elts);
2669 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2670 CharType->isUnsignedIntegerType());
2671 if (Result.hasArrayFiller())
2672 Result.getArrayFiller() = APValue(Value);
2673 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2674 Value = S->getCodeUnit(I);
2675 Result.getArrayInitializedElt(I) = APValue(Value);
2676 }
2677}
2678
2679// Expand an array so that it has more than Index filled elements.
2680static void expandArray(APValue &Array, unsigned Index) {
2681 unsigned Size = Array.getArraySize();
2682 assert(Index < Size);
2683
2684 // Always at least double the number of elements for which we store a value.
2685 unsigned OldElts = Array.getArrayInitializedElts();
2686 unsigned NewElts = std::max(Index+1, OldElts * 2);
2687 NewElts = std::min(Size, std::max(NewElts, 8u));
2688
2689 // Copy the data across.
2690 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2691 for (unsigned I = 0; I != OldElts; ++I)
2692 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2693 for (unsigned I = OldElts; I != NewElts; ++I)
2694 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2695 if (NewValue.hasArrayFiller())
2696 NewValue.getArrayFiller() = Array.getArrayFiller();
2697 Array.swap(NewValue);
2698}
2699
Richard Smithb01fe402014-09-16 01:24:02 +00002700/// Determine whether a type would actually be read by an lvalue-to-rvalue
2701/// conversion. If it's of class type, we may assume that the copy operation
2702/// is trivial. Note that this is never true for a union type with fields
2703/// (because the copy always "reads" the active member) and always true for
2704/// a non-class type.
2705static bool isReadByLvalueToRvalueConversion(QualType T) {
2706 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2707 if (!RD || (RD->isUnion() && !RD->field_empty()))
2708 return true;
2709 if (RD->isEmpty())
2710 return false;
2711
2712 for (auto *Field : RD->fields())
2713 if (isReadByLvalueToRvalueConversion(Field->getType()))
2714 return true;
2715
2716 for (auto &BaseSpec : RD->bases())
2717 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2718 return true;
2719
2720 return false;
2721}
2722
2723/// Diagnose an attempt to read from any unreadable field within the specified
2724/// type, which might be a class type.
2725static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2726 QualType T) {
2727 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2728 if (!RD)
2729 return false;
2730
2731 if (!RD->hasMutableFields())
2732 return false;
2733
2734 for (auto *Field : RD->fields()) {
2735 // If we're actually going to read this field in some way, then it can't
2736 // be mutable. If we're in a union, then assigning to a mutable field
2737 // (even an empty one) can change the active member, so that's not OK.
2738 // FIXME: Add core issue number for the union case.
2739 if (Field->isMutable() &&
2740 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002741 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002742 Info.Note(Field->getLocation(), diag::note_declared_at);
2743 return true;
2744 }
2745
2746 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2747 return true;
2748 }
2749
2750 for (auto &BaseSpec : RD->bases())
2751 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2752 return true;
2753
2754 // All mutable fields were empty, and thus not actually read.
2755 return false;
2756}
2757
Richard Smithdebad642019-05-12 09:39:08 +00002758static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2759 APValue::LValueBase Base) {
2760 // A temporary we created.
2761 if (Base.getCallIndex())
2762 return true;
2763
2764 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2765 if (!Evaluating)
2766 return false;
2767
2768 // The variable whose initializer we're evaluating.
2769 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2770 if (declaresSameEntity(Evaluating, BaseD))
2771 return true;
2772
2773 // A temporary lifetime-extended by the variable whose initializer we're
2774 // evaluating.
2775 if (auto *BaseE = Base.dyn_cast<const Expr *>())
2776 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2777 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2778 return true;
2779
2780 return false;
2781}
2782
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002783namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002784/// A handle to a complete object (an object that is not a subobject of
2785/// another object).
2786struct CompleteObject {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002787 /// The identity of the object.
2788 APValue::LValueBase Base;
Richard Smith3229b742013-05-05 21:17:10 +00002789 /// The value of the complete object.
2790 APValue *Value;
2791 /// The type of the complete object.
2792 QualType Type;
2793
Craig Topper36250ad2014-05-12 05:36:57 +00002794 CompleteObject() : Value(nullptr) {}
Richard Smithdebad642019-05-12 09:39:08 +00002795 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2796 : Base(Base), Value(Value), Type(Type) {}
2797
2798 bool mayReadMutableMembers(EvalInfo &Info) const {
2799 // In C++14 onwards, it is permitted to read a mutable member whose
2800 // lifetime began within the evaluation.
2801 // FIXME: Should we also allow this in C++11?
2802 if (!Info.getLangOpts().CPlusPlus14)
2803 return false;
2804 return lifetimeStartedInEvaluation(Info, Base);
Richard Smith3229b742013-05-05 21:17:10 +00002805 }
2806
Richard Smithdebad642019-05-12 09:39:08 +00002807 explicit operator bool() const { return !Type.isNull(); }
Richard Smith3229b742013-05-05 21:17:10 +00002808};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002809} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002810
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002811static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2812 bool IsMutable = false) {
2813 // C++ [basic.type.qualifier]p1:
2814 // - A const object is an object of type const T or a non-mutable subobject
2815 // of a const object.
2816 if (ObjType.isConstQualified() && !IsMutable)
2817 SubobjType.addConst();
2818 // - A volatile object is an object of type const T or a subobject of a
2819 // volatile object.
2820 if (ObjType.isVolatileQualified())
2821 SubobjType.addVolatile();
2822 return SubobjType;
2823}
2824
Richard Smith3da88fa2013-04-26 14:36:30 +00002825/// Find the designated sub-object of an rvalue.
2826template<typename SubobjectHandler>
2827typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002828findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002829 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002830 if (Sub.Invalid)
2831 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002832 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002833 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002834 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002835 Info.FFDiag(E, Sub.isOnePastTheEnd()
2836 ? diag::note_constexpr_access_past_end
2837 : diag::note_constexpr_access_unsized_array)
2838 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002839 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002840 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002841 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002842 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002843
Richard Smith3229b742013-05-05 21:17:10 +00002844 APValue *O = Obj.Value;
2845 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002846 const FieldDecl *LastField = nullptr;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002847 const FieldDecl *VolatileField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002848
Richard Smithd62306a2011-11-10 06:34:14 +00002849 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002850 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
Richard Smith31c69a32019-05-21 23:15:20 +00002851 // Reading an indeterminate value is undefined, but assigning over one is OK.
Richard Smithc667cdc2019-09-18 17:37:44 +00002852 if (O->isAbsent() ||
2853 (O->isIndeterminate() && handler.AccessKind != AK_Assign &&
2854 handler.AccessKind != AK_ReadObjectRepresentation)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002855 if (!Info.checkingPotentialConstantExpression())
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002856 Info.FFDiag(E, diag::note_constexpr_access_uninit)
Richard Smithe637cbe2019-05-21 23:15:18 +00002857 << handler.AccessKind << O->isIndeterminate();
Richard Smith08d6a2c2013-07-24 07:11:57 +00002858 return handler.failed();
2859 }
2860
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002861 // C++ [class.ctor]p5:
2862 // const and volatile semantics are not applied on an object under
2863 // construction.
2864 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
2865 ObjType->isRecordType() &&
2866 Info.isEvaluatingConstructor(
2867 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
2868 Sub.Entries.begin() + I)) !=
2869 ConstructionPhase::None) {
2870 ObjType = Info.Ctx.getCanonicalType(ObjType);
2871 ObjType.removeLocalConst();
2872 ObjType.removeLocalVolatile();
2873 }
2874
2875 // If this is our last pass, check that the final object type is OK.
2876 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
2877 // Accesses to volatile objects are prohibited.
Richard Smith7bd54ab2019-05-15 20:22:21 +00002878 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002879 if (Info.getLangOpts().CPlusPlus) {
2880 int DiagKind;
2881 SourceLocation Loc;
2882 const NamedDecl *Decl = nullptr;
2883 if (VolatileField) {
2884 DiagKind = 2;
2885 Loc = VolatileField->getLocation();
2886 Decl = VolatileField;
2887 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
2888 DiagKind = 1;
2889 Loc = VD->getLocation();
2890 Decl = VD;
2891 } else {
2892 DiagKind = 0;
2893 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
2894 Loc = E->getExprLoc();
2895 }
2896 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2897 << handler.AccessKind << DiagKind << Decl;
2898 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
2899 } else {
2900 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2901 }
2902 return handler.failed();
2903 }
2904
Richard Smithb01fe402014-09-16 01:24:02 +00002905 // If we are reading an object of class type, there may still be more
2906 // things we need to check: if there are any mutable subobjects, we
2907 // cannot perform this read. (This only happens when performing a trivial
2908 // copy or assignment.)
Richard Smithc667cdc2019-09-18 17:37:44 +00002909 if (ObjType->isRecordType() && isRead(handler.AccessKind) &&
Richard Smithdebad642019-05-12 09:39:08 +00002910 !Obj.mayReadMutableMembers(Info) &&
2911 diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002912 return handler.failed();
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002913 }
Richard Smithb01fe402014-09-16 01:24:02 +00002914
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002915 if (I == N) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00002916 if (!handler.found(*O, ObjType))
2917 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002918
Richard Smith49ca8aa2013-08-06 07:09:20 +00002919 // If we modified a bit-field, truncate it to the right width.
Richard Smithdebad642019-05-12 09:39:08 +00002920 if (isModification(handler.AccessKind) &&
Richard Smith49ca8aa2013-08-06 07:09:20 +00002921 LastField && LastField->isBitField() &&
2922 !truncateBitfieldValue(Info, E, *O, LastField))
2923 return false;
2924
2925 return true;
2926 }
2927
Craig Topper36250ad2014-05-12 05:36:57 +00002928 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002929 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002930 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002931 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002932 assert(CAT && "vla in literal type?");
Richard Smith5b5e27a2019-05-10 20:05:31 +00002933 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002934 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002935 // Note, it should not be possible to form a pointer with a valid
2936 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002937 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002938 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002939 << handler.AccessKind;
2940 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002941 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002942 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002943 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002944
2945 ObjType = CAT->getElementType();
2946
Richard Smith3da88fa2013-04-26 14:36:30 +00002947 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002948 O = &O->getArrayInitializedElt(Index);
Richard Smithc667cdc2019-09-18 17:37:44 +00002949 else if (!isRead(handler.AccessKind)) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002950 expandArray(*O, Index);
2951 O = &O->getArrayInitializedElt(Index);
2952 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002953 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002954 } else if (ObjType->isAnyComplexType()) {
2955 // Next subobject is a complex number.
Richard Smith5b5e27a2019-05-10 20:05:31 +00002956 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smith66c96992012-02-18 22:04:06 +00002957 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002958 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002959 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002960 << handler.AccessKind;
2961 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002962 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002963 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002964 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002965
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002966 ObjType = getSubobjectType(
2967 ObjType, ObjType->castAs<ComplexType>()->getElementType());
Richard Smith3da88fa2013-04-26 14:36:30 +00002968
Richard Smith66c96992012-02-18 22:04:06 +00002969 assert(I == N - 1 && "extracting subobject of scalar?");
2970 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002971 return handler.found(Index ? O->getComplexIntImag()
2972 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002973 } else {
2974 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002975 return handler.found(Index ? O->getComplexFloatImag()
2976 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002977 }
Richard Smithd62306a2011-11-10 06:34:14 +00002978 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithc667cdc2019-09-18 17:37:44 +00002979 if (Field->isMutable() && isRead(handler.AccessKind) &&
Richard Smithdebad642019-05-12 09:39:08 +00002980 !Obj.mayReadMutableMembers(Info)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002981 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002982 << Field;
2983 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002984 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002985 }
2986
Richard Smithd62306a2011-11-10 06:34:14 +00002987 // Next subobject is a class, struct or union field.
2988 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2989 if (RD->isUnion()) {
2990 const FieldDecl *UnionField = O->getUnionField();
2991 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002992 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002993 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002994 << handler.AccessKind << Field << !UnionField << UnionField;
2995 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002996 }
Richard Smithd62306a2011-11-10 06:34:14 +00002997 O = &O->getUnionValue();
2998 } else
2999 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00003000
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003001 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
Richard Smith49ca8aa2013-08-06 07:09:20 +00003002 LastField = Field;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003003 if (Field->getType().isVolatileQualified())
3004 VolatileField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00003005 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00003006 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00003007 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3008 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3009 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00003010
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003011 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
Richard Smithf3e9e432011-11-07 09:22:26 +00003012 }
3013 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003014}
3015
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003016namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003017struct ExtractSubobjectHandler {
3018 EvalInfo &Info;
Richard Smithc667cdc2019-09-18 17:37:44 +00003019 const Expr *E;
Richard Smith3229b742013-05-05 21:17:10 +00003020 APValue &Result;
Richard Smithc667cdc2019-09-18 17:37:44 +00003021 const AccessKinds AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00003022
3023 typedef bool result_type;
3024 bool failed() { return false; }
3025 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003026 Result = Subobj;
Richard Smithc667cdc2019-09-18 17:37:44 +00003027 if (AccessKind == AK_ReadObjectRepresentation)
3028 return true;
3029 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
Richard Smith3da88fa2013-04-26 14:36:30 +00003030 }
3031 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003032 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003033 return true;
3034 }
3035 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003036 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003037 return true;
3038 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003039};
Richard Smith3229b742013-05-05 21:17:10 +00003040} // end anonymous namespace
3041
Richard Smith3da88fa2013-04-26 14:36:30 +00003042/// Extract the designated sub-object of an rvalue.
3043static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003044 const CompleteObject &Obj,
Richard Smithc667cdc2019-09-18 17:37:44 +00003045 const SubobjectDesignator &Sub, APValue &Result,
3046 AccessKinds AK = AK_Read) {
3047 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3048 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
Richard Smith3229b742013-05-05 21:17:10 +00003049 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003050}
3051
Richard Smith3229b742013-05-05 21:17:10 +00003052namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003053struct ModifySubobjectHandler {
3054 EvalInfo &Info;
3055 APValue &NewVal;
3056 const Expr *E;
3057
3058 typedef bool result_type;
3059 static const AccessKinds AccessKind = AK_Assign;
3060
3061 bool checkConst(QualType QT) {
3062 // Assigning to a const object has undefined behavior.
3063 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003064 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003065 return false;
3066 }
3067 return true;
3068 }
3069
3070 bool failed() { return false; }
3071 bool found(APValue &Subobj, QualType SubobjType) {
3072 if (!checkConst(SubobjType))
3073 return false;
3074 // We've been given ownership of NewVal, so just swap it in.
3075 Subobj.swap(NewVal);
3076 return true;
3077 }
3078 bool found(APSInt &Value, QualType SubobjType) {
3079 if (!checkConst(SubobjType))
3080 return false;
3081 if (!NewVal.isInt()) {
3082 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003083 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003084 return false;
3085 }
3086 Value = NewVal.getInt();
3087 return true;
3088 }
3089 bool found(APFloat &Value, QualType SubobjType) {
3090 if (!checkConst(SubobjType))
3091 return false;
3092 Value = NewVal.getFloat();
3093 return true;
3094 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003095};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003096} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003097
Richard Smith3229b742013-05-05 21:17:10 +00003098const AccessKinds ModifySubobjectHandler::AccessKind;
3099
Richard Smith3da88fa2013-04-26 14:36:30 +00003100/// Update the designated sub-object of an rvalue to the given value.
3101static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003102 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003103 const SubobjectDesignator &Sub,
3104 APValue &NewVal) {
3105 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003106 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003107}
3108
Richard Smith84f6dcf2012-02-02 01:16:57 +00003109/// Find the position where two subobject designators diverge, or equivalently
3110/// the length of the common initial subsequence.
3111static unsigned FindDesignatorMismatch(QualType ObjType,
3112 const SubobjectDesignator &A,
3113 const SubobjectDesignator &B,
3114 bool &WasArrayIndex) {
3115 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3116 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003117 if (!ObjType.isNull() &&
3118 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003119 // Next subobject is an array element.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003120 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003121 WasArrayIndex = true;
3122 return I;
3123 }
Richard Smith66c96992012-02-18 22:04:06 +00003124 if (ObjType->isAnyComplexType())
3125 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3126 else
3127 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003128 } else {
Richard Smith5b5e27a2019-05-10 20:05:31 +00003129 if (A.Entries[I].getAsBaseOrMember() !=
3130 B.Entries[I].getAsBaseOrMember()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003131 WasArrayIndex = false;
3132 return I;
3133 }
3134 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3135 // Next subobject is a field.
3136 ObjType = FD->getType();
3137 else
3138 // Next subobject is a base class.
3139 ObjType = QualType();
3140 }
3141 }
3142 WasArrayIndex = false;
3143 return I;
3144}
3145
3146/// Determine whether the given subobject designators refer to elements of the
3147/// same array object.
3148static bool AreElementsOfSameArray(QualType ObjType,
3149 const SubobjectDesignator &A,
3150 const SubobjectDesignator &B) {
3151 if (A.Entries.size() != B.Entries.size())
3152 return false;
3153
George Burgess IVa51c4072015-10-16 01:49:01 +00003154 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003155 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3156 // A is a subobject of the array element.
3157 return false;
3158
3159 // If A (and B) designates an array element, the last entry will be the array
3160 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3161 // of length 1' case, and the entire path must match.
3162 bool WasArrayIndex;
3163 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3164 return CommonLength >= A.Entries.size() - IsArray;
3165}
3166
Richard Smith3229b742013-05-05 21:17:10 +00003167/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003168static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3169 AccessKinds AK, const LValue &LVal,
3170 QualType LValType) {
Richard Smith51ce8442019-05-17 08:01:34 +00003171 if (LVal.InvalidBase) {
3172 Info.FFDiag(E);
3173 return CompleteObject();
3174 }
3175
Richard Smith3229b742013-05-05 21:17:10 +00003176 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003177 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003178 return CompleteObject();
3179 }
3180
Craig Topper36250ad2014-05-12 05:36:57 +00003181 CallStackFrame *Frame = nullptr;
Richard Smith37be3362019-05-04 04:00:45 +00003182 unsigned Depth = 0;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003183 if (LVal.getLValueCallIndex()) {
Richard Smith37be3362019-05-04 04:00:45 +00003184 std::tie(Frame, Depth) =
3185 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003186 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003187 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003188 << AK << LVal.Base.is<const ValueDecl*>();
3189 NoteLValueLocation(Info, LVal.Base);
3190 return CompleteObject();
3191 }
Richard Smith3229b742013-05-05 21:17:10 +00003192 }
3193
Richard Smith7bd54ab2019-05-15 20:22:21 +00003194 bool IsAccess = isFormalAccess(AK);
3195
Richard Smith3229b742013-05-05 21:17:10 +00003196 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3197 // is not a constant expression (even if the object is non-volatile). We also
3198 // apply this rule to C++98, in order to conform to the expected 'volatile'
3199 // semantics.
Richard Smith7bd54ab2019-05-15 20:22:21 +00003200 if (IsAccess && LValType.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003201 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003202 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003203 << AK << LValType;
3204 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003205 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003206 return CompleteObject();
3207 }
3208
3209 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003210 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003211 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00003212
3213 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3214 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3215 // In C++11, constexpr, non-volatile variables initialized with constant
3216 // expressions are constant expressions too. Inside constexpr functions,
3217 // parameters are constant expressions even if they're non-const.
3218 // In C++1y, objects local to a constant expression (those with a Frame) are
3219 // both readable and writable inside constant expressions.
3220 // In C, such things can also be folded, although they are not ICEs.
3221 const VarDecl *VD = dyn_cast<VarDecl>(D);
3222 if (VD) {
3223 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3224 VD = VDef;
3225 }
3226 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003227 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003228 return CompleteObject();
3229 }
3230
Richard Smith3229b742013-05-05 21:17:10 +00003231 // Unless we're looking at a local variable or argument in a constexpr call,
3232 // the variable we're reading must be const.
3233 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003234 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smithdebad642019-05-12 09:39:08 +00003235 declaresSameEntity(
3236 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003237 // OK, we can read and modify an object if we're in the process of
3238 // evaluating its initializer, because its lifetime began in this
3239 // evaluation.
Richard Smithdebad642019-05-12 09:39:08 +00003240 } else if (isModification(AK)) {
3241 // All the remaining cases do not permit modification of the object.
Faisal Valie690b7a2016-07-02 22:34:24 +00003242 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003243 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003244 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003245 // OK, we can read this variable.
3246 } else if (BaseType->isIntegralOrEnumerationType()) {
Richard Smithdebad642019-05-12 09:39:08 +00003247 // In OpenCL if a variable is in constant address space it is a const
3248 // value.
Xiuli Pan244e3f62016-06-07 04:34:00 +00003249 if (!(BaseType.isConstQualified() ||
3250 (Info.getLangOpts().OpenCL &&
3251 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003252 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003253 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003254 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003255 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003256 Info.Note(VD->getLocation(), diag::note_declared_at);
3257 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003258 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003259 }
3260 return CompleteObject();
3261 }
Richard Smith7bd54ab2019-05-15 20:22:21 +00003262 } else if (!IsAccess) {
Richard Smithdebad642019-05-12 09:39:08 +00003263 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003264 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3265 // We support folding of const floating-point types, in order to make
3266 // static const data members of such types (supported as an extension)
3267 // more useful.
3268 if (Info.getLangOpts().CPlusPlus11) {
3269 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3270 Info.Note(VD->getLocation(), diag::note_declared_at);
3271 } else {
3272 Info.CCEDiag(E);
3273 }
George Burgess IVb5316982016-12-27 05:33:20 +00003274 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3275 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3276 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003277 } else {
3278 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003279 if (Info.checkingPotentialConstantExpression() &&
3280 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3281 // The definition of this variable could be constexpr. We can't
3282 // access it right now, but may be able to in future.
3283 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003284 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003285 Info.Note(VD->getLocation(), diag::note_declared_at);
3286 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003287 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003288 }
3289 return CompleteObject();
3290 }
3291 }
3292
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003293 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003294 return CompleteObject();
3295 } else {
3296 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3297
3298 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003299 if (const MaterializeTemporaryExpr *MTE =
Richard Smithee0ce3022019-05-17 07:06:46 +00003300 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
Richard Smithe6c01442013-06-05 00:46:14 +00003301 assert(MTE->getStorageDuration() == SD_Static &&
3302 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003303
Richard Smithe6c01442013-06-05 00:46:14 +00003304 // Per C++1y [expr.const]p2:
3305 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3306 // - a [...] glvalue of integral or enumeration type that refers to
3307 // a non-volatile const object [...]
3308 // [...]
3309 // - a [...] glvalue of literal type that refers to a non-volatile
3310 // object whose lifetime began within the evaluation of e.
3311 //
3312 // C++11 misses the 'began within the evaluation of e' check and
3313 // instead allows all temporaries, including things like:
3314 // int &&r = 1;
3315 // int x = ++r;
3316 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003317 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003318 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3319 const ValueDecl *ED = MTE->getExtendingDecl();
3320 if (!(BaseType.isConstQualified() &&
3321 BaseType->isIntegralOrEnumerationType()) &&
3322 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003323 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003324 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Faisal Valie690b7a2016-07-02 22:34:24 +00003325 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003326 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3327 return CompleteObject();
3328 }
3329
3330 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3331 assert(BaseVal && "got reference to unevaluated temporary");
3332 } else {
Richard Smith7bd54ab2019-05-15 20:22:21 +00003333 if (!IsAccess)
Richard Smithdebad642019-05-12 09:39:08 +00003334 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smithee0ce3022019-05-17 07:06:46 +00003335 APValue Val;
3336 LVal.moveInto(Val);
3337 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3338 << AK
3339 << Val.getAsString(Info.Ctx,
3340 Info.Ctx.getLValueReferenceType(LValType));
3341 NoteLValueLocation(Info, LVal.Base);
Richard Smithe6c01442013-06-05 00:46:14 +00003342 return CompleteObject();
3343 }
3344 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003345 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003346 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003347 }
Richard Smith7525ff62013-05-09 07:14:00 +00003348 }
3349
Richard Smith9defb7d2018-02-21 03:38:30 +00003350 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003351 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003352 //
3353 // FIXME: Not all local state is mutable. Allow local constant subobjects
3354 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003355 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3356 Info.EvalStatus.HasSideEffects) ||
Richard Smithdebad642019-05-12 09:39:08 +00003357 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
Richard Smith3229b742013-05-05 21:17:10 +00003358 return CompleteObject();
3359
Richard Smithdebad642019-05-12 09:39:08 +00003360 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003361}
3362
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003363/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003364/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3365/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003366///
3367/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003368/// \param Conv - The expression for which we are performing the conversion.
3369/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003370/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3371/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003372/// \param LVal - The glvalue on which we are attempting to perform this action.
3373/// \param RVal - The produced value will be placed here.
Richard Smithc667cdc2019-09-18 17:37:44 +00003374/// \param WantObjectRepresentation - If true, we're looking for the object
3375/// representation rather than the value, and in particular,
3376/// there is no requirement that the result be fully initialized.
3377static bool
3378handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3379 const LValue &LVal, APValue &RVal,
3380 bool WantObjectRepresentation = false) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003381 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003382 return false;
3383
Richard Smith3229b742013-05-05 21:17:10 +00003384 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003385 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Eric Fiselier708afb52019-05-16 21:04:15 +00003386
Richard Smithc667cdc2019-09-18 17:37:44 +00003387 AccessKinds AK =
3388 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3389
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003390 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003391 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3392 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3393 // initializer until now for such expressions. Such an expression can't be
3394 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003395 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003396 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003397 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003398 }
Richard Smith3229b742013-05-05 21:17:10 +00003399 APValue Lit;
3400 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3401 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003402 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
Richard Smithc667cdc2019-09-18 17:37:44 +00003403 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
Alexey Bataevec474782014-10-09 08:45:04 +00003404 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00003405 // Special-case character extraction so we don't have to construct an
3406 // APValue for the whole string.
Eli Friedman041adb02019-02-09 02:22:17 +00003407 assert(LVal.Designator.Entries.size() <= 1 &&
Eli Friedman3bf72d72019-02-08 21:18:46 +00003408 "Can only read characters from string literals");
Eli Friedman041adb02019-02-09 02:22:17 +00003409 if (LVal.Designator.Entries.empty()) {
3410 // Fail for now for LValue to RValue conversion of an array.
3411 // (This shouldn't show up in C/C++, but it could be triggered by a
3412 // weird EvaluateAsRValue call from a tool.)
3413 Info.FFDiag(Conv);
3414 return false;
3415 }
Eli Friedman3bf72d72019-02-08 21:18:46 +00003416 if (LVal.Designator.isOnePastTheEnd()) {
3417 if (Info.getLangOpts().CPlusPlus11)
Richard Smithc667cdc2019-09-18 17:37:44 +00003418 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
Eli Friedman3bf72d72019-02-08 21:18:46 +00003419 else
3420 Info.FFDiag(Conv);
3421 return false;
3422 }
Richard Smith5b5e27a2019-05-10 20:05:31 +00003423 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
Eli Friedman3bf72d72019-02-08 21:18:46 +00003424 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3425 return true;
Richard Smith96e0c102011-11-04 02:25:55 +00003426 }
Richard Smith11562c52011-10-28 17:51:58 +00003427 }
3428
Richard Smithc667cdc2019-09-18 17:37:44 +00003429 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
3430 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
Richard Smith3da88fa2013-04-26 14:36:30 +00003431}
3432
3433/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003434static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003435 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003436 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003437 return false;
3438
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003439 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003440 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003441 return false;
3442 }
3443
Richard Smith3229b742013-05-05 21:17:10 +00003444 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003445 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3446}
3447
3448namespace {
3449struct CompoundAssignSubobjectHandler {
3450 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003451 const Expr *E;
3452 QualType PromotedLHSType;
3453 BinaryOperatorKind Opcode;
3454 const APValue &RHS;
3455
3456 static const AccessKinds AccessKind = AK_Assign;
3457
3458 typedef bool result_type;
3459
3460 bool checkConst(QualType QT) {
3461 // Assigning to a const object has undefined behavior.
3462 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003463 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003464 return false;
3465 }
3466 return true;
3467 }
3468
3469 bool failed() { return false; }
3470 bool found(APValue &Subobj, QualType SubobjType) {
3471 switch (Subobj.getKind()) {
3472 case APValue::Int:
3473 return found(Subobj.getInt(), SubobjType);
3474 case APValue::Float:
3475 return found(Subobj.getFloat(), SubobjType);
3476 case APValue::ComplexInt:
3477 case APValue::ComplexFloat:
3478 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003479 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003480 return false;
3481 case APValue::LValue:
3482 return foundPointer(Subobj, SubobjType);
3483 default:
3484 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003485 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003486 return false;
3487 }
3488 }
3489 bool found(APSInt &Value, QualType SubobjType) {
3490 if (!checkConst(SubobjType))
3491 return false;
3492
Tan S. B.9f935e82018-12-18 07:38:06 +00003493 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003494 // We don't support compound assignment on integer-cast-to-pointer
3495 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003496 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003497 return false;
3498 }
3499
Tan S. B.9f935e82018-12-18 07:38:06 +00003500 if (RHS.isInt()) {
3501 APSInt LHS =
3502 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3503 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3504 return false;
3505 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3506 return true;
3507 } else if (RHS.isFloat()) {
3508 APFloat FValue(0.0);
3509 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3510 FValue) &&
3511 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3512 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3513 Value);
3514 }
3515
3516 Info.FFDiag(E);
3517 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003518 }
3519 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003520 return checkConst(SubobjType) &&
3521 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3522 Value) &&
3523 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3524 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003525 }
3526 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3527 if (!checkConst(SubobjType))
3528 return false;
3529
3530 QualType PointeeType;
3531 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3532 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003533
3534 if (PointeeType.isNull() || !RHS.isInt() ||
3535 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003536 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003537 return false;
3538 }
3539
Richard Smithd6cc1982017-01-31 02:23:02 +00003540 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003541 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003542 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003543
3544 LValue LVal;
3545 LVal.setFrom(Info.Ctx, Subobj);
3546 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3547 return false;
3548 LVal.moveInto(Subobj);
3549 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003550 }
Richard Smith43e77732013-05-07 04:50:00 +00003551};
3552} // end anonymous namespace
3553
3554const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3555
3556/// Perform a compound assignment of LVal <op>= RVal.
3557static bool handleCompoundAssignment(
3558 EvalInfo &Info, const Expr *E,
3559 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3560 BinaryOperatorKind Opcode, const APValue &RVal) {
3561 if (LVal.Designator.Invalid)
3562 return false;
3563
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003564 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003565 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003566 return false;
3567 }
3568
3569 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3570 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3571 RVal };
3572 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3573}
3574
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003575namespace {
3576struct IncDecSubobjectHandler {
3577 EvalInfo &Info;
3578 const UnaryOperator *E;
3579 AccessKinds AccessKind;
3580 APValue *Old;
3581
Richard Smith243ef902013-05-05 23:31:59 +00003582 typedef bool result_type;
3583
3584 bool checkConst(QualType QT) {
3585 // Assigning to a const object has undefined behavior.
3586 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003587 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003588 return false;
3589 }
3590 return true;
3591 }
3592
3593 bool failed() { return false; }
3594 bool found(APValue &Subobj, QualType SubobjType) {
3595 // Stash the old value. Also clear Old, so we don't clobber it later
3596 // if we're post-incrementing a complex.
3597 if (Old) {
3598 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003599 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003600 }
3601
3602 switch (Subobj.getKind()) {
3603 case APValue::Int:
3604 return found(Subobj.getInt(), SubobjType);
3605 case APValue::Float:
3606 return found(Subobj.getFloat(), SubobjType);
3607 case APValue::ComplexInt:
3608 return found(Subobj.getComplexIntReal(),
3609 SubobjType->castAs<ComplexType>()->getElementType()
3610 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3611 case APValue::ComplexFloat:
3612 return found(Subobj.getComplexFloatReal(),
3613 SubobjType->castAs<ComplexType>()->getElementType()
3614 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3615 case APValue::LValue:
3616 return foundPointer(Subobj, SubobjType);
3617 default:
3618 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003619 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003620 return false;
3621 }
3622 }
3623 bool found(APSInt &Value, QualType SubobjType) {
3624 if (!checkConst(SubobjType))
3625 return false;
3626
3627 if (!SubobjType->isIntegerType()) {
3628 // We don't support increment / decrement on integer-cast-to-pointer
3629 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003630 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003631 return false;
3632 }
3633
3634 if (Old) *Old = APValue(Value);
3635
3636 // bool arithmetic promotes to int, and the conversion back to bool
3637 // doesn't reduce mod 2^n, so special-case it.
3638 if (SubobjType->isBooleanType()) {
3639 if (AccessKind == AK_Increment)
3640 Value = 1;
3641 else
3642 Value = !Value;
3643 return true;
3644 }
3645
3646 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003647 if (AccessKind == AK_Increment) {
3648 ++Value;
3649
3650 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3651 APSInt ActualValue(Value, /*IsUnsigned*/true);
3652 return HandleOverflow(Info, E, ActualValue, SubobjType);
3653 }
3654 } else {
3655 --Value;
3656
3657 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3658 unsigned BitWidth = Value.getBitWidth();
3659 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3660 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003661 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003662 }
3663 }
3664 return true;
3665 }
3666 bool found(APFloat &Value, QualType SubobjType) {
3667 if (!checkConst(SubobjType))
3668 return false;
3669
3670 if (Old) *Old = APValue(Value);
3671
3672 APFloat One(Value.getSemantics(), 1);
3673 if (AccessKind == AK_Increment)
3674 Value.add(One, APFloat::rmNearestTiesToEven);
3675 else
3676 Value.subtract(One, APFloat::rmNearestTiesToEven);
3677 return true;
3678 }
3679 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3680 if (!checkConst(SubobjType))
3681 return false;
3682
3683 QualType PointeeType;
3684 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3685 PointeeType = PT->getPointeeType();
3686 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003687 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003688 return false;
3689 }
3690
3691 LValue LVal;
3692 LVal.setFrom(Info.Ctx, Subobj);
3693 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3694 AccessKind == AK_Increment ? 1 : -1))
3695 return false;
3696 LVal.moveInto(Subobj);
3697 return true;
3698 }
Richard Smith243ef902013-05-05 23:31:59 +00003699};
3700} // end anonymous namespace
3701
3702/// Perform an increment or decrement on LVal.
3703static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3704 QualType LValType, bool IsIncrement, APValue *Old) {
3705 if (LVal.Designator.Invalid)
3706 return false;
3707
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003708 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003709 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003710 return false;
3711 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003712
3713 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3714 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3715 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3716 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3717}
3718
Richard Smithe97cbd72011-11-11 04:05:33 +00003719/// Build an lvalue for the object argument of a member function call.
3720static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3721 LValue &This) {
3722 if (Object->getType()->isPointerType())
3723 return EvaluatePointer(Object, This, Info);
3724
3725 if (Object->isGLValue())
3726 return EvaluateLValue(Object, This, Info);
3727
Richard Smithd9f663b2013-04-22 15:31:51 +00003728 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003729 return EvaluateTemporary(Object, This, Info);
3730
Faisal Valie690b7a2016-07-02 22:34:24 +00003731 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003732 return false;
3733}
3734
3735/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3736/// lvalue referring to the result.
3737///
3738/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003739/// \param LV - An lvalue referring to the base of the member pointer.
3740/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003741/// \param IncludeMember - Specifies whether the member itself is included in
3742/// the resulting LValue subobject designator. This is not possible when
3743/// creating a bound member function.
3744/// \return The field or method declaration to which the member pointer refers,
3745/// or 0 if evaluation fails.
3746static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003747 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003748 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003749 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003750 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003751 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003752 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003753 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003754
3755 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3756 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003757 if (!MemPtr.getDecl()) {
3758 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003759 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003760 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003761 }
Richard Smith253c2a32012-01-27 01:14:48 +00003762
Richard Smith027bf112011-11-17 22:56:20 +00003763 if (MemPtr.isDerivedMember()) {
3764 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003765 // The end of the derived-to-base path for the base object must match the
3766 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003767 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003768 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003769 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003770 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003771 }
Richard Smith027bf112011-11-17 22:56:20 +00003772 unsigned PathLengthToMember =
3773 LV.Designator.Entries.size() - MemPtr.Path.size();
3774 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3775 const CXXRecordDecl *LVDecl = getAsBaseClass(
3776 LV.Designator.Entries[PathLengthToMember + I]);
3777 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003778 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003779 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003780 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003781 }
Richard Smith027bf112011-11-17 22:56:20 +00003782 }
3783
3784 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003785 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003786 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003787 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003788 } else if (!MemPtr.Path.empty()) {
3789 // Extend the LValue path with the member pointer's path.
3790 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3791 MemPtr.Path.size() + IncludeMember);
3792
3793 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003794 if (const PointerType *PT = LVType->getAs<PointerType>())
3795 LVType = PT->getPointeeType();
3796 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3797 assert(RD && "member pointer access on non-class-type expression");
3798 // The first class in the path is that of the lvalue.
3799 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3800 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003801 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003802 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003803 RD = Base;
3804 }
3805 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003806 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3807 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003808 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003809 }
3810
3811 // Add the member. Note that we cannot build bound member functions here.
3812 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003813 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003814 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003815 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003816 } else if (const IndirectFieldDecl *IFD =
3817 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003818 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003819 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003820 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003821 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003822 }
Richard Smith027bf112011-11-17 22:56:20 +00003823 }
3824
3825 return MemPtr.getDecl();
3826}
3827
Richard Smith84401042013-06-03 05:03:02 +00003828static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3829 const BinaryOperator *BO,
3830 LValue &LV,
3831 bool IncludeMember = true) {
3832 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3833
3834 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003835 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003836 MemberPtr MemPtr;
3837 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3838 }
Craig Topper36250ad2014-05-12 05:36:57 +00003839 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003840 }
3841
3842 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3843 BO->getRHS(), IncludeMember);
3844}
3845
Richard Smith027bf112011-11-17 22:56:20 +00003846/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3847/// the provided lvalue, which currently refers to the base object.
3848static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3849 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003850 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003851 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003852 return false;
3853
Richard Smitha8105bc2012-01-06 16:39:00 +00003854 QualType TargetQT = E->getType();
3855 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3856 TargetQT = PT->getPointeeType();
3857
3858 // Check this cast lands within the final derived-to-base subobject path.
3859 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003860 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003861 << D.MostDerivedType << TargetQT;
3862 return false;
3863 }
3864
Richard Smith027bf112011-11-17 22:56:20 +00003865 // Check the type of the final cast. We don't need to check the path,
3866 // since a cast can only be formed if the path is unique.
3867 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003868 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3869 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003870 if (NewEntriesSize == D.MostDerivedPathLength)
3871 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3872 else
Richard Smith027bf112011-11-17 22:56:20 +00003873 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003874 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003875 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003876 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003877 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003878 }
Richard Smith027bf112011-11-17 22:56:20 +00003879
3880 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003881 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003882}
3883
Richard Smithc667cdc2019-09-18 17:37:44 +00003884/// Get the value to use for a default-initialized object of type T.
3885static APValue getDefaultInitValue(QualType T) {
3886 if (auto *RD = T->getAsCXXRecordDecl()) {
3887 if (RD->isUnion())
3888 return APValue((const FieldDecl*)nullptr);
3889
3890 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
3891 std::distance(RD->field_begin(), RD->field_end()));
3892
3893 unsigned Index = 0;
3894 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
3895 End = RD->bases_end(); I != End; ++I, ++Index)
3896 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
3897
3898 for (const auto *I : RD->fields()) {
3899 if (I->isUnnamedBitfield())
3900 continue;
3901 Struct.getStructField(I->getFieldIndex()) =
3902 getDefaultInitValue(I->getType());
3903 }
3904 return Struct;
3905 }
3906
3907 if (auto *AT =
3908 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
3909 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
3910 if (Array.hasArrayFiller())
3911 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
3912 return Array;
3913 }
3914
3915 return APValue::IndeterminateValue();
3916}
3917
Mike Stump876387b2009-10-27 22:09:17 +00003918namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003919enum EvalStmtResult {
3920 /// Evaluation failed.
3921 ESR_Failed,
3922 /// Hit a 'return' statement.
3923 ESR_Returned,
3924 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003925 ESR_Succeeded,
3926 /// Hit a 'continue' statement.
3927 ESR_Continue,
3928 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003929 ESR_Break,
3930 /// Still scanning for 'case' or 'default' statement.
3931 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003932};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003933}
Richard Smith254a73d2011-10-28 22:34:42 +00003934
Richard Smith97fcf4b2016-08-14 23:15:52 +00003935static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3936 // We don't need to evaluate the initializer for a static local.
3937 if (!VD->hasLocalStorage())
3938 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003939
Richard Smith97fcf4b2016-08-14 23:15:52 +00003940 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003941 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00003942
Richard Smith97fcf4b2016-08-14 23:15:52 +00003943 const Expr *InitE = VD->getInit();
3944 if (!InitE) {
Richard Smithc667cdc2019-09-18 17:37:44 +00003945 Val = getDefaultInitValue(VD->getType());
3946 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00003947 }
Richard Smith51f03172013-06-20 03:00:05 +00003948
Richard Smith97fcf4b2016-08-14 23:15:52 +00003949 if (InitE->isValueDependent())
3950 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003951
Richard Smith97fcf4b2016-08-14 23:15:52 +00003952 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3953 // Wipe out any partially-computed value, to allow tracking that this
3954 // evaluation failed.
3955 Val = APValue();
3956 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003957 }
3958
3959 return true;
3960}
3961
Richard Smith97fcf4b2016-08-14 23:15:52 +00003962static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3963 bool OK = true;
3964
3965 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3966 OK &= EvaluateVarDecl(Info, VD);
3967
3968 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3969 for (auto *BD : DD->bindings())
3970 if (auto *VD = BD->getHoldingVar())
3971 OK &= EvaluateDecl(Info, VD);
3972
3973 return OK;
3974}
3975
3976
Richard Smith4e18ca52013-05-06 05:56:11 +00003977/// Evaluate a condition (either a variable declaration or an expression).
3978static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3979 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003980 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003981 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3982 return false;
3983 return EvaluateAsBooleanCondition(Cond, Result, Info);
3984}
3985
Richard Smith89210072016-04-04 23:29:43 +00003986namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003987/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00003988/// statement should be stored.
3989struct StmtResult {
3990 /// The APValue that should be filled in with the returned value.
3991 APValue &Value;
3992 /// The location containing the result, if any (used to support RVO).
3993 const LValue *Slot;
3994};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003995
3996struct TempVersionRAII {
3997 CallStackFrame &Frame;
3998
3999 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4000 Frame.pushTempVersion();
4001 }
4002
4003 ~TempVersionRAII() {
4004 Frame.popTempVersion();
4005 }
4006};
4007
Richard Smith89210072016-04-04 23:29:43 +00004008}
Richard Smith52a980a2015-08-28 02:43:42 +00004009
4010static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00004011 const Stmt *S,
4012 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00004013
4014/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00004015static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004016 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00004017 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004018 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00004019 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00004020 case ESR_Break:
4021 return ESR_Succeeded;
4022 case ESR_Succeeded:
4023 case ESR_Continue:
4024 return ESR_Continue;
4025 case ESR_Failed:
4026 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00004027 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00004028 return ESR;
4029 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00004030 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00004031}
4032
Richard Smith496ddcf2013-05-12 17:32:42 +00004033/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004034static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004035 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004036 BlockScopeRAII Scope(Info);
4037
Richard Smith496ddcf2013-05-12 17:32:42 +00004038 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00004039 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004040 {
4041 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004042 if (const Stmt *Init = SS->getInit()) {
4043 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4044 if (ESR != ESR_Succeeded)
4045 return ESR;
4046 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004047 if (SS->getConditionVariable() &&
4048 !EvaluateDecl(Info, SS->getConditionVariable()))
4049 return ESR_Failed;
4050 if (!EvaluateInteger(SS->getCond(), Value, Info))
4051 return ESR_Failed;
4052 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004053
4054 // Find the switch case corresponding to the value of the condition.
4055 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00004056 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004057 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4058 SC = SC->getNextSwitchCase()) {
4059 if (isa<DefaultStmt>(SC)) {
4060 Found = SC;
4061 continue;
4062 }
4063
4064 const CaseStmt *CS = cast<CaseStmt>(SC);
4065 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4066 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4067 : LHS;
4068 if (LHS <= Value && Value <= RHS) {
4069 Found = SC;
4070 break;
4071 }
4072 }
4073
4074 if (!Found)
4075 return ESR_Succeeded;
4076
4077 // Search the switch body for the switch case and evaluate it from there.
4078 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4079 case ESR_Break:
4080 return ESR_Succeeded;
4081 case ESR_Succeeded:
4082 case ESR_Continue:
4083 case ESR_Failed:
4084 case ESR_Returned:
4085 return ESR;
4086 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004087 // This can only happen if the switch case is nested within a statement
4088 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004089 Info.FFDiag(Found->getBeginLoc(),
4090 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004091 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004092 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004093 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004094}
4095
Richard Smith254a73d2011-10-28 22:34:42 +00004096// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004097static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004098 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004099 if (!Info.nextStep(S))
4100 return ESR_Failed;
4101
Richard Smith496ddcf2013-05-12 17:32:42 +00004102 // If we're hunting down a 'case' or 'default' label, recurse through
4103 // substatements until we hit the label.
4104 if (Case) {
4105 // FIXME: We don't start the lifetime of objects whose initialization we
4106 // jump over. However, such objects must be of class type with a trivial
4107 // default constructor that initialize all subobjects, so must be empty,
4108 // so this almost never matters.
4109 switch (S->getStmtClass()) {
4110 case Stmt::CompoundStmtClass:
4111 // FIXME: Precompute which substatement of a compound statement we
4112 // would jump to, and go straight there rather than performing a
4113 // linear scan each time.
4114 case Stmt::LabelStmtClass:
4115 case Stmt::AttributedStmtClass:
4116 case Stmt::DoStmtClass:
4117 break;
4118
4119 case Stmt::CaseStmtClass:
4120 case Stmt::DefaultStmtClass:
4121 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004122 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004123 break;
4124
4125 case Stmt::IfStmtClass: {
4126 // FIXME: Precompute which side of an 'if' we would jump to, and go
4127 // straight there rather than scanning both sides.
4128 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004129
4130 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4131 // preceded by our switch label.
4132 BlockScopeRAII Scope(Info);
4133
Richard Smith397a6862019-09-20 23:08:59 +00004134 // Step into the init statement in case it brings an (uninitialized)
4135 // variable into scope.
4136 if (const Stmt *Init = IS->getInit()) {
4137 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4138 if (ESR != ESR_CaseNotFound) {
4139 assert(ESR != ESR_Succeeded);
4140 return ESR;
4141 }
4142 }
4143
4144 // Condition variable must be initialized if it exists.
4145 // FIXME: We can skip evaluating the body if there's a condition
4146 // variable, as there can't be any case labels within it.
4147 // (The same is true for 'for' statements.)
4148
Richard Smith496ddcf2013-05-12 17:32:42 +00004149 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4150 if (ESR != ESR_CaseNotFound || !IS->getElse())
4151 return ESR;
4152 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4153 }
4154
4155 case Stmt::WhileStmtClass: {
4156 EvalStmtResult ESR =
4157 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4158 if (ESR != ESR_Continue)
4159 return ESR;
4160 break;
4161 }
4162
4163 case Stmt::ForStmtClass: {
4164 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith397a6862019-09-20 23:08:59 +00004165 BlockScopeRAII Scope(Info);
4166
4167 // Step into the init statement in case it brings an (uninitialized)
4168 // variable into scope.
4169 if (const Stmt *Init = FS->getInit()) {
4170 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4171 if (ESR != ESR_CaseNotFound) {
4172 assert(ESR != ESR_Succeeded);
4173 return ESR;
4174 }
4175 }
4176
Richard Smith496ddcf2013-05-12 17:32:42 +00004177 EvalStmtResult ESR =
4178 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4179 if (ESR != ESR_Continue)
4180 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004181 if (FS->getInc()) {
4182 FullExpressionRAII IncScope(Info);
4183 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4184 return ESR_Failed;
4185 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004186 break;
4187 }
4188
Richard Smithc667cdc2019-09-18 17:37:44 +00004189 case Stmt::DeclStmtClass: {
4190 // Start the lifetime of any uninitialized variables we encounter. They
4191 // might be used by the selected branch of the switch.
4192 const DeclStmt *DS = cast<DeclStmt>(S);
4193 for (const auto *D : DS->decls()) {
4194 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4195 if (VD->hasLocalStorage() && !VD->getInit())
4196 if (!EvaluateVarDecl(Info, VD))
4197 return ESR_Failed;
4198 // FIXME: If the variable has initialization that can't be jumped
4199 // over, bail out of any immediately-surrounding compound-statement
4200 // too. There can't be any case labels here.
4201 }
4202 }
4203 return ESR_CaseNotFound;
4204 }
4205
Richard Smith496ddcf2013-05-12 17:32:42 +00004206 default:
4207 return ESR_CaseNotFound;
4208 }
4209 }
4210
Richard Smith254a73d2011-10-28 22:34:42 +00004211 switch (S->getStmtClass()) {
4212 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004213 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004214 // Don't bother evaluating beyond an expression-statement which couldn't
4215 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004216 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004217 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004218 return ESR_Failed;
4219 return ESR_Succeeded;
4220 }
4221
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004222 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004223 return ESR_Failed;
4224
4225 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004226 return ESR_Succeeded;
4227
Richard Smithd9f663b2013-04-22 15:31:51 +00004228 case Stmt::DeclStmtClass: {
4229 const DeclStmt *DS = cast<DeclStmt>(S);
Richard Smithc667cdc2019-09-18 17:37:44 +00004230 for (const auto *D : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004231 // Each declaration initialization is its own full-expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004232 FullExpressionRAII Scope(Info);
Richard Smithc667cdc2019-09-18 17:37:44 +00004233 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004234 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004235 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004236 return ESR_Succeeded;
4237 }
4238
Richard Smith357362d2011-12-13 06:39:58 +00004239 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004240 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004241 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004242 if (RetExpr &&
4243 !(Result.Slot
4244 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4245 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004246 return ESR_Failed;
4247 return ESR_Returned;
4248 }
Richard Smith254a73d2011-10-28 22:34:42 +00004249
4250 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004251 BlockScopeRAII Scope(Info);
4252
Richard Smith254a73d2011-10-28 22:34:42 +00004253 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004254 for (const auto *BI : CS->body()) {
4255 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004256 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004257 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004258 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004259 return ESR;
4260 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004261 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004262 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004263
4264 case Stmt::IfStmtClass: {
4265 const IfStmt *IS = cast<IfStmt>(S);
4266
4267 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004268 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004269 if (const Stmt *Init = IS->getInit()) {
4270 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4271 if (ESR != ESR_Succeeded)
4272 return ESR;
4273 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004274 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004275 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004276 return ESR_Failed;
4277
4278 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4279 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4280 if (ESR != ESR_Succeeded)
4281 return ESR;
4282 }
4283 return ESR_Succeeded;
4284 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004285
4286 case Stmt::WhileStmtClass: {
4287 const WhileStmt *WS = cast<WhileStmt>(S);
4288 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004289 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004290 bool Continue;
4291 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4292 Continue))
4293 return ESR_Failed;
4294 if (!Continue)
4295 break;
4296
4297 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4298 if (ESR != ESR_Continue)
4299 return ESR;
4300 }
4301 return ESR_Succeeded;
4302 }
4303
4304 case Stmt::DoStmtClass: {
4305 const DoStmt *DS = cast<DoStmt>(S);
4306 bool Continue;
4307 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004308 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004309 if (ESR != ESR_Continue)
4310 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004311 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004312
Richard Smith08d6a2c2013-07-24 07:11:57 +00004313 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004314 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4315 return ESR_Failed;
4316 } while (Continue);
4317 return ESR_Succeeded;
4318 }
4319
4320 case Stmt::ForStmtClass: {
4321 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004322 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004323 if (FS->getInit()) {
4324 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4325 if (ESR != ESR_Succeeded)
4326 return ESR;
4327 }
4328 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004329 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004330 bool Continue = true;
4331 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4332 FS->getCond(), Continue))
4333 return ESR_Failed;
4334 if (!Continue)
4335 break;
4336
4337 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4338 if (ESR != ESR_Continue)
4339 return ESR;
4340
Richard Smith08d6a2c2013-07-24 07:11:57 +00004341 if (FS->getInc()) {
4342 FullExpressionRAII IncScope(Info);
4343 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4344 return ESR_Failed;
4345 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004346 }
4347 return ESR_Succeeded;
4348 }
4349
Richard Smith896e0d72013-05-06 06:51:17 +00004350 case Stmt::CXXForRangeStmtClass: {
4351 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004352 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004353
Richard Smith8baa5002018-09-28 18:44:09 +00004354 // Evaluate the init-statement if present.
4355 if (FS->getInit()) {
4356 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4357 if (ESR != ESR_Succeeded)
4358 return ESR;
4359 }
4360
Richard Smith896e0d72013-05-06 06:51:17 +00004361 // Initialize the __range variable.
4362 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4363 if (ESR != ESR_Succeeded)
4364 return ESR;
4365
4366 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004367 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4368 if (ESR != ESR_Succeeded)
4369 return ESR;
4370 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004371 if (ESR != ESR_Succeeded)
4372 return ESR;
4373
4374 while (true) {
4375 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004376 {
4377 bool Continue = true;
4378 FullExpressionRAII CondExpr(Info);
4379 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4380 return ESR_Failed;
4381 if (!Continue)
4382 break;
4383 }
Richard Smith896e0d72013-05-06 06:51:17 +00004384
4385 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004386 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004387 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4388 if (ESR != ESR_Succeeded)
4389 return ESR;
4390
4391 // Loop body.
4392 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4393 if (ESR != ESR_Continue)
4394 return ESR;
4395
4396 // Increment: ++__begin
4397 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4398 return ESR_Failed;
4399 }
4400
4401 return ESR_Succeeded;
4402 }
4403
Richard Smith496ddcf2013-05-12 17:32:42 +00004404 case Stmt::SwitchStmtClass:
4405 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4406
Richard Smith4e18ca52013-05-06 05:56:11 +00004407 case Stmt::ContinueStmtClass:
4408 return ESR_Continue;
4409
4410 case Stmt::BreakStmtClass:
4411 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004412
4413 case Stmt::LabelStmtClass:
4414 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4415
4416 case Stmt::AttributedStmtClass:
4417 // As a general principle, C++11 attributes can be ignored without
4418 // any semantic impact.
4419 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4420 Case);
4421
4422 case Stmt::CaseStmtClass:
4423 case Stmt::DefaultStmtClass:
4424 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004425 case Stmt::CXXTryStmtClass:
4426 // Evaluate try blocks by evaluating all sub statements.
4427 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004428 }
4429}
4430
Richard Smithcc36f692011-12-22 02:22:31 +00004431/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4432/// default constructor. If so, we'll fold it whether or not it's marked as
4433/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4434/// so we need special handling.
4435static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004436 const CXXConstructorDecl *CD,
4437 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004438 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4439 return false;
4440
Richard Smith66e05fe2012-01-18 05:21:49 +00004441 // Value-initialization does not call a trivial default constructor, so such a
4442 // call is a core constant expression whether or not the constructor is
4443 // constexpr.
4444 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004445 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004446 // FIXME: If DiagDecl is an implicitly-declared special member function,
4447 // we should be much more explicit about why it's not constexpr.
4448 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4449 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4450 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004451 } else {
4452 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4453 }
4454 }
4455 return true;
4456}
4457
Richard Smith357362d2011-12-13 06:39:58 +00004458/// CheckConstexprFunction - Check that a function can be called in a constant
4459/// expression.
4460static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4461 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004462 const FunctionDecl *Definition,
4463 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004464 // Potential constant expressions can contain calls to declared, but not yet
4465 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004466 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004467 Declaration->isConstexpr())
4468 return false;
4469
James Y Knightc7d3e602018-10-05 17:49:48 +00004470 // Bail out if the function declaration itself is invalid. We will
4471 // have produced a relevant diagnostic while parsing it, so just
4472 // note the problematic sub-expression.
4473 if (Declaration->isInvalidDecl()) {
4474 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004475 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004476 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004477
Richard Smithd9c6b032019-05-09 19:45:49 +00004478 // DR1872: An instantiated virtual constexpr function can't be called in a
Richard Smith921f1322019-05-13 23:35:21 +00004479 // constant expression (prior to C++20). We can still constant-fold such a
4480 // call.
4481 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4482 cast<CXXMethodDecl>(Declaration)->isVirtual())
4483 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4484
4485 if (Definition && Definition->isInvalidDecl()) {
4486 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd9c6b032019-05-09 19:45:49 +00004487 return false;
4488 }
4489
Richard Smith357362d2011-12-13 06:39:58 +00004490 // Can we evaluate this function call?
Richard Smith921f1322019-05-13 23:35:21 +00004491 if (Definition && Definition->isConstexpr() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004492 return true;
4493
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004494 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004495 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004496
Richard Smith5179eb72016-06-28 19:03:57 +00004497 // If this function is not constexpr because it is an inherited
4498 // non-constexpr constructor, diagnose that directly.
4499 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4500 if (CD && CD->isInheritingConstructor()) {
4501 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004502 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004503 DiagDecl = CD = Inherited;
4504 }
4505
4506 // FIXME: If DiagDecl is an implicitly-declared special member function
4507 // or an inheriting constructor, we should be much more explicit about why
4508 // it's not constexpr.
4509 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004510 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004511 << CD->getInheritedConstructor().getConstructor()->getParent();
4512 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004513 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004514 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004515 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4516 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004517 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004518 }
4519 return false;
4520}
4521
Richard Smithdebad642019-05-12 09:39:08 +00004522namespace {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004523struct CheckDynamicTypeHandler {
4524 AccessKinds AccessKind;
Richard Smithdebad642019-05-12 09:39:08 +00004525 typedef bool result_type;
4526 bool failed() { return false; }
4527 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4528 bool found(APSInt &Value, QualType SubobjType) { return true; }
4529 bool found(APFloat &Value, QualType SubobjType) { return true; }
4530};
4531} // end anonymous namespace
4532
Richard Smith7bd54ab2019-05-15 20:22:21 +00004533/// Check that we can access the notional vptr of an object / determine its
4534/// dynamic type.
4535static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4536 AccessKinds AK, bool Polymorphic) {
Richard Smithdab287b2019-05-13 07:51:29 +00004537 if (This.Designator.Invalid)
4538 return false;
4539
Richard Smith7bd54ab2019-05-15 20:22:21 +00004540 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
Richard Smithdebad642019-05-12 09:39:08 +00004541
4542 if (!Obj)
4543 return false;
4544
4545 if (!Obj.Value) {
4546 // The object is not usable in constant expressions, so we can't inspect
4547 // its value to see if it's in-lifetime or what the active union members
4548 // are. We can still check for a one-past-the-end lvalue.
4549 if (This.Designator.isOnePastTheEnd() ||
4550 This.Designator.isMostDerivedAnUnsizedArray()) {
4551 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4552 ? diag::note_constexpr_access_past_end
4553 : diag::note_constexpr_access_unsized_array)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004554 << AK;
Richard Smithdebad642019-05-12 09:39:08 +00004555 return false;
Richard Smith7bd54ab2019-05-15 20:22:21 +00004556 } else if (Polymorphic) {
4557 // Conservatively refuse to perform a polymorphic operation if we would
Richard Smith921f1322019-05-13 23:35:21 +00004558 // not be able to read a notional 'vptr' value.
4559 APValue Val;
4560 This.moveInto(Val);
4561 QualType StarThisType =
4562 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
Richard Smith7bd54ab2019-05-15 20:22:21 +00004563 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4564 << AK << Val.getAsString(Info.Ctx, StarThisType);
Richard Smith921f1322019-05-13 23:35:21 +00004565 return false;
Richard Smithdebad642019-05-12 09:39:08 +00004566 }
4567 return true;
4568 }
4569
Richard Smith7bd54ab2019-05-15 20:22:21 +00004570 CheckDynamicTypeHandler Handler{AK};
Richard Smithdebad642019-05-12 09:39:08 +00004571 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4572}
4573
Richard Smith7bd54ab2019-05-15 20:22:21 +00004574/// Check that the pointee of the 'this' pointer in a member function call is
4575/// either within its lifetime or in its period of construction or destruction.
4576static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4577 const LValue &This) {
4578 return checkDynamicType(Info, E, This, AK_MemberCall, false);
4579}
4580
Richard Smith921f1322019-05-13 23:35:21 +00004581struct DynamicType {
4582 /// The dynamic class type of the object.
4583 const CXXRecordDecl *Type;
4584 /// The corresponding path length in the lvalue.
4585 unsigned PathLength;
4586};
4587
4588static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4589 unsigned PathLength) {
4590 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4591 Designator.Entries.size() && "invalid path length");
4592 return (PathLength == Designator.MostDerivedPathLength)
4593 ? Designator.MostDerivedType->getAsCXXRecordDecl()
4594 : getAsBaseClass(Designator.Entries[PathLength - 1]);
4595}
4596
4597/// Determine the dynamic type of an object.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004598static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4599 LValue &This, AccessKinds AK) {
Richard Smith921f1322019-05-13 23:35:21 +00004600 // If we don't have an lvalue denoting an object of class type, there is no
4601 // meaningful dynamic type. (We consider objects of non-class type to have no
4602 // dynamic type.)
Richard Smith7bd54ab2019-05-15 20:22:21 +00004603 if (!checkDynamicType(Info, E, This, AK, true))
Richard Smith921f1322019-05-13 23:35:21 +00004604 return None;
4605
Richard Smith7bd54ab2019-05-15 20:22:21 +00004606 // Refuse to compute a dynamic type in the presence of virtual bases. This
4607 // shouldn't happen other than in constant-folding situations, since literal
4608 // types can't have virtual bases.
4609 //
4610 // Note that consumers of DynamicType assume that the type has no virtual
4611 // bases, and will need modifications if this restriction is relaxed.
4612 const CXXRecordDecl *Class =
4613 This.Designator.MostDerivedType->getAsCXXRecordDecl();
4614 if (!Class || Class->getNumVBases()) {
4615 Info.FFDiag(E);
4616 return None;
4617 }
4618
Richard Smith921f1322019-05-13 23:35:21 +00004619 // FIXME: For very deep class hierarchies, it might be beneficial to use a
4620 // binary search here instead. But the overwhelmingly common case is that
4621 // we're not in the middle of a constructor, so it probably doesn't matter
4622 // in practice.
4623 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4624 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4625 PathLength <= Path.size(); ++PathLength) {
4626 switch (Info.isEvaluatingConstructor(This.getLValueBase(),
4627 Path.slice(0, PathLength))) {
4628 case ConstructionPhase::Bases:
4629 // We're constructing a base class. This is not the dynamic type.
4630 break;
4631
4632 case ConstructionPhase::None:
4633 case ConstructionPhase::AfterBases:
4634 // We've finished constructing the base classes, so this is the dynamic
4635 // type.
4636 return DynamicType{getBaseClassType(This.Designator, PathLength),
4637 PathLength};
4638 }
4639 }
4640
4641 // CWG issue 1517: we're constructing a base class of the object described by
4642 // 'This', so that object has not yet begun its period of construction and
4643 // any polymorphic operation on it results in undefined behavior.
Richard Smith7bd54ab2019-05-15 20:22:21 +00004644 Info.FFDiag(E);
Richard Smith921f1322019-05-13 23:35:21 +00004645 return None;
4646}
4647
4648/// Perform virtual dispatch.
4649static const CXXMethodDecl *HandleVirtualDispatch(
4650 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4651 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00004652 Optional<DynamicType> DynType =
4653 ComputeDynamicType(Info, E, This, AK_MemberCall);
4654 if (!DynType)
Richard Smith921f1322019-05-13 23:35:21 +00004655 return nullptr;
Richard Smith921f1322019-05-13 23:35:21 +00004656
4657 // Find the final overrider. It must be declared in one of the classes on the
4658 // path from the dynamic type to the static type.
4659 // FIXME: If we ever allow literal types to have virtual base classes, that
4660 // won't be true.
4661 const CXXMethodDecl *Callee = Found;
4662 unsigned PathLength = DynType->PathLength;
4663 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4664 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
Richard Smith921f1322019-05-13 23:35:21 +00004665 const CXXMethodDecl *Overrider =
4666 Found->getCorrespondingMethodDeclaredInClass(Class, false);
4667 if (Overrider) {
4668 Callee = Overrider;
4669 break;
4670 }
4671 }
4672
4673 // C++2a [class.abstract]p6:
4674 // the effect of making a virtual call to a pure virtual function [...] is
4675 // undefined
4676 if (Callee->isPure()) {
4677 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4678 Info.Note(Callee->getLocation(), diag::note_declared_at);
4679 return nullptr;
4680 }
4681
4682 // If necessary, walk the rest of the path to determine the sequence of
4683 // covariant adjustment steps to apply.
4684 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4685 Found->getReturnType())) {
4686 CovariantAdjustmentPath.push_back(Callee->getReturnType());
4687 for (unsigned CovariantPathLength = PathLength + 1;
4688 CovariantPathLength != This.Designator.Entries.size();
4689 ++CovariantPathLength) {
4690 const CXXRecordDecl *NextClass =
4691 getBaseClassType(This.Designator, CovariantPathLength);
4692 const CXXMethodDecl *Next =
4693 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4694 if (Next && !Info.Ctx.hasSameUnqualifiedType(
4695 Next->getReturnType(), CovariantAdjustmentPath.back()))
4696 CovariantAdjustmentPath.push_back(Next->getReturnType());
4697 }
4698 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4699 CovariantAdjustmentPath.back()))
4700 CovariantAdjustmentPath.push_back(Found->getReturnType());
4701 }
4702
4703 // Perform 'this' adjustment.
4704 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4705 return nullptr;
4706
4707 return Callee;
4708}
4709
4710/// Perform the adjustment from a value returned by a virtual function to
4711/// a value of the statically expected type, which may be a pointer or
4712/// reference to a base class of the returned type.
4713static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4714 APValue &Result,
4715 ArrayRef<QualType> Path) {
4716 assert(Result.isLValue() &&
4717 "unexpected kind of APValue for covariant return");
4718 if (Result.isNullPointer())
4719 return true;
4720
4721 LValue LVal;
4722 LVal.setFrom(Info.Ctx, Result);
4723
4724 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4725 for (unsigned I = 1; I != Path.size(); ++I) {
4726 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4727 assert(OldClass && NewClass && "unexpected kind of covariant return");
4728 if (OldClass != NewClass &&
4729 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4730 return false;
4731 OldClass = NewClass;
4732 }
4733
4734 LVal.moveInto(Result);
4735 return true;
4736}
4737
Richard Smith7bd54ab2019-05-15 20:22:21 +00004738/// Determine whether \p Base, which is known to be a direct base class of
4739/// \p Derived, is a public base class.
4740static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4741 const CXXRecordDecl *Base) {
4742 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4743 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4744 if (BaseClass && declaresSameEntity(BaseClass, Base))
4745 return BaseSpec.getAccessSpecifier() == AS_public;
4746 }
4747 llvm_unreachable("Base is not a direct base of Derived");
4748}
4749
4750/// Apply the given dynamic cast operation on the provided lvalue.
4751///
4752/// This implements the hard case of dynamic_cast, requiring a "runtime check"
4753/// to find a suitable target subobject.
4754static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4755 LValue &Ptr) {
4756 // We can't do anything with a non-symbolic pointer value.
4757 SubobjectDesignator &D = Ptr.Designator;
4758 if (D.Invalid)
4759 return false;
4760
4761 // C++ [expr.dynamic.cast]p6:
4762 // If v is a null pointer value, the result is a null pointer value.
4763 if (Ptr.isNullPointer() && !E->isGLValue())
4764 return true;
4765
4766 // For all the other cases, we need the pointer to point to an object within
4767 // its lifetime / period of construction / destruction, and we need to know
4768 // its dynamic type.
4769 Optional<DynamicType> DynType =
4770 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4771 if (!DynType)
4772 return false;
4773
4774 // C++ [expr.dynamic.cast]p7:
4775 // If T is "pointer to cv void", then the result is a pointer to the most
4776 // derived object
4777 if (E->getType()->isVoidPointerType())
4778 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4779
4780 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
4781 assert(C && "dynamic_cast target is not void pointer nor class");
4782 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4783
4784 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4785 // C++ [expr.dynamic.cast]p9:
4786 if (!E->isGLValue()) {
4787 // The value of a failed cast to pointer type is the null pointer value
4788 // of the required result type.
4789 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4790 Ptr.setNull(E->getType(), TargetVal);
4791 return true;
4792 }
4793
4794 // A failed cast to reference type throws [...] std::bad_cast.
4795 unsigned DiagKind;
4796 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4797 DynType->Type->isDerivedFrom(C)))
4798 DiagKind = 0;
4799 else if (!Paths || Paths->begin() == Paths->end())
4800 DiagKind = 1;
4801 else if (Paths->isAmbiguous(CQT))
4802 DiagKind = 2;
4803 else {
4804 assert(Paths->front().Access != AS_public && "why did the cast fail?");
4805 DiagKind = 3;
4806 }
4807 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4808 << DiagKind << Ptr.Designator.getType(Info.Ctx)
4809 << Info.Ctx.getRecordType(DynType->Type)
4810 << E->getType().getUnqualifiedType();
4811 return false;
4812 };
4813
4814 // Runtime check, phase 1:
4815 // Walk from the base subobject towards the derived object looking for the
4816 // target type.
4817 for (int PathLength = Ptr.Designator.Entries.size();
4818 PathLength >= (int)DynType->PathLength; --PathLength) {
4819 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4820 if (declaresSameEntity(Class, C))
4821 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4822 // We can only walk across public inheritance edges.
4823 if (PathLength > (int)DynType->PathLength &&
4824 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4825 Class))
4826 return RuntimeCheckFailed(nullptr);
4827 }
4828
4829 // Runtime check, phase 2:
4830 // Search the dynamic type for an unambiguous public base of type C.
4831 CXXBasePaths Paths(/*FindAmbiguities=*/true,
4832 /*RecordPaths=*/true, /*DetectVirtual=*/false);
4833 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4834 Paths.front().Access == AS_public) {
4835 // Downcast to the dynamic type...
4836 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4837 return false;
4838 // ... then upcast to the chosen base class subobject.
4839 for (CXXBasePathElement &Elem : Paths.front())
4840 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4841 return false;
4842 return true;
4843 }
4844
4845 // Otherwise, the runtime check fails.
4846 return RuntimeCheckFailed(&Paths);
4847}
4848
Richard Smith31c69a32019-05-21 23:15:20 +00004849namespace {
4850struct StartLifetimeOfUnionMemberHandler {
4851 const FieldDecl *Field;
4852
4853 static const AccessKinds AccessKind = AK_Assign;
4854
Richard Smith31c69a32019-05-21 23:15:20 +00004855 typedef bool result_type;
4856 bool failed() { return false; }
4857 bool found(APValue &Subobj, QualType SubobjType) {
4858 // We are supposed to perform no initialization but begin the lifetime of
4859 // the object. We interpret that as meaning to do what default
4860 // initialization of the object would do if all constructors involved were
4861 // trivial:
4862 // * All base, non-variant member, and array element subobjects' lifetimes
4863 // begin
4864 // * No variant members' lifetimes begin
4865 // * All scalar subobjects whose lifetimes begin have indeterminate values
4866 assert(SubobjType->isUnionType());
4867 if (!declaresSameEntity(Subobj.getUnionField(), Field))
4868 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
4869 return true;
4870 }
4871 bool found(APSInt &Value, QualType SubobjType) {
4872 llvm_unreachable("wrong value kind for union object");
4873 }
4874 bool found(APFloat &Value, QualType SubobjType) {
4875 llvm_unreachable("wrong value kind for union object");
4876 }
4877};
4878} // end anonymous namespace
4879
4880const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
4881
4882/// Handle a builtin simple-assignment or a call to a trivial assignment
4883/// operator whose left-hand side might involve a union member access. If it
4884/// does, implicitly start the lifetime of any accessed union elements per
4885/// C++20 [class.union]5.
4886static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
4887 const LValue &LHS) {
4888 if (LHS.InvalidBase || LHS.Designator.Invalid)
4889 return false;
4890
4891 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
4892 // C++ [class.union]p5:
4893 // define the set S(E) of subexpressions of E as follows:
Richard Smith31c69a32019-05-21 23:15:20 +00004894 unsigned PathLength = LHS.Designator.Entries.size();
Eric Fiselierffafdb92019-05-23 23:34:43 +00004895 for (const Expr *E = LHSExpr; E != nullptr;) {
Richard Smith31c69a32019-05-21 23:15:20 +00004896 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
4897 if (auto *ME = dyn_cast<MemberExpr>(E)) {
4898 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
4899 if (!FD)
4900 break;
4901
4902 // ... and also contains A.B if B names a union member
4903 if (FD->getParent()->isUnion())
4904 UnionPathLengths.push_back({PathLength - 1, FD});
4905
4906 E = ME->getBase();
4907 --PathLength;
4908 assert(declaresSameEntity(FD,
4909 LHS.Designator.Entries[PathLength]
4910 .getAsBaseOrMember().getPointer()));
4911
4912 // -- If E is of the form A[B] and is interpreted as a built-in array
4913 // subscripting operator, S(E) is [S(the array operand, if any)].
4914 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
4915 // Step over an ArrayToPointerDecay implicit cast.
4916 auto *Base = ASE->getBase()->IgnoreImplicit();
4917 if (!Base->getType()->isArrayType())
4918 break;
4919
4920 E = Base;
4921 --PathLength;
4922
4923 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4924 // Step over a derived-to-base conversion.
Eric Fiselierffafdb92019-05-23 23:34:43 +00004925 E = ICE->getSubExpr();
Richard Smith31c69a32019-05-21 23:15:20 +00004926 if (ICE->getCastKind() == CK_NoOp)
4927 continue;
4928 if (ICE->getCastKind() != CK_DerivedToBase &&
4929 ICE->getCastKind() != CK_UncheckedDerivedToBase)
4930 break;
Richard Smitha481b012019-05-30 20:45:12 +00004931 // Walk path backwards as we walk up from the base to the derived class.
4932 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
Richard Smith31c69a32019-05-21 23:15:20 +00004933 --PathLength;
Dmitri Gribenkoa10fe832019-05-22 06:57:23 +00004934 (void)Elt;
Richard Smith31c69a32019-05-21 23:15:20 +00004935 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
4936 LHS.Designator.Entries[PathLength]
4937 .getAsBaseOrMember().getPointer()));
4938 }
Richard Smith31c69a32019-05-21 23:15:20 +00004939
4940 // -- Otherwise, S(E) is empty.
4941 } else {
4942 break;
4943 }
4944 }
4945
4946 // Common case: no unions' lifetimes are started.
4947 if (UnionPathLengths.empty())
4948 return true;
4949
4950 // if modification of X [would access an inactive union member], an object
4951 // of the type of X is implicitly created
4952 CompleteObject Obj =
4953 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
4954 if (!Obj)
4955 return false;
4956 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
4957 llvm::reverse(UnionPathLengths)) {
4958 // Form a designator for the union object.
4959 SubobjectDesignator D = LHS.Designator;
4960 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
4961
4962 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
4963 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
4964 return false;
4965 }
4966
4967 return true;
4968}
4969
Richard Smithbe6dd812014-11-19 21:27:17 +00004970/// Determine if a class has any fields that might need to be copied by a
4971/// trivial copy or move operation.
4972static bool hasFields(const CXXRecordDecl *RD) {
4973 if (!RD || RD->isEmpty())
4974 return false;
4975 for (auto *FD : RD->fields()) {
4976 if (FD->isUnnamedBitfield())
4977 continue;
4978 return true;
4979 }
4980 for (auto &Base : RD->bases())
4981 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4982 return true;
4983 return false;
4984}
4985
Richard Smithd62306a2011-11-10 06:34:14 +00004986namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004987typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004988}
4989
4990/// EvaluateArgs - Evaluate the arguments to a function call.
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00004991static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
4992 EvalInfo &Info, const FunctionDecl *Callee) {
Richard Smith253c2a32012-01-27 01:14:48 +00004993 bool Success = true;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00004994 llvm::SmallBitVector ForbiddenNullArgs;
4995 if (Callee->hasAttr<NonNullAttr>()) {
4996 ForbiddenNullArgs.resize(Args.size());
4997 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
4998 if (!Attr->args_size()) {
4999 ForbiddenNullArgs.set();
5000 break;
5001 } else
5002 for (auto Idx : Attr->args()) {
5003 unsigned ASTIdx = Idx.getASTIndex();
5004 if (ASTIdx >= Args.size())
5005 continue;
5006 ForbiddenNullArgs[ASTIdx] = 1;
5007 }
5008 }
5009 }
Richard Smithd62306a2011-11-10 06:34:14 +00005010 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00005011 I != E; ++I) {
5012 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5013 // If we're checking for a potential constant expression, evaluate all
5014 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005015 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005016 return false;
5017 Success = false;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005018 } else if (!ForbiddenNullArgs.empty() &&
5019 ForbiddenNullArgs[I - Args.begin()] &&
5020 ArgValues[I - Args.begin()].isNullPointer()) {
5021 Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
5022 if (!Info.noteFailure())
5023 return false;
5024 Success = false;
Richard Smith253c2a32012-01-27 01:14:48 +00005025 }
5026 }
5027 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005028}
5029
Richard Smith254a73d2011-10-28 22:34:42 +00005030/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00005031static bool HandleFunctionCall(SourceLocation CallLoc,
5032 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005033 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00005034 EvalInfo &Info, APValue &Result,
5035 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00005036 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005037 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
Richard Smithd62306a2011-11-10 06:34:14 +00005038 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00005039
Richard Smith253c2a32012-01-27 01:14:48 +00005040 if (!Info.CheckCallLimit(CallLoc))
5041 return false;
5042
5043 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00005044
5045 // For a trivial copy or move assignment, perform an APValue copy. This is
5046 // essential for unions, where the operations performed by the assignment
5047 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00005048 //
5049 // Skip this for non-union classes with no fields; in that case, the defaulted
5050 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00005051 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00005052 if (MD && MD->isDefaulted() &&
5053 (MD->getParent()->isUnion() ||
5054 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00005055 assert(This &&
5056 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5057 LValue RHS;
5058 RHS.setFrom(Info.Ctx, ArgValues[0]);
5059 APValue RHSValue;
Richard Smithc667cdc2019-09-18 17:37:44 +00005060 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5061 RHSValue, MD->getParent()->isUnion()))
Richard Smith99005e62013-05-07 03:19:20 +00005062 return false;
Richard Smith31c69a32019-05-21 23:15:20 +00005063 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5064 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5065 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00005066 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00005067 RHSValue))
5068 return false;
5069 This->moveInto(Result);
5070 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00005071 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00005072 // We're in a lambda; determine the lambda capture field maps unless we're
5073 // just constexpr checking a lambda's call operator. constexpr checking is
5074 // done before the captures have been added to the closure object (unless
5075 // we're inferring constexpr-ness), so we don't have access to them in this
5076 // case. But since we don't need the captures to constexpr check, we can
5077 // just ignore them.
5078 if (!Info.checkingPotentialConstantExpression())
5079 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5080 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00005081 }
5082
Richard Smith52a980a2015-08-28 02:43:42 +00005083 StmtResult Ret = {Result, ResultSlot};
5084 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00005085 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00005086 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00005087 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005088 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00005089 }
Richard Smithd9f663b2013-04-22 15:31:51 +00005090 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00005091}
5092
Richard Smithd62306a2011-11-10 06:34:14 +00005093/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00005094static bool HandleConstructorCall(const Expr *E, const LValue &This,
5095 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00005096 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00005097 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00005098 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00005099 if (!Info.CheckCallLimit(CallLoc))
5100 return false;
5101
Richard Smith3607ffe2012-02-13 03:54:03 +00005102 const CXXRecordDecl *RD = Definition->getParent();
5103 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005104 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00005105 return false;
5106 }
5107
Erik Pilkington42925492017-10-04 00:18:55 +00005108 EvalInfo::EvaluatingConstructorRAII EvalObj(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005109 Info,
5110 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5111 RD->getNumBases());
Richard Smith5179eb72016-06-28 19:03:57 +00005112 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00005113
Richard Smith52a980a2015-08-28 02:43:42 +00005114 // FIXME: Creating an APValue just to hold a nonexistent return value is
5115 // wasteful.
5116 APValue RetVal;
5117 StmtResult Ret = {RetVal, nullptr};
5118
Richard Smith5179eb72016-06-28 19:03:57 +00005119 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00005120 if (Definition->isDelegatingConstructor()) {
5121 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00005122 {
5123 FullExpressionRAII InitScope(Info);
5124 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
5125 return false;
5126 }
Richard Smith52a980a2015-08-28 02:43:42 +00005127 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005128 }
5129
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005130 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00005131 // essential for unions (or classes with anonymous union members), where the
5132 // operations performed by the constructor cannot be represented by
5133 // ctor-initializers.
5134 //
5135 // Skip this for empty non-union classes; we should not perform an
5136 // lvalue-to-rvalue conversion on them because their copy constructor does not
5137 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00005138 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00005139 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00005140 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005141 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00005142 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00005143 return handleLValueToRValueConversion(
5144 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
Richard Smithc667cdc2019-09-18 17:37:44 +00005145 RHS, Result, Definition->getParent()->isUnion());
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005146 }
5147
5148 // Reserve space for the struct members.
Richard Smithe637cbe2019-05-21 23:15:18 +00005149 if (!RD->isUnion() && !Result.hasValue())
Richard Smithd62306a2011-11-10 06:34:14 +00005150 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00005151 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005152
John McCalld7bca762012-05-01 00:38:49 +00005153 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005154 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5155
Richard Smith08d6a2c2013-07-24 07:11:57 +00005156 // A scope for temporaries lifetime-extended by reference members.
5157 BlockScopeRAII LifetimeExtendedScope(Info);
5158
Richard Smith253c2a32012-01-27 01:14:48 +00005159 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00005160 unsigned BasesSeen = 0;
5161#ifndef NDEBUG
5162 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5163#endif
Richard Smithc667cdc2019-09-18 17:37:44 +00005164 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5165 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5166 // We might be initializing the same field again if this is an indirect
5167 // field initialization.
5168 if (FieldIt == RD->field_end() ||
5169 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5170 assert(Indirect && "fields out of order?");
5171 return;
5172 }
5173
5174 // Default-initialize any fields with no explicit initializer.
5175 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5176 assert(FieldIt != RD->field_end() && "missing field?");
5177 if (!FieldIt->isUnnamedBitfield())
5178 Result.getStructField(FieldIt->getFieldIndex()) =
5179 getDefaultInitValue(FieldIt->getType());
5180 }
5181 ++FieldIt;
5182 };
Aaron Ballman0ad78302014-03-13 17:34:31 +00005183 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00005184 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005185 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00005186 APValue *Value = &Result;
5187
5188 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00005189 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005190 if (I->isBaseInitializer()) {
5191 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00005192#ifndef NDEBUG
5193 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00005194 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00005195 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5196 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5197 "base class initializers not in expected order");
5198 ++BaseIt;
5199#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00005200 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00005201 BaseType->getAsCXXRecordDecl(), &Layout))
5202 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005203 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00005204 } else if ((FD = I->getMember())) {
5205 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005206 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005207 if (RD->isUnion()) {
5208 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00005209 Value = &Result.getUnionValue();
5210 } else {
Richard Smithc667cdc2019-09-18 17:37:44 +00005211 SkipToField(FD, false);
Richard Smith253c2a32012-01-27 01:14:48 +00005212 Value = &Result.getStructField(FD->getFieldIndex());
5213 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00005214 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005215 // Walk the indirect field decl's chain to find the object to initialize,
5216 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005217 auto IndirectFieldChain = IFD->chain();
5218 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00005219 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005220 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5221 // Switch the union field if it differs. This happens if we had
5222 // preceding zero-initialization, and we're now initializing a union
5223 // subobject other than the first.
5224 // FIXME: In this case, the values of the other subobjects are
5225 // specified, since zero-initialization sets all padding bits to zero.
Richard Smithe637cbe2019-05-21 23:15:18 +00005226 if (!Value->hasValue() ||
Richard Smith1b78b3d2012-01-25 22:15:11 +00005227 (Value->isUnion() && Value->getUnionField() != FD)) {
5228 if (CD->isUnion())
5229 *Value = APValue(FD);
5230 else
Richard Smithc667cdc2019-09-18 17:37:44 +00005231 // FIXME: This immediately starts the lifetime of all members of an
5232 // anonymous struct. It would be preferable to strictly start member
5233 // lifetime in initialization order.
5234 *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
Richard Smith1b78b3d2012-01-25 22:15:11 +00005235 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005236 // Store Subobject as its parent before updating it for the last element
5237 // in the chain.
5238 if (C == IndirectFieldChain.back())
5239 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00005240 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00005241 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005242 if (CD->isUnion())
5243 Value = &Value->getUnionValue();
Richard Smithc667cdc2019-09-18 17:37:44 +00005244 else {
5245 if (C == IndirectFieldChain.front() && !RD->isUnion())
5246 SkipToField(FD, true);
Richard Smith1b78b3d2012-01-25 22:15:11 +00005247 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithc667cdc2019-09-18 17:37:44 +00005248 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00005249 }
Richard Smithd62306a2011-11-10 06:34:14 +00005250 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00005251 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00005252 }
Richard Smith253c2a32012-01-27 01:14:48 +00005253
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005254 // Need to override This for implicit field initializers as in this case
5255 // This refers to innermost anonymous struct/union containing initializer,
5256 // not to currently constructed class.
5257 const Expr *Init = I->getInit();
5258 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5259 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00005260 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00005261 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5262 (FD && FD->isBitField() &&
5263 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005264 // If we're checking for a potential constant expression, evaluate all
5265 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00005266 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00005267 return false;
5268 Success = false;
5269 }
Richard Smith921f1322019-05-13 23:35:21 +00005270
5271 // This is the point at which the dynamic type of the object becomes this
5272 // class type.
5273 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5274 EvalObj.finishedConstructingBases();
Richard Smithd62306a2011-11-10 06:34:14 +00005275 }
5276
Richard Smithc667cdc2019-09-18 17:37:44 +00005277 // Default-initialize any remaining fields.
5278 if (!RD->isUnion()) {
5279 for (; FieldIt != RD->field_end(); ++FieldIt) {
5280 if (!FieldIt->isUnnamedBitfield())
5281 Result.getStructField(FieldIt->getFieldIndex()) =
5282 getDefaultInitValue(FieldIt->getType());
5283 }
5284 }
5285
Richard Smithd9f663b2013-04-22 15:31:51 +00005286 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00005287 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00005288}
5289
Richard Smith5179eb72016-06-28 19:03:57 +00005290static bool HandleConstructorCall(const Expr *E, const LValue &This,
5291 ArrayRef<const Expr*> Args,
5292 const CXXConstructorDecl *Definition,
5293 EvalInfo &Info, APValue &Result) {
5294 ArgVector ArgValues(Args.size());
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +00005295 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
Richard Smith5179eb72016-06-28 19:03:57 +00005296 return false;
5297
5298 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5299 Info, Result);
5300}
5301
Eli Friedman9a156e52008-11-12 09:44:48 +00005302//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00005303// Generic Evaluation
5304//===----------------------------------------------------------------------===//
5305namespace {
5306
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005307class BitCastBuffer {
5308 // FIXME: We're going to need bit-level granularity when we support
5309 // bit-fields.
5310 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
5311 // we don't support a host or target where that is the case. Still, we should
5312 // use a more generic type in case we ever do.
5313 SmallVector<Optional<unsigned char>, 32> Bytes;
5314
5315 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
5316 "Need at least 8 bit unsigned char");
5317
5318 bool TargetIsLittleEndian;
5319
5320public:
5321 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
5322 : Bytes(Width.getQuantity()),
5323 TargetIsLittleEndian(TargetIsLittleEndian) {}
5324
5325 LLVM_NODISCARD
5326 bool readObject(CharUnits Offset, CharUnits Width,
5327 SmallVectorImpl<unsigned char> &Output) const {
5328 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
5329 // If a byte of an integer is uninitialized, then the whole integer is
5330 // uninitalized.
5331 if (!Bytes[I.getQuantity()])
5332 return false;
5333 Output.push_back(*Bytes[I.getQuantity()]);
5334 }
5335 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5336 std::reverse(Output.begin(), Output.end());
5337 return true;
5338 }
5339
5340 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
5341 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5342 std::reverse(Input.begin(), Input.end());
5343
5344 size_t Index = 0;
5345 for (unsigned char Byte : Input) {
5346 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
5347 Bytes[Offset.getQuantity() + Index] = Byte;
5348 ++Index;
5349 }
5350 }
5351
5352 size_t size() { return Bytes.size(); }
5353};
5354
5355/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
5356/// target would represent the value at runtime.
5357class APValueToBufferConverter {
5358 EvalInfo &Info;
5359 BitCastBuffer Buffer;
5360 const CastExpr *BCE;
5361
5362 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
5363 const CastExpr *BCE)
5364 : Info(Info),
5365 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
5366 BCE(BCE) {}
5367
5368 bool visit(const APValue &Val, QualType Ty) {
5369 return visit(Val, Ty, CharUnits::fromQuantity(0));
5370 }
5371
5372 // Write out Val with type Ty into Buffer starting at Offset.
5373 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
5374 assert((size_t)Offset.getQuantity() <= Buffer.size());
5375
5376 // As a special case, nullptr_t has an indeterminate value.
5377 if (Ty->isNullPtrType())
5378 return true;
5379
5380 // Dig through Src to find the byte at SrcOffset.
5381 switch (Val.getKind()) {
5382 case APValue::Indeterminate:
5383 case APValue::None:
5384 return true;
5385
5386 case APValue::Int:
5387 return visitInt(Val.getInt(), Ty, Offset);
5388 case APValue::Float:
5389 return visitFloat(Val.getFloat(), Ty, Offset);
5390 case APValue::Array:
5391 return visitArray(Val, Ty, Offset);
5392 case APValue::Struct:
5393 return visitRecord(Val, Ty, Offset);
5394
5395 case APValue::ComplexInt:
5396 case APValue::ComplexFloat:
5397 case APValue::Vector:
5398 case APValue::FixedPoint:
5399 // FIXME: We should support these.
5400
5401 case APValue::Union:
5402 case APValue::MemberPointer:
5403 case APValue::AddrLabelDiff: {
5404 Info.FFDiag(BCE->getBeginLoc(),
5405 diag::note_constexpr_bit_cast_unsupported_type)
5406 << Ty;
5407 return false;
5408 }
5409
5410 case APValue::LValue:
5411 llvm_unreachable("LValue subobject in bit_cast?");
5412 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00005413 llvm_unreachable("Unhandled APValue::ValueKind");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005414 }
5415
5416 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
5417 const RecordDecl *RD = Ty->getAsRecordDecl();
5418 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5419
5420 // Visit the base classes.
5421 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5422 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5423 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5424 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5425
5426 if (!visitRecord(Val.getStructBase(I), BS.getType(),
5427 Layout.getBaseClassOffset(BaseDecl) + Offset))
5428 return false;
5429 }
5430 }
5431
5432 // Visit the fields.
5433 unsigned FieldIdx = 0;
5434 for (FieldDecl *FD : RD->fields()) {
5435 if (FD->isBitField()) {
5436 Info.FFDiag(BCE->getBeginLoc(),
5437 diag::note_constexpr_bit_cast_unsupported_bitfield);
5438 return false;
5439 }
5440
5441 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5442
5443 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
5444 "only bit-fields can have sub-char alignment");
5445 CharUnits FieldOffset =
5446 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
5447 QualType FieldTy = FD->getType();
5448 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
5449 return false;
5450 ++FieldIdx;
5451 }
5452
5453 return true;
5454 }
5455
5456 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
5457 const auto *CAT =
5458 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
5459 if (!CAT)
5460 return false;
5461
5462 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
5463 unsigned NumInitializedElts = Val.getArrayInitializedElts();
5464 unsigned ArraySize = Val.getArraySize();
5465 // First, initialize the initialized elements.
5466 for (unsigned I = 0; I != NumInitializedElts; ++I) {
5467 const APValue &SubObj = Val.getArrayInitializedElt(I);
5468 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
5469 return false;
5470 }
5471
5472 // Next, initialize the rest of the array using the filler.
5473 if (Val.hasArrayFiller()) {
5474 const APValue &Filler = Val.getArrayFiller();
5475 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
5476 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
5477 return false;
5478 }
5479 }
5480
5481 return true;
5482 }
5483
5484 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
5485 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
5486 SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
5487 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
5488 Buffer.writeObject(Offset, Bytes);
5489 return true;
5490 }
5491
5492 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
5493 APSInt AsInt(Val.bitcastToAPInt());
5494 return visitInt(AsInt, Ty, Offset);
5495 }
5496
5497public:
5498 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
5499 const CastExpr *BCE) {
5500 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
5501 APValueToBufferConverter Converter(Info, DstSize, BCE);
5502 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
5503 return None;
5504 return Converter.Buffer;
5505 }
5506};
5507
5508/// Write an BitCastBuffer into an APValue.
5509class BufferToAPValueConverter {
5510 EvalInfo &Info;
5511 const BitCastBuffer &Buffer;
5512 const CastExpr *BCE;
5513
5514 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
5515 const CastExpr *BCE)
5516 : Info(Info), Buffer(Buffer), BCE(BCE) {}
5517
5518 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
5519 // with an invalid type, so anything left is a deficiency on our part (FIXME).
5520 // Ideally this will be unreachable.
5521 llvm::NoneType unsupportedType(QualType Ty) {
5522 Info.FFDiag(BCE->getBeginLoc(),
5523 diag::note_constexpr_bit_cast_unsupported_type)
5524 << Ty;
5525 return None;
5526 }
5527
5528 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
5529 const EnumType *EnumSugar = nullptr) {
5530 if (T->isNullPtrType()) {
5531 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
5532 return APValue((Expr *)nullptr,
5533 /*Offset=*/CharUnits::fromQuantity(NullValue),
5534 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
5535 }
5536
5537 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
5538 SmallVector<uint8_t, 8> Bytes;
5539 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
5540 // If this is std::byte or unsigned char, then its okay to store an
5541 // indeterminate value.
5542 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
5543 bool IsUChar =
5544 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
5545 T->isSpecificBuiltinType(BuiltinType::Char_U));
5546 if (!IsStdByte && !IsUChar) {
Simon Pilgrimbc7f30e82019-07-03 12:20:28 +00005547 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005548 Info.FFDiag(BCE->getExprLoc(),
5549 diag::note_constexpr_bit_cast_indet_dest)
5550 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
5551 return None;
5552 }
5553
5554 return APValue::IndeterminateValue();
5555 }
5556
5557 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
5558 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
5559
5560 if (T->isIntegralOrEnumerationType()) {
5561 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
5562 return APValue(Val);
5563 }
5564
5565 if (T->isRealFloatingType()) {
5566 const llvm::fltSemantics &Semantics =
5567 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
5568 return APValue(APFloat(Semantics, Val));
5569 }
5570
5571 return unsupportedType(QualType(T, 0));
5572 }
5573
5574 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
5575 const RecordDecl *RD = RTy->getAsRecordDecl();
5576 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5577
5578 unsigned NumBases = 0;
5579 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
5580 NumBases = CXXRD->getNumBases();
5581
5582 APValue ResultVal(APValue::UninitStruct(), NumBases,
5583 std::distance(RD->field_begin(), RD->field_end()));
5584
5585 // Visit the base classes.
5586 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5587 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5588 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5589 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5590 if (BaseDecl->isEmpty() ||
5591 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
5592 continue;
5593
5594 Optional<APValue> SubObj = visitType(
5595 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
5596 if (!SubObj)
5597 return None;
5598 ResultVal.getStructBase(I) = *SubObj;
5599 }
5600 }
5601
5602 // Visit the fields.
5603 unsigned FieldIdx = 0;
5604 for (FieldDecl *FD : RD->fields()) {
5605 // FIXME: We don't currently support bit-fields. A lot of the logic for
5606 // this is in CodeGen, so we need to factor it around.
5607 if (FD->isBitField()) {
5608 Info.FFDiag(BCE->getBeginLoc(),
5609 diag::note_constexpr_bit_cast_unsupported_bitfield);
5610 return None;
5611 }
5612
5613 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5614 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
5615
5616 CharUnits FieldOffset =
5617 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
5618 Offset;
5619 QualType FieldTy = FD->getType();
5620 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
5621 if (!SubObj)
5622 return None;
5623 ResultVal.getStructField(FieldIdx) = *SubObj;
5624 ++FieldIdx;
5625 }
5626
5627 return ResultVal;
5628 }
5629
5630 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
5631 QualType RepresentationType = Ty->getDecl()->getIntegerType();
5632 assert(!RepresentationType.isNull() &&
5633 "enum forward decl should be caught by Sema");
5634 const BuiltinType *AsBuiltin =
5635 RepresentationType.getCanonicalType()->getAs<BuiltinType>();
5636 assert(AsBuiltin && "non-integral enum underlying type?");
5637 // Recurse into the underlying type. Treat std::byte transparently as
5638 // unsigned char.
5639 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
5640 }
5641
5642 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
5643 size_t Size = Ty->getSize().getLimitedValue();
5644 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
5645
5646 APValue ArrayValue(APValue::UninitArray(), Size, Size);
5647 for (size_t I = 0; I != Size; ++I) {
5648 Optional<APValue> ElementValue =
5649 visitType(Ty->getElementType(), Offset + I * ElementWidth);
5650 if (!ElementValue)
5651 return None;
5652 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
5653 }
5654
5655 return ArrayValue;
5656 }
5657
5658 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
5659 return unsupportedType(QualType(Ty, 0));
5660 }
5661
5662 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
5663 QualType Can = Ty.getCanonicalType();
5664
5665 switch (Can->getTypeClass()) {
5666#define TYPE(Class, Base) \
5667 case Type::Class: \
5668 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
5669#define ABSTRACT_TYPE(Class, Base)
5670#define NON_CANONICAL_TYPE(Class, Base) \
5671 case Type::Class: \
5672 llvm_unreachable("non-canonical type should be impossible!");
5673#define DEPENDENT_TYPE(Class, Base) \
5674 case Type::Class: \
5675 llvm_unreachable( \
5676 "dependent types aren't supported in the constant evaluator!");
5677#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
5678 case Type::Class: \
5679 llvm_unreachable("either dependent or not canonical!");
5680#include "clang/AST/TypeNodes.def"
5681 }
Simon Pilgrim71600be2019-07-03 09:54:25 +00005682 llvm_unreachable("Unhandled Type::TypeClass");
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005683 }
5684
5685public:
5686 // Pull out a full value of type DstType.
5687 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
5688 const CastExpr *BCE) {
5689 BufferToAPValueConverter Converter(Info, Buffer, BCE);
5690 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
5691 }
5692};
5693
5694static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
5695 QualType Ty, EvalInfo *Info,
5696 const ASTContext &Ctx,
5697 bool CheckingDest) {
5698 Ty = Ty.getCanonicalType();
5699
5700 auto diag = [&](int Reason) {
5701 if (Info)
5702 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
5703 << CheckingDest << (Reason == 4) << Reason;
5704 return false;
5705 };
5706 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
5707 if (Info)
5708 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
5709 << NoteTy << Construct << Ty;
5710 return false;
5711 };
5712
5713 if (Ty->isUnionType())
5714 return diag(0);
5715 if (Ty->isPointerType())
5716 return diag(1);
5717 if (Ty->isMemberPointerType())
5718 return diag(2);
5719 if (Ty.isVolatileQualified())
5720 return diag(3);
5721
5722 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
5723 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
5724 for (CXXBaseSpecifier &BS : CXXRD->bases())
5725 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
5726 CheckingDest))
5727 return note(1, BS.getType(), BS.getBeginLoc());
5728 }
5729 for (FieldDecl *FD : Record->fields()) {
5730 if (FD->getType()->isReferenceType())
5731 return diag(4);
5732 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
5733 CheckingDest))
5734 return note(0, FD->getType(), FD->getBeginLoc());
5735 }
5736 }
5737
5738 if (Ty->isArrayType() &&
5739 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
5740 Info, Ctx, CheckingDest))
5741 return false;
5742
5743 return true;
5744}
5745
5746static bool checkBitCastConstexprEligibility(EvalInfo *Info,
5747 const ASTContext &Ctx,
5748 const CastExpr *BCE) {
5749 bool DestOK = checkBitCastConstexprEligibilityType(
5750 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
5751 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
5752 BCE->getBeginLoc(),
5753 BCE->getSubExpr()->getType(), Info, Ctx, false);
5754 return SourceOK;
5755}
5756
5757static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
5758 APValue &SourceValue,
5759 const CastExpr *BCE) {
5760 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
5761 "no host or target supports non 8-bit chars");
5762 assert(SourceValue.isLValue() &&
5763 "LValueToRValueBitcast requires an lvalue operand!");
5764
5765 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
5766 return false;
5767
5768 LValue SourceLValue;
5769 APValue SourceRValue;
5770 SourceLValue.setFrom(Info.Ctx, SourceValue);
Richard Smithc667cdc2019-09-18 17:37:44 +00005771 if (!handleLValueToRValueConversion(
5772 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
5773 SourceRValue, /*WantObjectRepresentation=*/true))
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005774 return false;
5775
5776 // Read out SourceValue into a char buffer.
5777 Optional<BitCastBuffer> Buffer =
5778 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
5779 if (!Buffer)
5780 return false;
5781
5782 // Write out the buffer into a new APValue.
5783 Optional<APValue> MaybeDestValue =
5784 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
5785 if (!MaybeDestValue)
5786 return false;
5787
5788 DestValue = std::move(*MaybeDestValue);
5789 return true;
5790}
5791
Aaron Ballman68af21c2014-01-03 19:26:43 +00005792template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00005793class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005794 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00005795private:
Richard Smith52a980a2015-08-28 02:43:42 +00005796 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005797 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005798 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005799 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005800 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005801 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005802 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005803
Richard Smith17100ba2012-02-16 02:46:34 +00005804 // Check whether a conditional operator with a non-constant condition is a
5805 // potential constant expression. If neither arm is a potential constant
5806 // expression, then the conditional operator is not either.
5807 template<typename ConditionalOperator>
5808 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005809 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00005810
5811 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00005812 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00005813 {
Richard Smith17100ba2012-02-16 02:46:34 +00005814 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00005815 StmtVisitorTy::Visit(E->getFalseExpr());
5816 if (Diag.empty())
5817 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00005818 }
Richard Smith17100ba2012-02-16 02:46:34 +00005819
George Burgess IV8c892b52016-05-25 22:31:54 +00005820 {
5821 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00005822 Diag.clear();
5823 StmtVisitorTy::Visit(E->getTrueExpr());
5824 if (Diag.empty())
5825 return;
5826 }
5827
5828 Error(E, diag::note_constexpr_conditional_never_const);
5829 }
5830
5831
5832 template<typename ConditionalOperator>
5833 bool HandleConditionalOperator(const ConditionalOperator *E) {
5834 bool BoolResult;
5835 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00005836 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00005837 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00005838 return false;
5839 }
5840 if (Info.noteFailure()) {
5841 StmtVisitorTy::Visit(E->getTrueExpr());
5842 StmtVisitorTy::Visit(E->getFalseExpr());
5843 }
Richard Smith17100ba2012-02-16 02:46:34 +00005844 return false;
5845 }
5846
5847 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
5848 return StmtVisitorTy::Visit(EvalExpr);
5849 }
5850
Peter Collingbournee9200682011-05-13 03:29:01 +00005851protected:
5852 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005853 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00005854 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
5855
Richard Smith92b1ce02011-12-12 09:28:41 +00005856 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005857 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005858 }
5859
Aaron Ballman68af21c2014-01-03 19:26:43 +00005860 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005861
5862public:
5863 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
5864
5865 EvalInfo &getEvalInfo() { return Info; }
5866
Richard Smithf57d8cb2011-12-09 22:58:01 +00005867 /// Report an evaluation error. This should only be called when an error is
5868 /// first discovered. When propagating an error, just return false.
5869 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005870 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005871 return false;
5872 }
5873 bool Error(const Expr *E) {
5874 return Error(E, diag::note_invalid_subexpr_in_const_expr);
5875 }
5876
Aaron Ballman68af21c2014-01-03 19:26:43 +00005877 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00005878 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00005879 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005880 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005881 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005882 }
5883
Bill Wendling8003edc2018-11-09 00:41:36 +00005884 bool VisitConstantExpr(const ConstantExpr *E)
5885 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005886 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005887 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005888 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005889 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005890 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005891 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005892 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00005893 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005894 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00005895 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005896 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00005897 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005898 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
5899 TempVersionRAII RAII(*Info.CurrentCall);
Eric Fiselier708afb52019-05-16 21:04:15 +00005900 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005901 return StmtVisitorTy::Visit(E->getExpr());
5902 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005903 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005904 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00005905 // The initializer may not have been parsed yet, or might be erroneous.
5906 if (!E->getExpr())
5907 return Error(E);
Eric Fiselier708afb52019-05-16 21:04:15 +00005908 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
Richard Smith17e32462013-09-13 20:51:45 +00005909 return StmtVisitorTy::Visit(E->getExpr());
5910 }
Eric Fiselier708afb52019-05-16 21:04:15 +00005911
Richard Smith5894a912011-12-19 22:12:41 +00005912 // We cannot create any objects for which cleanups are required, so there is
5913 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00005914 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00005915 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005916
Aaron Ballman68af21c2014-01-03 19:26:43 +00005917 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005918 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
5919 return static_cast<Derived*>(this)->VisitCastExpr(E);
5920 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005921 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith7bd54ab2019-05-15 20:22:21 +00005922 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
5923 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005924 return static_cast<Derived*>(this)->VisitCastExpr(E);
5925 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00005926 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
5927 return static_cast<Derived*>(this)->VisitCastExpr(E);
5928 }
Richard Smith6d6ecc32011-12-12 12:46:16 +00005929
Aaron Ballman68af21c2014-01-03 19:26:43 +00005930 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005931 switch (E->getOpcode()) {
5932 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005933 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005934
5935 case BO_Comma:
5936 VisitIgnoredValue(E->getLHS());
5937 return StmtVisitorTy::Visit(E->getRHS());
5938
5939 case BO_PtrMemD:
5940 case BO_PtrMemI: {
5941 LValue Obj;
5942 if (!HandleMemberPointerAccess(Info, E, Obj))
5943 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005944 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00005945 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005946 return false;
5947 return DerivedSuccess(Result, E);
5948 }
5949 }
5950 }
5951
Aaron Ballman68af21c2014-01-03 19:26:43 +00005952 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00005953 // Evaluate and cache the common expression. We treat it as a temporary,
5954 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00005955 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00005956 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005957 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00005958
Richard Smith17100ba2012-02-16 02:46:34 +00005959 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005960 }
5961
Aaron Ballman68af21c2014-01-03 19:26:43 +00005962 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005963 bool IsBcpCall = false;
5964 // If the condition (ignoring parens) is a __builtin_constant_p call,
5965 // the result is a constant expression if it can be folded without
5966 // side-effects. This is an important GNU extension. See GCC PR38377
5967 // for discussion.
5968 if (const CallExpr *CallCE =
5969 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00005970 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00005971 IsBcpCall = true;
5972
5973 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
5974 // constant expression; we can't check whether it's potentially foldable.
Richard Smith045b2272019-09-10 21:24:09 +00005975 // FIXME: We should instead treat __builtin_constant_p as non-constant if
5976 // it would return 'false' in this mode.
Richard Smith6d4c6582013-11-05 22:18:15 +00005977 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00005978 return false;
5979
Richard Smith6d4c6582013-11-05 22:18:15 +00005980 FoldConstant Fold(Info, IsBcpCall);
5981 if (!HandleConditionalOperator(E)) {
5982 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00005983 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00005984 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00005985
5986 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00005987 }
5988
Aaron Ballman68af21c2014-01-03 19:26:43 +00005989 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005990 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00005991 return DerivedSuccess(*Value, E);
5992
5993 const Expr *Source = E->getSourceExpr();
5994 if (!Source)
5995 return Error(E);
5996 if (Source == E) { // sanity checking.
5997 assert(0 && "OpaqueValueExpr recursively refers to itself");
5998 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00005999 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00006000 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00006001 }
Richard Smith4ce706a2011-10-11 21:43:33 +00006002
Aaron Ballman68af21c2014-01-03 19:26:43 +00006003 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00006004 APValue Result;
6005 if (!handleCallExpr(E, Result, nullptr))
6006 return false;
6007 return DerivedSuccess(Result, E);
6008 }
6009
6010 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00006011 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00006012 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00006013 QualType CalleeType = Callee->getType();
6014
Craig Topper36250ad2014-05-12 05:36:57 +00006015 const FunctionDecl *FD = nullptr;
6016 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00006017 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith921f1322019-05-13 23:35:21 +00006018 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00006019
Richard Smithe97cbd72011-11-11 04:05:33 +00006020 // Extract function decl and 'this' pointer from the callee.
6021 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smith921f1322019-05-13 23:35:21 +00006022 const CXXMethodDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00006023 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6024 // Explicit bound member calls, such as x.f() or p->g();
6025 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006026 return false;
Richard Smith921f1322019-05-13 23:35:21 +00006027 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6028 if (!Member)
6029 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006030 This = &ThisVal;
Richard Smith921f1322019-05-13 23:35:21 +00006031 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00006032 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6033 // Indirect bound member calls ('.*' or '->*').
Richard Smith921f1322019-05-13 23:35:21 +00006034 Member = dyn_cast_or_null<CXXMethodDecl>(
6035 HandleMemberPointerAccess(Info, BE, ThisVal, false));
6036 if (!Member)
6037 return Error(Callee);
Richard Smith027bf112011-11-17 22:56:20 +00006038 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00006039 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006040 return Error(Callee);
Richard Smith921f1322019-05-13 23:35:21 +00006041 FD = Member;
Richard Smithe97cbd72011-11-11 04:05:33 +00006042 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00006043 LValue Call;
6044 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006045 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00006046
Richard Smitha8105bc2012-01-06 16:39:00 +00006047 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006048 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00006049 FD = dyn_cast_or_null<FunctionDecl>(
6050 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00006051 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006052 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00006053 // Don't call function pointers which have been cast to some other type.
6054 // Per DR (no number yet), the caller and callee can differ in noexcept.
6055 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6056 CalleeType->getPointeeType(), FD->getType())) {
6057 return Error(E);
6058 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006059
6060 // Overloaded operator calls to member functions are represented as normal
6061 // calls with '*this' as the first argument.
6062 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6063 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006064 // FIXME: When selecting an implicit conversion for an overloaded
6065 // operator delete, we sometimes try to evaluate calls to conversion
6066 // operators without a 'this' parameter!
6067 if (Args.empty())
6068 return Error(E);
6069
Nick Lewycky13073a62017-06-12 21:15:44 +00006070 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00006071 return false;
6072 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00006073 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00006074 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00006075 // Map the static invoker for the lambda back to the call operator.
6076 // Conveniently, we don't have to slice out the 'this' argument (as is
6077 // being done for the non-static case), since a static member function
6078 // doesn't have an implicit argument passed in.
6079 const CXXRecordDecl *ClosureClass = MD->getParent();
6080 assert(
6081 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6082 "Number of captures must be zero for conversion to function-ptr");
6083
6084 const CXXMethodDecl *LambdaCallOp =
6085 ClosureClass->getLambdaCallOperator();
6086
6087 // Set 'FD', the function that will be called below, to the call
6088 // operator. If the closure object represents a generic lambda, find
6089 // the corresponding specialization of the call operator.
6090
6091 if (ClosureClass->isGenericLambda()) {
6092 assert(MD->isFunctionTemplateSpecialization() &&
6093 "A generic lambda's static-invoker function must be a "
6094 "template specialization");
6095 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6096 FunctionTemplateDecl *CallOpTemplate =
6097 LambdaCallOp->getDescribedFunctionTemplate();
6098 void *InsertPos = nullptr;
6099 FunctionDecl *CorrespondingCallOpSpecialization =
6100 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6101 assert(CorrespondingCallOpSpecialization &&
6102 "We must always have a function call operator specialization "
6103 "that corresponds to our static invoker specialization");
6104 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6105 } else
6106 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00006107 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006108 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00006109 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00006110
Richard Smith921f1322019-05-13 23:35:21 +00006111 SmallVector<QualType, 4> CovariantAdjustmentPath;
6112 if (This) {
6113 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006114 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
6115 // Perform virtual dispatch, if necessary.
6116 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6117 CovariantAdjustmentPath);
6118 if (!FD)
6119 return false;
6120 } else {
6121 // Check that the 'this' pointer points to an object of the right type.
6122 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
6123 return false;
6124 }
Richard Smith921f1322019-05-13 23:35:21 +00006125 }
Richard Smith47b34932012-02-01 02:39:43 +00006126
Craig Topper36250ad2014-05-12 05:36:57 +00006127 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00006128 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00006129
Nick Lewycky13073a62017-06-12 21:15:44 +00006130 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
6131 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00006132 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006133 return false;
6134
Richard Smith921f1322019-05-13 23:35:21 +00006135 if (!CovariantAdjustmentPath.empty() &&
6136 !HandleCovariantReturnAdjustment(Info, E, Result,
6137 CovariantAdjustmentPath))
6138 return false;
6139
Richard Smith52a980a2015-08-28 02:43:42 +00006140 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00006141 }
6142
Aaron Ballman68af21c2014-01-03 19:26:43 +00006143 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006144 return StmtVisitorTy::Visit(E->getInitializer());
6145 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006146 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00006147 if (E->getNumInits() == 0)
6148 return DerivedZeroInitialization(E);
6149 if (E->getNumInits() == 1)
6150 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00006151 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006152 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006153 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006154 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006155 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006156 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006157 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00006158 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006159 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006160 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006161 }
Richard Smith4ce706a2011-10-11 21:43:33 +00006162
Richard Smithd62306a2011-11-10 06:34:14 +00006163 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00006164 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006165 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
6166 "missing temporary materialization conversion");
Richard Smithd62306a2011-11-10 06:34:14 +00006167 assert(!E->isArrow() && "missing call to bound member function?");
6168
Richard Smith2e312c82012-03-03 22:46:17 +00006169 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00006170 if (!Evaluate(Val, Info, E->getBase()))
6171 return false;
6172
6173 QualType BaseTy = E->getBase()->getType();
6174
6175 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00006176 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006177 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00006178 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00006179 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6180
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006181 // Note: there is no lvalue base here. But this case should only ever
6182 // happen in C or in C++98, where we cannot be evaluating a constexpr
6183 // constructor, which is the only case the base matters.
Richard Smithdebad642019-05-12 09:39:08 +00006184 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00006185 SubobjectDesignator Designator(BaseTy);
6186 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00006187
Richard Smith3229b742013-05-05 21:17:10 +00006188 APValue Result;
6189 return extractSubobject(Info, E, Obj, Designator, Result) &&
6190 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00006191 }
6192
Aaron Ballman68af21c2014-01-03 19:26:43 +00006193 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006194 switch (E->getCastKind()) {
6195 default:
6196 break;
6197
Richard Smitha23ab512013-05-23 00:30:41 +00006198 case CK_AtomicToNonAtomic: {
6199 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00006200 // This does not need to be done in place even for class/array types:
6201 // atomic-to-non-atomic conversion implies copying the object
6202 // representation.
6203 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00006204 return false;
6205 return DerivedSuccess(AtomicVal, E);
6206 }
6207
Richard Smith11562c52011-10-28 17:51:58 +00006208 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00006209 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00006210 return StmtVisitorTy::Visit(E->getSubExpr());
6211
6212 case CK_LValueToRValue: {
6213 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006214 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
6215 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006216 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00006217 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00006218 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00006219 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006220 return false;
6221 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00006222 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00006223 case CK_LValueToRValueBitCast: {
6224 APValue DestValue, SourceValue;
6225 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
6226 return false;
6227 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
6228 return false;
6229 return DerivedSuccess(DestValue, E);
6230 }
Richard Smith11562c52011-10-28 17:51:58 +00006231 }
6232
Richard Smithf57d8cb2011-12-09 22:58:01 +00006233 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00006234 }
6235
Aaron Ballman68af21c2014-01-03 19:26:43 +00006236 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00006237 return VisitUnaryPostIncDec(UO);
6238 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006239 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00006240 return VisitUnaryPostIncDec(UO);
6241 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00006242 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006243 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006244 return Error(UO);
6245
6246 LValue LVal;
6247 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
6248 return false;
6249 APValue RVal;
6250 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
6251 UO->isIncrementOp(), &RVal))
6252 return false;
6253 return DerivedSuccess(RVal, UO);
6254 }
6255
Aaron Ballman68af21c2014-01-03 19:26:43 +00006256 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00006257 // We will have checked the full-expressions inside the statement expression
6258 // when they were completed, and don't need to check them again now.
Richard Smith045b2272019-09-10 21:24:09 +00006259 if (Info.checkingForUndefinedBehavior())
Richard Smith51f03172013-06-20 03:00:05 +00006260 return Error(E);
6261
Richard Smith08d6a2c2013-07-24 07:11:57 +00006262 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00006263 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00006264 if (CS->body_empty())
6265 return true;
6266
Richard Smith51f03172013-06-20 03:00:05 +00006267 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
6268 BE = CS->body_end();
6269 /**/; ++BI) {
6270 if (BI + 1 == BE) {
6271 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
6272 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006273 Info.FFDiag((*BI)->getBeginLoc(),
6274 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00006275 return false;
6276 }
6277 return this->Visit(FinalExpr);
6278 }
6279
6280 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00006281 StmtResult Result = { ReturnValue, nullptr };
6282 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00006283 if (ESR != ESR_Succeeded) {
6284 // FIXME: If the statement-expression terminated due to 'return',
6285 // 'break', or 'continue', it would be nice to propagate that to
6286 // the outer statement evaluation rather than bailing out.
6287 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006288 Info.FFDiag((*BI)->getBeginLoc(),
6289 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00006290 return false;
6291 }
6292 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00006293
6294 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00006295 }
6296
Richard Smith4a678122011-10-24 18:44:57 +00006297 /// Visit a value which is evaluated, but whose value is ignored.
6298 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00006299 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00006300 }
David Majnemere9807b22016-02-26 04:23:19 +00006301
6302 /// Potentially visit a MemberExpr's base expression.
6303 void VisitIgnoredBaseExpression(const Expr *E) {
6304 // While MSVC doesn't evaluate the base expression, it does diagnose the
6305 // presence of side-effecting behavior.
6306 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
6307 return;
6308 VisitIgnoredValue(E);
6309 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006310};
6311
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006312} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00006313
6314//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006315// Common base class for lvalue and temporary evaluation.
6316//===----------------------------------------------------------------------===//
6317namespace {
6318template<class Derived>
6319class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00006320 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00006321protected:
6322 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006323 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00006324 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00006325 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00006326
6327 bool Success(APValue::LValueBase B) {
6328 Result.set(B);
6329 return true;
6330 }
6331
George Burgess IVf9013bf2017-02-10 22:52:29 +00006332 bool evaluatePointer(const Expr *E, LValue &Result) {
6333 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
6334 }
6335
Richard Smith027bf112011-11-17 22:56:20 +00006336public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006337 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
6338 : ExprEvaluatorBaseTy(Info), Result(Result),
6339 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00006340
Richard Smith2e312c82012-03-03 22:46:17 +00006341 bool Success(const APValue &V, const Expr *E) {
6342 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00006343 return true;
6344 }
Richard Smith027bf112011-11-17 22:56:20 +00006345
Richard Smith027bf112011-11-17 22:56:20 +00006346 bool VisitMemberExpr(const MemberExpr *E) {
6347 // Handle non-static data members.
6348 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006349 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00006350 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006351 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00006352 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00006353 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006354 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00006355 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00006356 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00006357 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00006358 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00006359 BaseTy = E->getBase()->getType();
6360 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00006361 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006362 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006363 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00006364 Result.setInvalid(E);
6365 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006366 }
Richard Smith027bf112011-11-17 22:56:20 +00006367
Richard Smith1b78b3d2012-01-25 22:15:11 +00006368 const ValueDecl *MD = E->getMemberDecl();
6369 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
6370 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6371 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6372 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00006373 if (!HandleLValueMember(this->Info, E, Result, FD))
6374 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00006375 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00006376 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
6377 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00006378 } else
6379 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006380
Richard Smith1b78b3d2012-01-25 22:15:11 +00006381 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00006382 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00006383 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00006384 RefValue))
6385 return false;
6386 return Success(RefValue, E);
6387 }
6388 return true;
6389 }
6390
6391 bool VisitBinaryOperator(const BinaryOperator *E) {
6392 switch (E->getOpcode()) {
6393 default:
6394 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6395
6396 case BO_PtrMemD:
6397 case BO_PtrMemI:
6398 return HandleMemberPointerAccess(this->Info, E, Result);
6399 }
6400 }
6401
6402 bool VisitCastExpr(const CastExpr *E) {
6403 switch (E->getCastKind()) {
6404 default:
6405 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6406
6407 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00006408 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00006409 if (!this->Visit(E->getSubExpr()))
6410 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006411
6412 // Now figure out the necessary offset to add to the base LV to get from
6413 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00006414 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
6415 Result);
Richard Smith027bf112011-11-17 22:56:20 +00006416 }
6417 }
6418};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006419}
Richard Smith027bf112011-11-17 22:56:20 +00006420
6421//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00006422// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006423//
6424// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
6425// function designators (in C), decl references to void objects (in C), and
6426// temporaries (if building with -Wno-address-of-temporary).
6427//
6428// LValue evaluation produces values comprising a base expression of one of the
6429// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00006430// - Declarations
6431// * VarDecl
6432// * FunctionDecl
6433// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00006434// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00006435// * StringLiteral
6436// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00006437// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00006438// * ObjCEncodeExpr
6439// * AddrLabelExpr
6440// * BlockExpr
6441// * CallExpr for a MakeStringConstant builtin
Richard Smithee0ce3022019-05-17 07:06:46 +00006442// - typeid(T) expressions, as TypeInfoLValues
Richard Smithce40ad62011-11-12 22:28:03 +00006443// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00006444// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00006445// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00006446// was evaluated, for cases where the MaterializeTemporaryExpr is missing
6447// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00006448// * A MaterializeTemporaryExpr that has static storage duration, with no
6449// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00006450// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00006451//===----------------------------------------------------------------------===//
6452namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006453class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00006454 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00006455public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006456 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
6457 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00006458
Richard Smith11562c52011-10-28 17:51:58 +00006459 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00006460 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00006461
Peter Collingbournee9200682011-05-13 03:29:01 +00006462 bool VisitDeclRefExpr(const DeclRefExpr *E);
6463 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006464 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006465 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
6466 bool VisitMemberExpr(const MemberExpr *E);
6467 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
6468 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00006469 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00006470 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006471 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
6472 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00006473 bool VisitUnaryReal(const UnaryOperator *E);
6474 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00006475 bool VisitUnaryPreInc(const UnaryOperator *UO) {
6476 return VisitUnaryPreIncDec(UO);
6477 }
6478 bool VisitUnaryPreDec(const UnaryOperator *UO) {
6479 return VisitUnaryPreIncDec(UO);
6480 }
Richard Smith3229b742013-05-05 21:17:10 +00006481 bool VisitBinAssign(const BinaryOperator *BO);
6482 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00006483
Peter Collingbournee9200682011-05-13 03:29:01 +00006484 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00006485 switch (E->getCastKind()) {
6486 default:
Richard Smith027bf112011-11-17 22:56:20 +00006487 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00006488
Eli Friedmance3e02a2011-10-11 00:13:24 +00006489 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00006490 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00006491 if (!Visit(E->getSubExpr()))
6492 return false;
6493 Result.Designator.setInvalid();
6494 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00006495
Richard Smith027bf112011-11-17 22:56:20 +00006496 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00006497 if (!Visit(E->getSubExpr()))
6498 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006499 return HandleBaseToDerivedCast(Info, E, Result);
Richard Smith7bd54ab2019-05-15 20:22:21 +00006500
6501 case CK_Dynamic:
6502 if (!Visit(E->getSubExpr()))
6503 return false;
6504 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00006505 }
6506 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006507};
6508} // end anonymous namespace
6509
Richard Smith11562c52011-10-28 17:51:58 +00006510/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00006511/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00006512/// * function designators in C, and
6513/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00006514/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00006515static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
6516 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00006517 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00006518 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00006519 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006520}
6521
Peter Collingbournee9200682011-05-13 03:29:01 +00006522bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00006523 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00006524 return Success(FD);
6525 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00006526 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00006527 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00006528 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00006529 return Error(E);
6530}
Richard Smith733237d2011-10-24 23:14:33 +00006531
Faisal Vali0528a312016-11-13 06:09:16 +00006532
Richard Smith11562c52011-10-28 17:51:58 +00006533bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00006534
6535 // If we are within a lambda's call operator, check whether the 'VD' referred
6536 // to within 'E' actually represents a lambda-capture that maps to a
6537 // data-member/field within the closure object, and if so, evaluate to the
6538 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00006539 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
6540 isa<DeclRefExpr>(E) &&
6541 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
6542 // We don't always have a complete capture-map when checking or inferring if
6543 // the function call operator meets the requirements of a constexpr function
6544 // - but we don't need to evaluate the captures to determine constexprness
6545 // (dcl.constexpr C++17).
6546 if (Info.checkingPotentialConstantExpression())
6547 return false;
6548
Faisal Vali051e3a22017-02-16 04:12:21 +00006549 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00006550 // Start with 'Result' referring to the complete closure object...
6551 Result = *Info.CurrentCall->This;
6552 // ... then update it to refer to the field of the closure object
6553 // that represents the capture.
6554 if (!HandleLValueMember(Info, E, Result, FD))
6555 return false;
6556 // And if the field is of reference type, update 'Result' to refer to what
6557 // the field refers to.
6558 if (FD->getType()->isReferenceType()) {
6559 APValue RVal;
6560 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
6561 RVal))
6562 return false;
6563 Result.setFrom(Info.Ctx, RVal);
6564 }
6565 return true;
6566 }
6567 }
Craig Topper36250ad2014-05-12 05:36:57 +00006568 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00006569 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
6570 // Only if a local variable was declared in the function currently being
6571 // evaluated, do we expect to be able to find its value in the current
6572 // frame. (Otherwise it was likely declared in an enclosing context and
6573 // could either have a valid evaluatable value (for e.g. a constexpr
6574 // variable) or be ill-formed (and trigger an appropriate evaluation
6575 // diagnostic)).
6576 if (Info.CurrentCall->Callee &&
6577 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
6578 Frame = Info.CurrentCall;
6579 }
6580 }
Richard Smith3229b742013-05-05 21:17:10 +00006581
Richard Smithfec09922011-11-01 16:57:24 +00006582 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00006583 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006584 Result.set({VD, Frame->Index,
6585 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00006586 return true;
6587 }
Richard Smithce40ad62011-11-12 22:28:03 +00006588 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00006589 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00006590
Richard Smith3229b742013-05-05 21:17:10 +00006591 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006592 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006593 return false;
Richard Smithe637cbe2019-05-21 23:15:18 +00006594 if (!V->hasValue()) {
6595 // FIXME: Is it possible for V to be indeterminate here? If so, we should
6596 // adjust the diagnostic to say that.
Richard Smith6d4c6582013-11-05 22:18:15 +00006597 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00006598 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006599 return false;
6600 }
Richard Smith3229b742013-05-05 21:17:10 +00006601 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00006602}
6603
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006604bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
6605 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00006606 // Walk through the expression to find the materialized temporary itself.
6607 SmallVector<const Expr *, 2> CommaLHSs;
6608 SmallVector<SubobjectAdjustment, 2> Adjustments;
6609 const Expr *Inner = E->GetTemporaryExpr()->
6610 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00006611
Richard Smith84401042013-06-03 05:03:02 +00006612 // If we passed any comma operators, evaluate their LHSs.
6613 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
6614 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
6615 return false;
6616
Richard Smithe6c01442013-06-05 00:46:14 +00006617 // A materialized temporary with static storage duration can appear within the
6618 // result of a constant expression evaluation, so we need to preserve its
6619 // value for use outside this evaluation.
6620 APValue *Value;
6621 if (E->getStorageDuration() == SD_Static) {
6622 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00006623 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00006624 Result.set(E);
6625 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006626 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
6627 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00006628 }
6629
Richard Smithea4ad5d2013-06-06 08:19:16 +00006630 QualType Type = Inner->getType();
6631
Richard Smith84401042013-06-03 05:03:02 +00006632 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00006633 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
6634 (E->getStorageDuration() == SD_Static &&
6635 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
6636 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00006637 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00006638 }
Richard Smith84401042013-06-03 05:03:02 +00006639
6640 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00006641 for (unsigned I = Adjustments.size(); I != 0; /**/) {
6642 --I;
6643 switch (Adjustments[I].Kind) {
6644 case SubobjectAdjustment::DerivedToBaseAdjustment:
6645 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6646 Type, Result))
6647 return false;
6648 Type = Adjustments[I].DerivedToBase.BasePath->getType();
6649 break;
6650
6651 case SubobjectAdjustment::FieldAdjustment:
6652 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6653 return false;
6654 Type = Adjustments[I].Field->getType();
6655 break;
6656
6657 case SubobjectAdjustment::MemberPointerAdjustment:
6658 if (!HandleMemberPointerAccess(this->Info, Type, Result,
6659 Adjustments[I].Ptr.RHS))
6660 return false;
6661 Type = Adjustments[I].Ptr.MPT->getPointeeType();
6662 break;
6663 }
6664 }
6665
6666 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00006667}
6668
Peter Collingbournee9200682011-05-13 03:29:01 +00006669bool
6670LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00006671 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6672 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00006673 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6674 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00006675 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006676}
6677
Richard Smith6e525142011-12-27 12:18:28 +00006678bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smitha9330302019-05-17 19:19:28 +00006679 TypeInfoLValue TypeInfo;
6680
Richard Smithee0ce3022019-05-17 07:06:46 +00006681 if (!E->isPotentiallyEvaluated()) {
Richard Smithee0ce3022019-05-17 07:06:46 +00006682 if (E->isTypeOperand())
6683 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6684 else
6685 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
Richard Smitha9330302019-05-17 19:19:28 +00006686 } else {
6687 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
6688 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
6689 << E->getExprOperand()->getType()
6690 << E->getExprOperand()->getSourceRange();
6691 }
6692
6693 if (!Visit(E->getExprOperand()))
6694 return false;
6695
6696 Optional<DynamicType> DynType =
6697 ComputeDynamicType(Info, E, Result, AK_TypeId);
6698 if (!DynType)
6699 return false;
6700
6701 TypeInfo =
6702 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
Richard Smithee0ce3022019-05-17 07:06:46 +00006703 }
Richard Smith6f3d4352012-10-17 23:52:07 +00006704
Richard Smitha9330302019-05-17 19:19:28 +00006705 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
Richard Smith6e525142011-12-27 12:18:28 +00006706}
6707
Francois Pichet0066db92012-04-16 04:08:35 +00006708bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
6709 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00006710}
Francois Pichet0066db92012-04-16 04:08:35 +00006711
Peter Collingbournee9200682011-05-13 03:29:01 +00006712bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006713 // Handle static data members.
6714 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006715 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00006716 return VisitVarDecl(E, VD);
6717 }
6718
Richard Smith254a73d2011-10-28 22:34:42 +00006719 // Handle static member functions.
6720 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
6721 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00006722 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00006723 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00006724 }
6725 }
6726
Richard Smithd62306a2011-11-10 06:34:14 +00006727 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00006728 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00006729}
6730
Peter Collingbournee9200682011-05-13 03:29:01 +00006731bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006732 // FIXME: Deal with vectors as array subscript bases.
6733 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006734 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00006735
Nick Lewyckyad888682017-04-27 07:27:36 +00006736 bool Success = true;
6737 if (!evaluatePointer(E->getBase(), Result)) {
6738 if (!Info.noteFailure())
6739 return false;
6740 Success = false;
6741 }
Mike Stump11289f42009-09-09 15:08:12 +00006742
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006743 APSInt Index;
6744 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00006745 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006746
Nick Lewyckyad888682017-04-27 07:27:36 +00006747 return Success &&
6748 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006749}
Eli Friedman9a156e52008-11-12 09:44:48 +00006750
Peter Collingbournee9200682011-05-13 03:29:01 +00006751bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006752 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00006753}
6754
Richard Smith66c96992012-02-18 22:04:06 +00006755bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6756 if (!Visit(E->getSubExpr()))
6757 return false;
6758 // __real is a no-op on scalar lvalues.
6759 if (E->getSubExpr()->getType()->isAnyComplexType())
6760 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
6761 return true;
6762}
6763
6764bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6765 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
6766 "lvalue __imag__ on scalar?");
6767 if (!Visit(E->getSubExpr()))
6768 return false;
6769 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
6770 return true;
6771}
6772
Richard Smith243ef902013-05-05 23:31:59 +00006773bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006774 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00006775 return Error(UO);
6776
6777 if (!this->Visit(UO->getSubExpr()))
6778 return false;
6779
Richard Smith243ef902013-05-05 23:31:59 +00006780 return handleIncDec(
6781 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00006782 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00006783}
6784
6785bool LValueExprEvaluator::VisitCompoundAssignOperator(
6786 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006787 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00006788 return Error(CAO);
6789
Richard Smith3229b742013-05-05 21:17:10 +00006790 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00006791
6792 // The overall lvalue result is the result of evaluating the LHS.
6793 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00006794 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006795 Evaluate(RHS, this->Info, CAO->getRHS());
6796 return false;
6797 }
6798
Richard Smith3229b742013-05-05 21:17:10 +00006799 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
6800 return false;
6801
Richard Smith43e77732013-05-07 04:50:00 +00006802 return handleCompoundAssignment(
6803 this->Info, CAO,
6804 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
6805 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00006806}
6807
6808bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006809 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006810 return Error(E);
6811
Richard Smith3229b742013-05-05 21:17:10 +00006812 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00006813
6814 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00006815 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00006816 Evaluate(NewVal, this->Info, E->getRHS());
6817 return false;
6818 }
6819
Richard Smith3229b742013-05-05 21:17:10 +00006820 if (!Evaluate(NewVal, this->Info, E->getRHS()))
6821 return false;
Richard Smith243ef902013-05-05 23:31:59 +00006822
Richard Smith31c69a32019-05-21 23:15:20 +00006823 if (Info.getLangOpts().CPlusPlus2a &&
6824 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
6825 return false;
6826
Richard Smith243ef902013-05-05 23:31:59 +00006827 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00006828 NewVal);
6829}
6830
Eli Friedman9a156e52008-11-12 09:44:48 +00006831//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006832// Pointer Evaluation
6833//===----------------------------------------------------------------------===//
6834
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006835/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00006836/// returned by a function with the alloc_size attribute. Returns true if we
6837/// were successful. Places an unsigned number into `Result`.
6838///
6839/// This expects the given CallExpr to be a call to a function with an
6840/// alloc_size attribute.
6841static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6842 const CallExpr *Call,
6843 llvm::APInt &Result) {
6844 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
6845
Joel E. Denny81508102018-03-13 14:51:22 +00006846 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
6847 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00006848 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
6849 if (Call->getNumArgs() <= SizeArgNo)
6850 return false;
6851
6852 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00006853 Expr::EvalResult ExprResult;
6854 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00006855 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006856 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00006857 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
6858 return false;
6859 Into = Into.zextOrSelf(BitsInSizeT);
6860 return true;
6861 };
6862
6863 APSInt SizeOfElem;
6864 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
6865 return false;
6866
Joel E. Denny81508102018-03-13 14:51:22 +00006867 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00006868 Result = std::move(SizeOfElem);
6869 return true;
6870 }
6871
6872 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00006873 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00006874 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
6875 return false;
6876
6877 bool Overflow;
6878 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
6879 if (Overflow)
6880 return false;
6881
6882 Result = std::move(BytesAvailable);
6883 return true;
6884}
6885
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006886/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00006887/// function.
6888static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6889 const LValue &LVal,
6890 llvm::APInt &Result) {
6891 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
6892 "Can't get the size of a non alloc_size function");
6893 const auto *Base = LVal.getLValueBase().get<const Expr *>();
6894 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
6895 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
6896}
6897
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006898/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00006899/// a function with the alloc_size attribute. If it was possible to do so, this
6900/// function will return true, make Result's Base point to said function call,
6901/// and mark Result's Base as invalid.
6902static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
6903 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006904 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00006905 return false;
6906
6907 // Because we do no form of static analysis, we only support const variables.
6908 //
6909 // Additionally, we can't support parameters, nor can we support static
6910 // variables (in the latter case, use-before-assign isn't UB; in the former,
6911 // we have no clue what they'll be assigned to).
6912 const auto *VD =
6913 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
6914 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
6915 return false;
6916
6917 const Expr *Init = VD->getAnyInitializer();
6918 if (!Init)
6919 return false;
6920
6921 const Expr *E = Init->IgnoreParens();
6922 if (!tryUnwrapAllocSizeCall(E))
6923 return false;
6924
6925 // Store E instead of E unwrapped so that the type of the LValue's base is
6926 // what the user wanted.
6927 Result.setInvalid(E);
6928
6929 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006930 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00006931 return true;
6932}
6933
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006934namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006935class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006936 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00006937 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006938 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00006939
Peter Collingbournee9200682011-05-13 03:29:01 +00006940 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00006941 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00006942 return true;
6943 }
George Burgess IVe3763372016-12-22 02:50:20 +00006944
George Burgess IVf9013bf2017-02-10 22:52:29 +00006945 bool evaluateLValue(const Expr *E, LValue &Result) {
6946 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
6947 }
6948
6949 bool evaluatePointer(const Expr *E, LValue &Result) {
6950 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
6951 }
6952
George Burgess IVe3763372016-12-22 02:50:20 +00006953 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006954public:
Mike Stump11289f42009-09-09 15:08:12 +00006955
George Burgess IVf9013bf2017-02-10 22:52:29 +00006956 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
6957 : ExprEvaluatorBaseTy(info), Result(Result),
6958 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006959
Richard Smith2e312c82012-03-03 22:46:17 +00006960 bool Success(const APValue &V, const Expr *E) {
6961 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00006962 return true;
6963 }
Richard Smithfddd3842011-12-30 21:15:51 +00006964 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00006965 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
6966 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00006967 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00006968 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00006969
John McCall45d55e42010-05-07 21:00:08 +00006970 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006971 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00006972 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00006973 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00006974 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00006975 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00006976 if (E->isExpressibleAsConstantInitializer())
6977 return Success(E);
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00006978 if (Info.noteFailure())
6979 EvaluateIgnoredValue(Info, E->getSubExpr());
6980 return Error(E);
6981 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006982 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00006983 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00006984 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006985 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00006986 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00006987 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00006988 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006989 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00006990 }
Richard Smithd62306a2011-11-10 06:34:14 +00006991 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00006992 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00006993 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00006994 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00006995 if (!Info.CurrentCall->This) {
6996 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00006997 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00006998 else
Faisal Valie690b7a2016-07-02 22:34:24 +00006999 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00007000 return false;
7001 }
Richard Smithd62306a2011-11-10 06:34:14 +00007002 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00007003 // If we are inside a lambda's call operator, the 'this' expression refers
7004 // to the enclosing '*this' object (either by value or reference) which is
7005 // either copied into the closure object's field that represents the '*this'
7006 // or refers to '*this'.
7007 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7008 // Update 'Result' to refer to the data member/field of the closure object
7009 // that represents the '*this' capture.
7010 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00007011 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00007012 return false;
7013 // If we captured '*this' by reference, replace the field with its referent.
7014 if (Info.CurrentCall->LambdaThisCaptureField->getType()
7015 ->isPointerType()) {
7016 APValue RVal;
7017 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7018 RVal))
7019 return false;
7020
7021 Result.setFrom(Info.Ctx, RVal);
7022 }
7023 }
Richard Smithd62306a2011-11-10 06:34:14 +00007024 return true;
7025 }
John McCallc07a0c72011-02-17 10:25:35 +00007026
Eric Fiselier708afb52019-05-16 21:04:15 +00007027 bool VisitSourceLocExpr(const SourceLocExpr *E) {
7028 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7029 APValue LValResult = E->EvaluateInContext(
7030 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7031 Result.setFrom(Info.Ctx, LValResult);
7032 return true;
7033 }
7034
Eli Friedman449fe542009-03-23 04:56:01 +00007035 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007036};
Chris Lattner05706e882008-07-11 18:11:29 +00007037} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007038
George Burgess IVf9013bf2017-02-10 22:52:29 +00007039static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7040 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00007041 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00007042 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00007043}
7044
John McCall45d55e42010-05-07 21:00:08 +00007045bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00007046 if (E->getOpcode() != BO_Add &&
7047 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00007048 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00007049
Chris Lattner05706e882008-07-11 18:11:29 +00007050 const Expr *PExp = E->getLHS();
7051 const Expr *IExp = E->getRHS();
7052 if (IExp->getType()->isPointerType())
7053 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00007054
George Burgess IVf9013bf2017-02-10 22:52:29 +00007055 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00007056 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00007057 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007058
John McCall45d55e42010-05-07 21:00:08 +00007059 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00007060 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00007061 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007062
Richard Smith96e0c102011-11-04 02:25:55 +00007063 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00007064 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007065
Ted Kremenek28831752012-08-23 20:46:57 +00007066 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00007067 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00007068}
Eli Friedman9a156e52008-11-12 09:44:48 +00007069
John McCall45d55e42010-05-07 21:00:08 +00007070bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007071 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007072}
Mike Stump11289f42009-09-09 15:08:12 +00007073
Richard Smith81dfef92018-07-11 00:29:05 +00007074bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7075 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00007076
Eli Friedman847a2bc2009-12-27 05:43:15 +00007077 switch (E->getCastKind()) {
7078 default:
7079 break;
John McCalle3027922010-08-25 11:45:40 +00007080 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00007081 case CK_CPointerToObjCPointerCast:
7082 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00007083 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00007084 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00007085 if (!Visit(SubExpr))
7086 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00007087 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7088 // permitted in constant expressions in C++11. Bitcasts from cv void* are
7089 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00007090 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00007091 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00007092 if (SubExpr->getType()->isVoidPointerType())
7093 CCEDiag(E, diag::note_constexpr_invalid_cast)
7094 << 3 << SubExpr->getType();
7095 else
7096 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7097 }
Yaxun Liu402804b2016-12-15 08:09:08 +00007098 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7099 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00007100 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00007101
Anders Carlsson18275092010-10-31 20:41:46 +00007102 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00007103 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007104 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00007105 return false;
Richard Smith027bf112011-11-17 22:56:20 +00007106 if (!Result.Base && Result.Offset.isZero())
7107 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00007108
Richard Smithd62306a2011-11-10 06:34:14 +00007109 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00007110 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00007111 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7112 castAs<PointerType>()->getPointeeType(),
7113 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00007114
Richard Smith027bf112011-11-17 22:56:20 +00007115 case CK_BaseToDerived:
7116 if (!Visit(E->getSubExpr()))
7117 return false;
7118 if (!Result.Base && Result.Offset.isZero())
7119 return true;
7120 return HandleBaseToDerivedCast(Info, E, Result);
7121
Richard Smith7bd54ab2019-05-15 20:22:21 +00007122 case CK_Dynamic:
7123 if (!Visit(E->getSubExpr()))
7124 return false;
7125 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7126
Richard Smith0b0a0b62011-10-29 20:57:55 +00007127 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007128 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007129 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00007130
John McCalle3027922010-08-25 11:45:40 +00007131 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007132 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7133
Richard Smith2e312c82012-03-03 22:46:17 +00007134 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00007135 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00007136 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00007137
John McCall45d55e42010-05-07 21:00:08 +00007138 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00007139 unsigned Size = Info.Ctx.getTypeSize(E->getType());
7140 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007141 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00007142 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00007143 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00007144 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00007145 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00007146 return true;
7147 } else {
7148 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00007149 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00007150 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00007151 }
7152 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00007153
7154 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00007155 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00007156 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00007157 return false;
7158 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007159 APValue &Value = createTemporary(SubExpr, false, Result,
7160 *Info.CurrentCall);
7161 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00007162 return false;
7163 }
Richard Smith96e0c102011-11-04 02:25:55 +00007164 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00007165 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
7166 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00007167 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00007168 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00007169 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00007170 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00007171 }
Richard Smithdd785442011-10-31 20:57:44 +00007172
John McCalle3027922010-08-25 11:45:40 +00007173 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007174 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00007175
7176 case CK_LValueToRValue: {
7177 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00007178 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00007179 return false;
7180
7181 APValue RVal;
7182 // Note, we use the subexpression's type in order to retain cv-qualifiers.
7183 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7184 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00007185 return InvalidBaseOK &&
7186 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00007187 return Success(RVal, E);
7188 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007189 }
7190
Richard Smith11562c52011-10-28 17:51:58 +00007191 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00007192}
Chris Lattner05706e882008-07-11 18:11:29 +00007193
Richard Smith6822bd72018-10-26 19:26:45 +00007194static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
7195 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007196 // C++ [expr.alignof]p3:
7197 // When alignof is applied to a reference type, the result is the
7198 // alignment of the referenced type.
7199 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
7200 T = Ref->getPointeeType();
7201
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00007202 if (T.getQualifiers().hasUnaligned())
7203 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00007204
7205 const bool AlignOfReturnsPreferred =
7206 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
7207
7208 // __alignof is defined to return the preferred alignment.
7209 // Before 8, clang returned the preferred alignment for alignof and _Alignof
7210 // as well.
7211 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
7212 return Info.Ctx.toCharUnitsFromBits(
7213 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
7214 // alignof and _Alignof are defined to return the ABI alignment.
7215 else if (ExprKind == UETT_AlignOf)
7216 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
7217 else
7218 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00007219}
7220
Richard Smith6822bd72018-10-26 19:26:45 +00007221static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
7222 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007223 E = E->IgnoreParens();
7224
7225 // The kinds of expressions that we have special-case logic here for
7226 // should be kept up to date with the special checks for those
7227 // expressions in Sema.
7228
7229 // alignof decl is always accepted, even if it doesn't make sense: we default
7230 // to 1 in those cases.
7231 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7232 return Info.Ctx.getDeclAlign(DRE->getDecl(),
7233 /*RefAsPointee*/true);
7234
7235 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
7236 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
7237 /*RefAsPointee*/true);
7238
Richard Smith6822bd72018-10-26 19:26:45 +00007239 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007240}
7241
George Burgess IVe3763372016-12-22 02:50:20 +00007242// To be clear: this happily visits unsupported builtins. Better name welcomed.
7243bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
7244 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
7245 return true;
7246
George Burgess IVf9013bf2017-02-10 22:52:29 +00007247 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00007248 return false;
7249
7250 Result.setInvalid(E);
7251 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00007252 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00007253 return true;
7254}
7255
Peter Collingbournee9200682011-05-13 03:29:01 +00007256bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007257 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00007258 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00007259
Richard Smith6328cbd2016-11-16 00:57:23 +00007260 if (unsigned BuiltinOp = E->getBuiltinCallee())
7261 return VisitBuiltinCallExpr(E, BuiltinOp);
7262
George Burgess IVe3763372016-12-22 02:50:20 +00007263 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007264}
7265
7266bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7267 unsigned BuiltinOp) {
7268 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00007269 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00007270 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007271 case Builtin::BI__builtin_assume_aligned: {
7272 // We need to be very careful here because: if the pointer does not have the
7273 // asserted alignment, then the behavior is undefined, and undefined
7274 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00007275 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00007276 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00007277
Hal Finkel0dd05d42014-10-03 17:18:37 +00007278 LValue OffsetResult(Result);
7279 APSInt Alignment;
7280 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
7281 return false;
Richard Smith642a2362017-01-30 23:30:26 +00007282 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00007283
7284 if (E->getNumArgs() > 2) {
7285 APSInt Offset;
7286 if (!EvaluateInteger(E->getArg(2), Offset, Info))
7287 return false;
7288
Richard Smith642a2362017-01-30 23:30:26 +00007289 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007290 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
7291 }
7292
7293 // If there is a base object, then it must have the correct alignment.
7294 if (OffsetResult.Base) {
7295 CharUnits BaseAlignment;
7296 if (const ValueDecl *VD =
7297 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
7298 BaseAlignment = Info.Ctx.getDeclAlign(VD);
Richard Smithee0ce3022019-05-17 07:06:46 +00007299 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
7300 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007301 } else {
Richard Smithee0ce3022019-05-17 07:06:46 +00007302 BaseAlignment = GetAlignOfType(
7303 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00007304 }
7305
7306 if (BaseAlignment < Align) {
7307 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00007308 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00007309 CCEDiag(E->getArg(0),
7310 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00007311 << (unsigned)BaseAlignment.getQuantity()
7312 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007313 return false;
7314 }
7315 }
7316
7317 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007318 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00007319 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007320
Richard Smith642a2362017-01-30 23:30:26 +00007321 (OffsetResult.Base
7322 ? CCEDiag(E->getArg(0),
7323 diag::note_constexpr_baa_insufficient_alignment) << 1
7324 : CCEDiag(E->getArg(0),
7325 diag::note_constexpr_baa_value_insufficient_alignment))
7326 << (int)OffsetResult.Offset.getQuantity()
7327 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00007328 return false;
7329 }
7330
7331 return true;
7332 }
Eric Fiselier26187502018-12-14 21:11:28 +00007333 case Builtin::BI__builtin_launder:
7334 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00007335 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007336 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00007337 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007338 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00007339 if (Info.getLangOpts().CPlusPlus11)
7340 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7341 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007342 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00007343 else
7344 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007345 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00007346 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007347 case Builtin::BI__builtin_wcschr:
7348 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00007349 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007350 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00007351 if (!Visit(E->getArg(0)))
7352 return false;
7353 APSInt Desired;
7354 if (!EvaluateInteger(E->getArg(1), Desired, Info))
7355 return false;
7356 uint64_t MaxLength = uint64_t(-1);
7357 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007358 BuiltinOp != Builtin::BIwcschr &&
7359 BuiltinOp != Builtin::BI__builtin_strchr &&
7360 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00007361 APSInt N;
7362 if (!EvaluateInteger(E->getArg(2), N, Info))
7363 return false;
7364 MaxLength = N.getExtValue();
7365 }
Hubert Tong147b7432018-12-12 16:53:43 +00007366 // We cannot find the value if there are no candidates to match against.
7367 if (MaxLength == 0u)
7368 return ZeroInitialization(E);
7369 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
7370 Result.Designator.Invalid)
7371 return false;
7372 QualType CharTy = Result.Designator.getType(Info.Ctx);
7373 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
7374 BuiltinOp == Builtin::BI__builtin_memchr;
7375 assert(IsRawByte ||
7376 Info.Ctx.hasSameUnqualifiedType(
7377 CharTy, E->getArg(0)->getType()->getPointeeType()));
7378 // Pointers to const void may point to objects of incomplete type.
7379 if (IsRawByte && CharTy->isIncompleteType()) {
7380 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
7381 return false;
7382 }
7383 // Give up on byte-oriented matching against multibyte elements.
7384 // FIXME: We can compare the bytes in the correct order.
7385 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
7386 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007387 // Figure out what value we're actually looking for (after converting to
7388 // the corresponding unsigned type if necessary).
7389 uint64_t DesiredVal;
7390 bool StopAtNull = false;
7391 switch (BuiltinOp) {
7392 case Builtin::BIstrchr:
7393 case Builtin::BI__builtin_strchr:
7394 // strchr compares directly to the passed integer, and therefore
7395 // always fails if given an int that is not a char.
7396 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
7397 E->getArg(1)->getType(),
7398 Desired),
7399 Desired))
7400 return ZeroInitialization(E);
7401 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007402 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007403 case Builtin::BImemchr:
7404 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00007405 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00007406 // memchr compares by converting both sides to unsigned char. That's also
7407 // correct for strchr if we get this far (to cope with plain char being
7408 // unsigned in the strchr case).
7409 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
7410 break;
Richard Smithe9507952016-11-12 01:39:56 +00007411
Richard Smith8110c9d2016-11-29 19:45:17 +00007412 case Builtin::BIwcschr:
7413 case Builtin::BI__builtin_wcschr:
7414 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007415 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007416 case Builtin::BIwmemchr:
7417 case Builtin::BI__builtin_wmemchr:
7418 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
7419 DesiredVal = Desired.getZExtValue();
7420 break;
7421 }
Richard Smithe9507952016-11-12 01:39:56 +00007422
7423 for (; MaxLength; --MaxLength) {
7424 APValue Char;
7425 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
7426 !Char.isInt())
7427 return false;
7428 if (Char.getInt().getZExtValue() == DesiredVal)
7429 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00007430 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00007431 break;
7432 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
7433 return false;
7434 }
7435 // Not found: return nullptr.
7436 return ZeroInitialization(E);
7437 }
7438
Richard Smith06f71b52018-08-04 00:57:17 +00007439 case Builtin::BImemcpy:
7440 case Builtin::BImemmove:
7441 case Builtin::BIwmemcpy:
7442 case Builtin::BIwmemmove:
7443 if (Info.getLangOpts().CPlusPlus11)
7444 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7445 << /*isConstexpr*/0 << /*isConstructor*/0
7446 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7447 else
7448 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7449 LLVM_FALLTHROUGH;
7450 case Builtin::BI__builtin_memcpy:
7451 case Builtin::BI__builtin_memmove:
7452 case Builtin::BI__builtin_wmemcpy:
7453 case Builtin::BI__builtin_wmemmove: {
7454 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
7455 BuiltinOp == Builtin::BIwmemmove ||
7456 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
7457 BuiltinOp == Builtin::BI__builtin_wmemmove;
7458 bool Move = BuiltinOp == Builtin::BImemmove ||
7459 BuiltinOp == Builtin::BIwmemmove ||
7460 BuiltinOp == Builtin::BI__builtin_memmove ||
7461 BuiltinOp == Builtin::BI__builtin_wmemmove;
7462
7463 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00007464 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00007465 return false;
7466 LValue Dest = Result;
7467
7468 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00007469 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00007470 return false;
7471
7472 APSInt N;
7473 if (!EvaluateInteger(E->getArg(2), N, Info))
7474 return false;
7475 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
7476
7477 // If the size is zero, we treat this as always being a valid no-op.
7478 // (Even if one of the src and dest pointers is null.)
7479 if (!N)
7480 return true;
7481
Richard Smith128719c2018-09-13 22:47:33 +00007482 // Otherwise, if either of the operands is null, we can't proceed. Don't
7483 // try to determine the type of the copied objects, because there aren't
7484 // any.
7485 if (!Src.Base || !Dest.Base) {
7486 APValue Val;
7487 (!Src.Base ? Src : Dest).moveInto(Val);
7488 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
7489 << Move << WChar << !!Src.Base
7490 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
7491 return false;
7492 }
7493 if (Src.Designator.Invalid || Dest.Designator.Invalid)
7494 return false;
7495
Richard Smith06f71b52018-08-04 00:57:17 +00007496 // We require that Src and Dest are both pointers to arrays of
7497 // trivially-copyable type. (For the wide version, the designator will be
7498 // invalid if the designated object is not a wchar_t.)
7499 QualType T = Dest.Designator.getType(Info.Ctx);
7500 QualType SrcT = Src.Designator.getType(Info.Ctx);
7501 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
7502 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
7503 return false;
7504 }
Petr Pavlued083f22018-10-04 09:25:44 +00007505 if (T->isIncompleteType()) {
7506 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
7507 return false;
7508 }
Richard Smith06f71b52018-08-04 00:57:17 +00007509 if (!T.isTriviallyCopyableType(Info.Ctx)) {
7510 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
7511 return false;
7512 }
7513
7514 // Figure out how many T's we're copying.
7515 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
7516 if (!WChar) {
7517 uint64_t Remainder;
7518 llvm::APInt OrigN = N;
7519 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
7520 if (Remainder) {
7521 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7522 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
7523 << (unsigned)TSize;
7524 return false;
7525 }
7526 }
7527
7528 // Check that the copying will remain within the arrays, just so that we
7529 // can give a more meaningful diagnostic. This implicitly also checks that
7530 // N fits into 64 bits.
7531 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
7532 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
7533 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
7534 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7535 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
7536 << N.toString(10, /*Signed*/false);
7537 return false;
7538 }
7539 uint64_t NElems = N.getZExtValue();
7540 uint64_t NBytes = NElems * TSize;
7541
7542 // Check for overlap.
7543 int Direction = 1;
7544 if (HasSameBase(Src, Dest)) {
7545 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
7546 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
7547 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
7548 // Dest is inside the source region.
7549 if (!Move) {
7550 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7551 return false;
7552 }
7553 // For memmove and friends, copy backwards.
7554 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
7555 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
7556 return false;
7557 Direction = -1;
7558 } else if (!Move && SrcOffset >= DestOffset &&
7559 SrcOffset - DestOffset < NBytes) {
7560 // Src is inside the destination region for memcpy: invalid.
7561 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7562 return false;
7563 }
7564 }
7565
7566 while (true) {
7567 APValue Val;
Richard Smithc667cdc2019-09-18 17:37:44 +00007568 // FIXME: Set WantObjectRepresentation to true if we're copying a
7569 // char-like type?
Richard Smith06f71b52018-08-04 00:57:17 +00007570 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
7571 !handleAssignment(Info, E, Dest, T, Val))
7572 return false;
7573 // Do not iterate past the last element; if we're copying backwards, that
7574 // might take us off the start of the array.
7575 if (--NElems == 0)
7576 return true;
7577 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
7578 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
7579 return false;
7580 }
7581 }
7582
Richard Smith6cbd65d2013-07-11 02:27:57 +00007583 default:
George Burgess IVe3763372016-12-22 02:50:20 +00007584 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00007585 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007586}
Chris Lattner05706e882008-07-11 18:11:29 +00007587
7588//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00007589// Member Pointer Evaluation
7590//===----------------------------------------------------------------------===//
7591
7592namespace {
7593class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007594 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00007595 MemberPtr &Result;
7596
7597 bool Success(const ValueDecl *D) {
7598 Result = MemberPtr(D);
7599 return true;
7600 }
7601public:
7602
7603 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
7604 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7605
Richard Smith2e312c82012-03-03 22:46:17 +00007606 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007607 Result.setFrom(V);
7608 return true;
7609 }
Richard Smithfddd3842011-12-30 21:15:51 +00007610 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00007611 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00007612 }
7613
7614 bool VisitCastExpr(const CastExpr *E);
7615 bool VisitUnaryAddrOf(const UnaryOperator *E);
7616};
7617} // end anonymous namespace
7618
7619static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
7620 EvalInfo &Info) {
7621 assert(E->isRValue() && E->getType()->isMemberPointerType());
7622 return MemberPointerExprEvaluator(Info, Result).Visit(E);
7623}
7624
7625bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7626 switch (E->getCastKind()) {
7627 default:
7628 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7629
7630 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00007631 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007632 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00007633
7634 case CK_BaseToDerivedMemberPointer: {
7635 if (!Visit(E->getSubExpr()))
7636 return false;
7637 if (E->path_empty())
7638 return true;
7639 // Base-to-derived member pointer casts store the path in derived-to-base
7640 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
7641 // the wrong end of the derived->base arc, so stagger the path by one class.
7642 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
7643 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
7644 PathI != PathE; ++PathI) {
7645 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7646 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7647 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007648 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007649 }
7650 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7651 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007652 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007653 return true;
7654 }
7655
7656 case CK_DerivedToBaseMemberPointer:
7657 if (!Visit(E->getSubExpr()))
7658 return false;
7659 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7660 PathE = E->path_end(); PathI != PathE; ++PathI) {
7661 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7662 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7663 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007664 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00007665 }
7666 return true;
7667 }
7668}
7669
7670bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7671 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7672 // member can be formed.
7673 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7674}
7675
7676//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00007677// Record Evaluation
7678//===----------------------------------------------------------------------===//
7679
7680namespace {
7681 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007682 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007683 const LValue &This;
7684 APValue &Result;
7685 public:
7686
7687 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
7688 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
7689
Richard Smith2e312c82012-03-03 22:46:17 +00007690 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00007691 Result = V;
7692 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00007693 }
Richard Smithb8348f52016-05-12 22:16:28 +00007694 bool ZeroInitialization(const Expr *E) {
7695 return ZeroInitialization(E, E->getType());
7696 }
7697 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00007698
Richard Smith52a980a2015-08-28 02:43:42 +00007699 bool VisitCallExpr(const CallExpr *E) {
7700 return handleCallExpr(E, Result, &This);
7701 }
Richard Smithe97cbd72011-11-11 04:05:33 +00007702 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00007703 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00007704 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7705 return VisitCXXConstructExpr(E, E->getType());
7706 }
Faisal Valic72a08c2017-01-09 03:02:53 +00007707 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00007708 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00007709 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00007710 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007711
7712 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00007713 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007714}
Richard Smithd62306a2011-11-10 06:34:14 +00007715
Richard Smithfddd3842011-12-30 21:15:51 +00007716/// Perform zero-initialization on an object of non-union class type.
7717/// C++11 [dcl.init]p5:
7718/// To zero-initialize an object or reference of type T means:
7719/// [...]
7720/// -- if T is a (possibly cv-qualified) non-union class type,
7721/// each non-static data member and each base-class subobject is
7722/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00007723static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
7724 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00007725 const LValue &This, APValue &Result) {
7726 assert(!RD->isUnion() && "Expected non-union class type");
7727 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
7728 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00007729 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00007730
John McCalld7bca762012-05-01 00:38:49 +00007731 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007732 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7733
7734 if (CD) {
7735 unsigned Index = 0;
7736 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00007737 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00007738 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
7739 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00007740 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
7741 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00007742 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00007743 Result.getStructBase(Index)))
7744 return false;
7745 }
7746 }
7747
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007748 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00007749 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00007750 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00007751 continue;
7752
7753 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007754 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00007755 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007756
David Blaikie2d7c57e2012-04-30 02:36:29 +00007757 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007758 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00007759 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00007760 return false;
7761 }
7762
7763 return true;
7764}
7765
Richard Smithb8348f52016-05-12 22:16:28 +00007766bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
7767 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00007768 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00007769 if (RD->isUnion()) {
7770 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
7771 // object's first non-static named data member is zero-initialized
7772 RecordDecl::field_iterator I = RD->field_begin();
7773 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00007774 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00007775 return true;
7776 }
7777
7778 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00007779 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00007780 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00007781 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00007782 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00007783 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00007784 }
7785
Richard Smith5d108602012-02-17 00:44:16 +00007786 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00007787 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00007788 return false;
7789 }
7790
Richard Smitha8105bc2012-01-06 16:39:00 +00007791 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00007792}
7793
Richard Smithe97cbd72011-11-11 04:05:33 +00007794bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
7795 switch (E->getCastKind()) {
7796 default:
7797 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7798
7799 case CK_ConstructorConversion:
7800 return Visit(E->getSubExpr());
7801
7802 case CK_DerivedToBase:
7803 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00007804 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007805 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00007806 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007807 if (!DerivedObject.isStruct())
7808 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00007809
7810 // Derived-to-base rvalue conversion: just slice off the derived part.
7811 APValue *Value = &DerivedObject;
7812 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
7813 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7814 PathE = E->path_end(); PathI != PathE; ++PathI) {
7815 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
7816 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7817 Value = &Value->getStructBase(getBaseIndex(RD, Base));
7818 RD = Base;
7819 }
7820 Result = *Value;
7821 return true;
7822 }
7823 }
7824}
7825
Richard Smithd62306a2011-11-10 06:34:14 +00007826bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00007827 if (E->isTransparent())
7828 return Visit(E->getInit(0));
7829
Richard Smithd62306a2011-11-10 06:34:14 +00007830 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00007831 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007832 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007833 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
7834
7835 EvalInfo::EvaluatingConstructorRAII EvalObj(
7836 Info,
7837 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7838 CXXRD && CXXRD->getNumBases());
Richard Smithd62306a2011-11-10 06:34:14 +00007839
7840 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00007841 const FieldDecl *Field = E->getInitializedFieldInUnion();
7842 Result = APValue(Field);
7843 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00007844 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00007845
7846 // If the initializer list for a union does not contain any elements, the
7847 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00007848 // FIXME: The element should be initialized from an initializer list.
7849 // Is this difference ever observable for initializer lists which
7850 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00007851 ImplicitValueInitExpr VIE(Field->getType());
7852 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
7853
Richard Smithd62306a2011-11-10 06:34:14 +00007854 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00007855 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
7856 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00007857
7858 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7859 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7860 isa<CXXDefaultInitExpr>(InitExpr));
7861
Richard Smithb228a862012-02-15 02:18:13 +00007862 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00007863 }
7864
Richard Smithe637cbe2019-05-21 23:15:18 +00007865 if (!Result.hasValue())
Richard Smithc0d04a22016-05-25 22:06:25 +00007866 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
7867 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00007868 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00007869 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00007870
7871 // Initialize base classes.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007872 if (CXXRD && CXXRD->getNumBases()) {
Richard Smith872307e2016-03-08 22:17:41 +00007873 for (const auto &Base : CXXRD->bases()) {
7874 assert(ElementNo < E->getNumInits() && "missing init for base class");
7875 const Expr *Init = E->getInit(ElementNo);
7876
7877 LValue Subobject = This;
7878 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
7879 return false;
7880
7881 APValue &FieldVal = Result.getStructBase(ElementNo);
7882 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007883 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00007884 return false;
7885 Success = false;
7886 }
7887 ++ElementNo;
7888 }
Richard Smithd3d6f4f2019-05-12 08:57:59 +00007889
7890 EvalObj.finishedConstructingBases();
Richard Smith872307e2016-03-08 22:17:41 +00007891 }
7892
7893 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007894 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00007895 // Anonymous bit-fields are not considered members of the class for
7896 // purposes of aggregate initialization.
7897 if (Field->isUnnamedBitfield())
7898 continue;
7899
7900 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00007901
Richard Smith253c2a32012-01-27 01:14:48 +00007902 bool HaveInit = ElementNo < E->getNumInits();
7903
7904 // FIXME: Diagnostics here should point to the end of the initializer
7905 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00007906 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007907 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00007908 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00007909
7910 // Perform an implicit value-initialization for members beyond the end of
7911 // the initializer list.
7912 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00007913 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00007914
Richard Smith852c9db2013-04-20 22:23:05 +00007915 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7916 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7917 isa<CXXDefaultInitExpr>(Init));
7918
Richard Smith49ca8aa2013-08-06 07:09:20 +00007919 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7920 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
7921 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007922 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00007923 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00007924 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00007925 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00007926 }
7927 }
7928
Richard Smith253c2a32012-01-27 01:14:48 +00007929 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00007930}
7931
Richard Smithb8348f52016-05-12 22:16:28 +00007932bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7933 QualType T) {
7934 // Note that E's type is not necessarily the type of our class here; we might
7935 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00007936 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00007937 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
7938
Richard Smithfddd3842011-12-30 21:15:51 +00007939 bool ZeroInit = E->requiresZeroInitialization();
7940 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00007941 // If we've already performed zero-initialization, we're already done.
Richard Smithe637cbe2019-05-21 23:15:18 +00007942 if (Result.hasValue())
Richard Smith9eae7232012-01-12 18:54:33 +00007943 return true;
7944
Richard Smithc667cdc2019-09-18 17:37:44 +00007945 if (ZeroInit)
7946 return ZeroInitialization(E, T);
7947
7948 Result = getDefaultInitValue(T);
7949 return true;
Richard Smithcc36f692011-12-22 02:22:31 +00007950 }
7951
Craig Topper36250ad2014-05-12 05:36:57 +00007952 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00007953 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00007954
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00007955 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00007956 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007957
Richard Smith1bc5c2c2012-01-10 04:32:03 +00007958 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00007959 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00007960 if (const MaterializeTemporaryExpr *ME
7961 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
7962 return Visit(ME->GetTemporaryExpr());
7963
Richard Smithb8348f52016-05-12 22:16:28 +00007964 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00007965 return false;
7966
Craig Topper5fc8fc22014-08-27 06:28:36 +00007967 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00007968 return HandleConstructorCall(E, This, Args,
7969 cast<CXXConstructorDecl>(Definition), Info,
7970 Result);
7971}
7972
7973bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
7974 const CXXInheritedCtorInitExpr *E) {
7975 if (!Info.CurrentCall) {
7976 assert(Info.checkingPotentialConstantExpression());
7977 return false;
7978 }
7979
7980 const CXXConstructorDecl *FD = E->getConstructor();
7981 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
7982 return false;
7983
7984 const FunctionDecl *Definition = nullptr;
7985 auto Body = FD->getBody(Definition);
7986
7987 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
7988 return false;
7989
7990 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00007991 cast<CXXConstructorDecl>(Definition), Info,
7992 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00007993}
7994
Richard Smithcc1b96d2013-06-12 22:31:48 +00007995bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
7996 const CXXStdInitializerListExpr *E) {
7997 const ConstantArrayType *ArrayType =
7998 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
7999
8000 LValue Array;
8001 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
8002 return false;
8003
8004 // Get a pointer to the first element of the array.
8005 Array.addArray(Info, E, ArrayType);
8006
8007 // FIXME: Perform the checks on the field types in SemaInit.
8008 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
8009 RecordDecl::field_iterator Field = Record->field_begin();
8010 if (Field == Record->field_end())
8011 return Error(E);
8012
8013 // Start pointer.
8014 if (!Field->getType()->isPointerType() ||
8015 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8016 ArrayType->getElementType()))
8017 return Error(E);
8018
8019 // FIXME: What if the initializer_list type has base classes, etc?
8020 Result = APValue(APValue::UninitStruct(), 0, 2);
8021 Array.moveInto(Result.getStructField(0));
8022
8023 if (++Field == Record->field_end())
8024 return Error(E);
8025
8026 if (Field->getType()->isPointerType() &&
8027 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8028 ArrayType->getElementType())) {
8029 // End pointer.
8030 if (!HandleLValueArrayAdjustment(Info, E, Array,
8031 ArrayType->getElementType(),
8032 ArrayType->getSize().getZExtValue()))
8033 return false;
8034 Array.moveInto(Result.getStructField(1));
8035 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
8036 // Length.
8037 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
8038 else
8039 return Error(E);
8040
8041 if (++Field != Record->field_end())
8042 return Error(E);
8043
8044 return true;
8045}
8046
Faisal Valic72a08c2017-01-09 03:02:53 +00008047bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
8048 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
8049 if (ClosureClass->isInvalidDecl()) return false;
8050
8051 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008052
Faisal Vali051e3a22017-02-16 04:12:21 +00008053 const size_t NumFields =
8054 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00008055
8056 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
8057 E->capture_init_end()) &&
8058 "The number of lambda capture initializers should equal the number of "
8059 "fields within the closure type");
8060
Faisal Vali051e3a22017-02-16 04:12:21 +00008061 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
8062 // Iterate through all the lambda's closure object's fields and initialize
8063 // them.
8064 auto *CaptureInitIt = E->capture_init_begin();
8065 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
8066 bool Success = true;
8067 for (const auto *Field : ClosureClass->fields()) {
8068 assert(CaptureInitIt != E->capture_init_end());
8069 // Get the initializer for this field
8070 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00008071
Faisal Vali051e3a22017-02-16 04:12:21 +00008072 // If there is no initializer, either this is a VLA or an error has
8073 // occurred.
8074 if (!CurFieldInit)
8075 return Error(E);
8076
8077 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8078 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
8079 if (!Info.keepEvaluatingAfterFailure())
8080 return false;
8081 Success = false;
8082 }
8083 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00008084 }
Faisal Vali051e3a22017-02-16 04:12:21 +00008085 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00008086}
8087
Richard Smithd62306a2011-11-10 06:34:14 +00008088static bool EvaluateRecord(const Expr *E, const LValue &This,
8089 APValue &Result, EvalInfo &Info) {
8090 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00008091 "can't evaluate expression as a record rvalue");
8092 return RecordExprEvaluator(Info, This, Result).Visit(E);
8093}
8094
8095//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00008096// Temporary Evaluation
8097//
8098// Temporaries are represented in the AST as rvalues, but generally behave like
8099// lvalues. The full-object of which the temporary is a subobject is implicitly
8100// materialized so that a reference can bind to it.
8101//===----------------------------------------------------------------------===//
8102namespace {
8103class TemporaryExprEvaluator
8104 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
8105public:
8106 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00008107 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00008108
8109 /// Visit an expression which constructs the value of this temporary.
8110 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00008111 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
8112 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00008113 }
8114
8115 bool VisitCastExpr(const CastExpr *E) {
8116 switch (E->getCastKind()) {
8117 default:
8118 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8119
8120 case CK_ConstructorConversion:
8121 return VisitConstructExpr(E->getSubExpr());
8122 }
8123 }
8124 bool VisitInitListExpr(const InitListExpr *E) {
8125 return VisitConstructExpr(E);
8126 }
8127 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8128 return VisitConstructExpr(E);
8129 }
8130 bool VisitCallExpr(const CallExpr *E) {
8131 return VisitConstructExpr(E);
8132 }
Richard Smith513955c2014-12-17 19:24:30 +00008133 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
8134 return VisitConstructExpr(E);
8135 }
Faisal Valic72a08c2017-01-09 03:02:53 +00008136 bool VisitLambdaExpr(const LambdaExpr *E) {
8137 return VisitConstructExpr(E);
8138 }
Richard Smith027bf112011-11-17 22:56:20 +00008139};
8140} // end anonymous namespace
8141
8142/// Evaluate an expression of record type as a temporary.
8143static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00008144 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00008145 return TemporaryExprEvaluator(Info, Result).Visit(E);
8146}
8147
8148//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008149// Vector Evaluation
8150//===----------------------------------------------------------------------===//
8151
8152namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008153 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008154 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00008155 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008156 public:
Mike Stump11289f42009-09-09 15:08:12 +00008157
Richard Smith2d406342011-10-22 21:10:00 +00008158 VectorExprEvaluator(EvalInfo &info, APValue &Result)
8159 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00008160
Craig Topper9798b932015-09-29 04:30:05 +00008161 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008162 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
8163 // FIXME: remove this APValue copy.
8164 Result = APValue(V.data(), V.size());
8165 return true;
8166 }
Richard Smith2e312c82012-03-03 22:46:17 +00008167 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00008168 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00008169 Result = V;
8170 return true;
8171 }
Richard Smithfddd3842011-12-30 21:15:51 +00008172 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00008173
Richard Smith2d406342011-10-22 21:10:00 +00008174 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00008175 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00008176 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00008177 bool VisitInitListExpr(const InitListExpr *E);
8178 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008179 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00008180 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00008181 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008182 };
8183} // end anonymous namespace
8184
8185static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008186 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00008187 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008188}
8189
George Burgess IV533ff002015-12-11 00:23:35 +00008190bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008191 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00008192 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00008193
Richard Smith161f09a2011-12-06 22:44:34 +00008194 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00008195 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008196
Eli Friedmanc757de22011-03-25 00:43:55 +00008197 switch (E->getCastKind()) {
8198 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00008199 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00008200 if (SETy->isIntegerType()) {
8201 APSInt IntResult;
8202 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00008203 return false;
8204 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00008205 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00008206 APFloat FloatResult(0.0);
8207 if (!EvaluateFloat(SE, FloatResult, Info))
8208 return false;
8209 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00008210 } else {
Richard Smith2d406342011-10-22 21:10:00 +00008211 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008212 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00008213
8214 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00008215 SmallVector<APValue, 4> Elts(NElts, Val);
8216 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00008217 }
Eli Friedman803acb32011-12-22 03:51:45 +00008218 case CK_BitCast: {
8219 // Evaluate the operand into an APInt we can extract from.
8220 llvm::APInt SValInt;
8221 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
8222 return false;
8223 // Extract the elements
8224 QualType EltTy = VTy->getElementType();
8225 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
8226 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8227 SmallVector<APValue, 4> Elts;
8228 if (EltTy->isRealFloatingType()) {
8229 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00008230 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00008231 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00008232 FloatEltSize = 80;
8233 for (unsigned i = 0; i < NElts; i++) {
8234 llvm::APInt Elt;
8235 if (BigEndian)
8236 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
8237 else
8238 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00008239 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00008240 }
8241 } else if (EltTy->isIntegerType()) {
8242 for (unsigned i = 0; i < NElts; i++) {
8243 llvm::APInt Elt;
8244 if (BigEndian)
8245 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
8246 else
8247 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
8248 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
8249 }
8250 } else {
8251 return Error(E);
8252 }
8253 return Success(Elts, E);
8254 }
Eli Friedmanc757de22011-03-25 00:43:55 +00008255 default:
Richard Smith11562c52011-10-28 17:51:58 +00008256 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008257 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008258}
8259
Richard Smith2d406342011-10-22 21:10:00 +00008260bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008261VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008262 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008263 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00008264 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00008265
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008266 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008267 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008268
Eli Friedmanb9c71292012-01-03 23:24:20 +00008269 // The number of initializers can be less than the number of
8270 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00008271 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00008272 // should be initialized with zeroes.
8273 unsigned CountInits = 0, CountElts = 0;
8274 while (CountElts < NumElements) {
8275 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00008276 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00008277 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00008278 APValue v;
8279 if (!EvaluateVector(E->getInit(CountInits), v, Info))
8280 return Error(E);
8281 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00008282 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00008283 Elements.push_back(v.getVectorElt(j));
8284 CountElts += vlen;
8285 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008286 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00008287 if (CountInits < NumInits) {
8288 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00008289 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00008290 } else // trailing integer zero.
8291 sInt = Info.Ctx.MakeIntValue(0, EltTy);
8292 Elements.push_back(APValue(sInt));
8293 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008294 } else {
8295 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00008296 if (CountInits < NumInits) {
8297 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00008298 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00008299 } else // trailing float zero.
8300 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
8301 Elements.push_back(APValue(f));
8302 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00008303 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00008304 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008305 }
Richard Smith2d406342011-10-22 21:10:00 +00008306 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008307}
8308
Richard Smith2d406342011-10-22 21:10:00 +00008309bool
Richard Smithfddd3842011-12-30 21:15:51 +00008310VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00008311 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00008312 QualType EltTy = VT->getElementType();
8313 APValue ZeroElement;
8314 if (EltTy->isIntegerType())
8315 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
8316 else
8317 ZeroElement =
8318 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
8319
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008320 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00008321 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008322}
8323
Richard Smith2d406342011-10-22 21:10:00 +00008324bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00008325 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00008326 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00008327}
8328
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008329//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00008330// Array Evaluation
8331//===----------------------------------------------------------------------===//
8332
8333namespace {
8334 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008335 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00008336 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00008337 APValue &Result;
8338 public:
8339
Richard Smithd62306a2011-11-10 06:34:14 +00008340 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
8341 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00008342
8343 bool Success(const APValue &V, const Expr *E) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00008344 assert(V.isArray() && "expected array");
Richard Smithf3e9e432011-11-07 09:22:26 +00008345 Result = V;
8346 return true;
8347 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008348
Richard Smithfddd3842011-12-30 21:15:51 +00008349 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00008350 const ConstantArrayType *CAT =
8351 Info.Ctx.getAsConstantArrayType(E->getType());
8352 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008353 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00008354
8355 Result = APValue(APValue::UninitArray(), 0,
8356 CAT->getSize().getZExtValue());
8357 if (!Result.hasArrayFiller()) return true;
8358
Richard Smithfddd3842011-12-30 21:15:51 +00008359 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00008360 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00008361 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00008362 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00008363 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00008364 }
8365
Richard Smith52a980a2015-08-28 02:43:42 +00008366 bool VisitCallExpr(const CallExpr *E) {
8367 return handleCallExpr(E, Result, &This);
8368 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008369 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00008370 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00008371 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00008372 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
8373 const LValue &Subobject,
8374 APValue *Value, QualType Type);
Eli Friedman3bf72d72019-02-08 21:18:46 +00008375 bool VisitStringLiteral(const StringLiteral *E) {
8376 expandStringLiteral(Info, E, Result);
8377 return true;
8378 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008379 };
8380} // end anonymous namespace
8381
Richard Smithd62306a2011-11-10 06:34:14 +00008382static bool EvaluateArray(const Expr *E, const LValue &This,
8383 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00008384 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00008385 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00008386}
8387
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008388// Return true iff the given array filler may depend on the element index.
8389static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
8390 // For now, just whitelist non-class value-initialization and initialization
8391 // lists comprised of them.
8392 if (isa<ImplicitValueInitExpr>(FillerExpr))
8393 return false;
8394 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
8395 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
8396 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
8397 return true;
8398 }
8399 return false;
8400 }
8401 return true;
8402}
8403
Richard Smithf3e9e432011-11-07 09:22:26 +00008404bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8405 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
8406 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008407 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00008408
Richard Smithca2cfbf2011-12-22 01:07:19 +00008409 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
8410 // an appropriately-typed string literal enclosed in braces.
Eli Friedman3bf72d72019-02-08 21:18:46 +00008411 if (E->isStringLiteralInit())
8412 return Visit(E->getInit(0));
Richard Smithca2cfbf2011-12-22 01:07:19 +00008413
Richard Smith253c2a32012-01-27 01:14:48 +00008414 bool Success = true;
8415
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008416 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
8417 "zero-initialized array shouldn't have any initialized elts");
8418 APValue Filler;
8419 if (Result.isArray() && Result.hasArrayFiller())
8420 Filler = Result.getArrayFiller();
8421
Richard Smith9543c5e2013-04-22 14:44:29 +00008422 unsigned NumEltsToInit = E->getNumInits();
8423 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00008424 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00008425
8426 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008427 // array element.
8428 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00008429 NumEltsToInit = NumElts;
8430
Nicola Zaghen3538b392018-05-15 13:30:56 +00008431 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
8432 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00008433
Richard Smith9543c5e2013-04-22 14:44:29 +00008434 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008435
8436 // If the array was previously zero-initialized, preserve the
8437 // zero-initialized values.
Richard Smithe637cbe2019-05-21 23:15:18 +00008438 if (Filler.hasValue()) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008439 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
8440 Result.getArrayInitializedElt(I) = Filler;
8441 if (Result.hasArrayFiller())
8442 Result.getArrayFiller() = Filler;
8443 }
8444
Richard Smithd62306a2011-11-10 06:34:14 +00008445 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00008446 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00008447 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
8448 const Expr *Init =
8449 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00008450 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00008451 Info, Subobject, Init) ||
8452 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00008453 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00008454 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00008455 return false;
8456 Success = false;
8457 }
Richard Smithd62306a2011-11-10 06:34:14 +00008458 }
Richard Smithf3e9e432011-11-07 09:22:26 +00008459
Richard Smith9543c5e2013-04-22 14:44:29 +00008460 if (!Result.hasArrayFiller())
8461 return Success;
8462
8463 // If we get here, we have a trivial filler, which we can just evaluate
8464 // once and splat over the rest of the array elements.
8465 assert(FillerExpr && "no array filler for incomplete init list");
8466 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
8467 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00008468}
8469
Richard Smith410306b2016-12-12 02:53:20 +00008470bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
8471 if (E->getCommonExpr() &&
8472 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
8473 Info, E->getCommonExpr()->getSourceExpr()))
8474 return false;
8475
8476 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
8477
8478 uint64_t Elements = CAT->getSize().getZExtValue();
8479 Result = APValue(APValue::UninitArray(), Elements, Elements);
8480
8481 LValue Subobject = This;
8482 Subobject.addArray(Info, E, CAT);
8483
8484 bool Success = true;
8485 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
8486 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8487 Info, Subobject, E->getSubExpr()) ||
8488 !HandleLValueArrayAdjustment(Info, E, Subobject,
8489 CAT->getElementType(), 1)) {
8490 if (!Info.noteFailure())
8491 return false;
8492 Success = false;
8493 }
8494 }
8495
8496 return Success;
8497}
8498
Richard Smith027bf112011-11-17 22:56:20 +00008499bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00008500 return VisitCXXConstructExpr(E, This, &Result, E->getType());
8501}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008502
Richard Smith9543c5e2013-04-22 14:44:29 +00008503bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8504 const LValue &Subobject,
8505 APValue *Value,
8506 QualType Type) {
Richard Smithe637cbe2019-05-21 23:15:18 +00008507 bool HadZeroInit = Value->hasValue();
Richard Smith9543c5e2013-04-22 14:44:29 +00008508
8509 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
8510 unsigned N = CAT->getSize().getZExtValue();
8511
8512 // Preserve the array filler if we had prior zero-initialization.
8513 APValue Filler =
8514 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
8515 : APValue();
8516
8517 *Value = APValue(APValue::UninitArray(), N, N);
8518
8519 if (HadZeroInit)
8520 for (unsigned I = 0; I != N; ++I)
8521 Value->getArrayInitializedElt(I) = Filler;
8522
8523 // Initialize the elements.
8524 LValue ArrayElt = Subobject;
8525 ArrayElt.addArray(Info, E, CAT);
8526 for (unsigned I = 0; I != N; ++I)
8527 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
8528 CAT->getElementType()) ||
8529 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
8530 CAT->getElementType(), 1))
8531 return false;
8532
8533 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00008534 }
Richard Smith027bf112011-11-17 22:56:20 +00008535
Richard Smith9543c5e2013-04-22 14:44:29 +00008536 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00008537 return Error(E);
8538
Richard Smithb8348f52016-05-12 22:16:28 +00008539 return RecordExprEvaluator(Info, Subobject, *Value)
8540 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00008541}
8542
Richard Smithf3e9e432011-11-07 09:22:26 +00008543//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00008544// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00008545//
8546// As a GNU extension, we support casting pointers to sufficiently-wide integer
8547// types and back in constant folding. Integer values are thus represented
8548// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00008549//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00008550
8551namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008552class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008553 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00008554 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00008555public:
Richard Smith2e312c82012-03-03 22:46:17 +00008556 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008557 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00008558
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008559 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008560 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008561 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008562 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008563 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008564 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008565 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008566 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008567 return true;
8568 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008569 bool Success(const llvm::APSInt &SI, const Expr *E) {
8570 return Success(SI, E, Result);
8571 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008572
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008573 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008574 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008575 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008576 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00008577 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008578 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00008579 Result.getInt().setIsUnsigned(
8580 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008581 return true;
8582 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008583 bool Success(const llvm::APInt &I, const Expr *E) {
8584 return Success(I, E, Result);
8585 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008586
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008587 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008588 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00008589 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00008590 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008591 return true;
8592 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008593 bool Success(uint64_t Value, const Expr *E) {
8594 return Success(Value, E, Result);
8595 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008596
Ken Dyckdbc01912011-03-11 02:13:43 +00008597 bool Success(CharUnits Size, const Expr *E) {
8598 return Success(Size.getQuantity(), E);
8599 }
8600
Richard Smith2e312c82012-03-03 22:46:17 +00008601 bool Success(const APValue &V, const Expr *E) {
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00008602 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00008603 Result = V;
8604 return true;
8605 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008606 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00008607 }
Mike Stump11289f42009-09-09 15:08:12 +00008608
Richard Smithfddd3842011-12-30 21:15:51 +00008609 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00008610
Peter Collingbournee9200682011-05-13 03:29:01 +00008611 //===--------------------------------------------------------------------===//
8612 // Visitor Methods
8613 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00008614
Fangrui Song407659a2018-11-30 23:41:18 +00008615 bool VisitConstantExpr(const ConstantExpr *E);
8616
Chris Lattner7174bf32008-07-12 00:38:25 +00008617 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008618 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00008619 }
8620 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008621 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00008622 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008623
8624 bool CheckReferencedDecl(const Expr *E, const Decl *D);
8625 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008626 if (CheckReferencedDecl(E, E->getDecl()))
8627 return true;
8628
8629 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008630 }
8631 bool VisitMemberExpr(const MemberExpr *E) {
8632 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00008633 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008634 return true;
8635 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008636
8637 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008638 }
8639
Peter Collingbournee9200682011-05-13 03:29:01 +00008640 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00008641 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00008642 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00008643 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00008644 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00008645
Peter Collingbournee9200682011-05-13 03:29:01 +00008646 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008647 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00008648
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008649 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008650 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008651 }
Mike Stump11289f42009-09-09 15:08:12 +00008652
Ted Kremeneke65b0862012-03-06 20:05:56 +00008653 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8654 return Success(E->getValue(), E);
8655 }
Richard Smith410306b2016-12-12 02:53:20 +00008656
8657 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8658 if (Info.ArrayInitIndex == uint64_t(-1)) {
8659 // We were asked to evaluate this subexpression independent of the
8660 // enclosing ArrayInitLoopExpr. We can't do that.
8661 Info.FFDiag(E);
8662 return false;
8663 }
8664 return Success(Info.ArrayInitIndex, E);
8665 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008666
Richard Smith4ce706a2011-10-11 21:43:33 +00008667 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00008668 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00008669 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008670 }
8671
Douglas Gregor29c42f22012-02-24 07:38:34 +00008672 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8673 return Success(E->getValue(), E);
8674 }
8675
John Wiegley6242b6a2011-04-28 00:16:57 +00008676 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
8677 return Success(E->getValue(), E);
8678 }
8679
John Wiegleyf9f65842011-04-25 06:54:41 +00008680 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
8681 return Success(E->getValue(), E);
8682 }
8683
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008684 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008685 bool VisitUnaryImag(const UnaryOperator *E);
8686
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008687 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008688 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Eric Fiselier708afb52019-05-16 21:04:15 +00008689 bool VisitSourceLocExpr(const SourceLocExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00008690 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00008691};
Leonard Chandb01c3a2018-06-20 17:19:40 +00008692
8693class FixedPointExprEvaluator
8694 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
8695 APValue &Result;
8696
8697 public:
8698 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
8699 : ExprEvaluatorBaseTy(info), Result(result) {}
8700
Leonard Chandb01c3a2018-06-20 17:19:40 +00008701 bool Success(const llvm::APInt &I, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008702 return Success(
8703 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008704 }
8705
Leonard Chandb01c3a2018-06-20 17:19:40 +00008706 bool Success(uint64_t Value, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008707 return Success(
8708 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008709 }
8710
8711 bool Success(const APValue &V, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00008712 return Success(V.getFixedPoint(), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008713 }
8714
Leonard Chand3f3e162019-01-18 21:04:25 +00008715 bool Success(const APFixedPoint &V, const Expr *E) {
8716 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
8717 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8718 "Invalid evaluation result.");
8719 Result = APValue(V);
8720 return true;
8721 }
Leonard Chandb01c3a2018-06-20 17:19:40 +00008722
8723 //===--------------------------------------------------------------------===//
8724 // Visitor Methods
8725 //===--------------------------------------------------------------------===//
8726
8727 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
8728 return Success(E->getValue(), E);
8729 }
8730
Leonard Chand3f3e162019-01-18 21:04:25 +00008731 bool VisitCastExpr(const CastExpr *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008732 bool VisitUnaryOperator(const UnaryOperator *E);
Leonard Chand3f3e162019-01-18 21:04:25 +00008733 bool VisitBinaryOperator(const BinaryOperator *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00008734};
Chris Lattner05706e882008-07-11 18:11:29 +00008735} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008736
Richard Smith11562c52011-10-28 17:51:58 +00008737/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
8738/// produce either the integer value or a pointer.
8739///
8740/// GCC has a heinous extension which folds casts between pointer types and
8741/// pointer-sized integral types. We support this by allowing the evaluation of
8742/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
8743/// Some simple arithmetic on such values is supported (they are treated much
8744/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00008745static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00008746 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008747 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008748 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00008749}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008750
Richard Smithf57d8cb2011-12-09 22:58:01 +00008751static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00008752 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008753 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00008754 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008755 if (!Val.isInt()) {
8756 // FIXME: It would be better to produce the diagnostic for casting
8757 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00008758 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008759 return false;
8760 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008761 Result = Val.getInt();
8762 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008763}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008764
Eric Fiselier708afb52019-05-16 21:04:15 +00008765bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
8766 APValue Evaluated = E->EvaluateInContext(
8767 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8768 return Success(Evaluated, E);
8769}
8770
Leonard Chand3f3e162019-01-18 21:04:25 +00008771static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
8772 EvalInfo &Info) {
8773 if (E->getType()->isFixedPointType()) {
8774 APValue Val;
8775 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
8776 return false;
8777 if (!Val.isFixedPoint())
8778 return false;
8779
8780 Result = Val.getFixedPoint();
8781 return true;
8782 }
8783 return false;
8784}
8785
8786static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
8787 EvalInfo &Info) {
8788 if (E->getType()->isIntegerType()) {
8789 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
8790 APSInt Val;
8791 if (!EvaluateInteger(E, Val, Info))
8792 return false;
8793 Result = APFixedPoint(Val, FXSema);
8794 return true;
8795 } else if (E->getType()->isFixedPointType()) {
8796 return EvaluateFixedPoint(E, Result, Info);
8797 }
8798 return false;
8799}
8800
Richard Smithf57d8cb2011-12-09 22:58:01 +00008801/// Check whether the given declaration can be directly converted to an integral
8802/// rvalue. If not, no diagnostic is produced; there are other things we can
8803/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00008804bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00008805 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00008806 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00008807 // Check for signedness/width mismatches between E type and ECD value.
8808 bool SameSign = (ECD->getInitVal().isSigned()
8809 == E->getType()->isSignedIntegerOrEnumerationType());
8810 bool SameWidth = (ECD->getInitVal().getBitWidth()
8811 == Info.Ctx.getIntWidth(E->getType()));
8812 if (SameSign && SameWidth)
8813 return Success(ECD->getInitVal(), E);
8814 else {
8815 // Get rid of mismatch (otherwise Success assertions will fail)
8816 // by computing a new value matching the type of E.
8817 llvm::APSInt Val = ECD->getInitVal();
8818 if (!SameSign)
8819 Val.setIsSigned(!ECD->getInitVal().isSigned());
8820 if (!SameWidth)
8821 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
8822 return Success(Val, E);
8823 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00008824 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008825 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00008826}
8827
Richard Smith08b682b2018-05-23 21:18:00 +00008828/// Values returned by __builtin_classify_type, chosen to match the values
8829/// produced by GCC's builtin.
8830enum class GCCTypeClass {
8831 None = -1,
8832 Void = 0,
8833 Integer = 1,
8834 // GCC reserves 2 for character types, but instead classifies them as
8835 // integers.
8836 Enum = 3,
8837 Bool = 4,
8838 Pointer = 5,
8839 // GCC reserves 6 for references, but appears to never use it (because
8840 // expressions never have reference type, presumably).
8841 PointerToDataMember = 7,
8842 RealFloat = 8,
8843 Complex = 9,
8844 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
8845 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
8846 // GCC claims to reserve 11 for pointers to member functions, but *actually*
8847 // uses 12 for that purpose, same as for a class or struct. Maybe it
8848 // internally implements a pointer to member as a struct? Who knows.
8849 PointerToMemberFunction = 12, // Not a bug, see above.
8850 ClassOrStruct = 12,
8851 Union = 13,
8852 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
8853 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
8854 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
8855 // literals.
8856};
8857
Chris Lattner86ee2862008-10-06 06:40:35 +00008858/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8859/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00008860static GCCTypeClass
8861EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
8862 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00008863
Richard Smith08b682b2018-05-23 21:18:00 +00008864 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008865 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
8866
8867 switch (CanTy->getTypeClass()) {
8868#define TYPE(ID, BASE)
8869#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
8870#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
8871#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
8872#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00008873 case Type::Auto:
8874 case Type::DeducedTemplateSpecialization:
8875 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008876
8877 case Type::Builtin:
8878 switch (BT->getKind()) {
8879#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00008880#define SIGNED_TYPE(ID, SINGLETON_ID) \
8881 case BuiltinType::ID: return GCCTypeClass::Integer;
8882#define FLOATING_TYPE(ID, SINGLETON_ID) \
8883 case BuiltinType::ID: return GCCTypeClass::RealFloat;
8884#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
8885 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008886#include "clang/AST/BuiltinTypes.def"
8887 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00008888 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008889
8890 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00008891 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008892
Richard Smith08b682b2018-05-23 21:18:00 +00008893 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008894 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00008895 case BuiltinType::WChar_U:
8896 case BuiltinType::Char8:
8897 case BuiltinType::Char16:
8898 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008899 case BuiltinType::UShort:
8900 case BuiltinType::UInt:
8901 case BuiltinType::ULong:
8902 case BuiltinType::ULongLong:
8903 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00008904 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008905
Leonard Chanf921d852018-06-04 16:07:52 +00008906 case BuiltinType::UShortAccum:
8907 case BuiltinType::UAccum:
8908 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00008909 case BuiltinType::UShortFract:
8910 case BuiltinType::UFract:
8911 case BuiltinType::ULongFract:
8912 case BuiltinType::SatUShortAccum:
8913 case BuiltinType::SatUAccum:
8914 case BuiltinType::SatULongAccum:
8915 case BuiltinType::SatUShortFract:
8916 case BuiltinType::SatUFract:
8917 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00008918 return GCCTypeClass::None;
8919
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008920 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008921
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008922 case BuiltinType::ObjCId:
8923 case BuiltinType::ObjCClass:
8924 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00008925#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8926 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00008927#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00008928#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8929 case BuiltinType::Id:
8930#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008931 case BuiltinType::OCLSampler:
8932 case BuiltinType::OCLEvent:
8933 case BuiltinType::OCLClkEvent:
8934 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008935 case BuiltinType::OCLReserveID:
Richard Sandifordeb485fb2019-08-09 08:52:54 +00008936#define SVE_TYPE(Name, Id, SingletonId) \
8937 case BuiltinType::Id:
8938#include "clang/Basic/AArch64SVEACLETypes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00008939 return GCCTypeClass::None;
8940
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008941 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00008942 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008943 };
Richard Smith08b682b2018-05-23 21:18:00 +00008944 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008945
8946 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00008947 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008948
8949 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008950 case Type::ConstantArray:
8951 case Type::VariableArray:
8952 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00008953 case Type::FunctionNoProto:
8954 case Type::FunctionProto:
8955 return GCCTypeClass::Pointer;
8956
8957 case Type::MemberPointer:
8958 return CanTy->isMemberDataPointerType()
8959 ? GCCTypeClass::PointerToDataMember
8960 : GCCTypeClass::PointerToMemberFunction;
8961
8962 case Type::Complex:
8963 return GCCTypeClass::Complex;
8964
8965 case Type::Record:
8966 return CanTy->isUnionType() ? GCCTypeClass::Union
8967 : GCCTypeClass::ClassOrStruct;
8968
8969 case Type::Atomic:
8970 // GCC classifies _Atomic T the same as T.
8971 return EvaluateBuiltinClassifyType(
8972 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008973
8974 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008975 case Type::Vector:
8976 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008977 case Type::ObjCObject:
8978 case Type::ObjCInterface:
8979 case Type::ObjCObjectPointer:
8980 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00008981 // GCC classifies vectors as None. We follow its lead and classify all
8982 // other types that don't fit into the regular classification the same way.
8983 return GCCTypeClass::None;
8984
8985 case Type::LValueReference:
8986 case Type::RValueReference:
8987 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00008988 }
8989
Richard Smith08b682b2018-05-23 21:18:00 +00008990 llvm_unreachable("unexpected type class");
8991}
8992
8993/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8994/// as GCC.
8995static GCCTypeClass
8996EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
8997 // If no argument was supplied, default to None. This isn't
8998 // ideal, however it is what gcc does.
8999 if (E->getNumArgs() == 0)
9000 return GCCTypeClass::None;
9001
9002 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
9003 // being an ICE, but still folds it to a constant using the type of the first
9004 // argument.
9005 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00009006}
9007
Richard Smith5fab0c92011-12-28 19:48:30 +00009008/// EvaluateBuiltinConstantPForLValue - Determine the result of
Richard Smith31cfb312019-04-27 02:58:17 +00009009/// __builtin_constant_p when applied to the given pointer.
Richard Smith5fab0c92011-12-28 19:48:30 +00009010///
Richard Smith31cfb312019-04-27 02:58:17 +00009011/// A pointer is only "constant" if it is null (or a pointer cast to integer)
9012/// or it points to the first character of a string literal.
9013static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
9014 APValue::LValueBase Base = LV.getLValueBase();
9015 if (Base.isNull()) {
9016 // A null base is acceptable.
9017 return true;
9018 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
9019 if (!isa<StringLiteral>(E))
9020 return false;
9021 return LV.getLValueOffset().isZero();
Richard Smithee0ce3022019-05-17 07:06:46 +00009022 } else if (Base.is<TypeInfoLValue>()) {
9023 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
9024 // evaluate to true.
9025 return true;
Richard Smith31cfb312019-04-27 02:58:17 +00009026 } else {
9027 // Any other base is not constant enough for GCC.
9028 return false;
9029 }
Richard Smith5fab0c92011-12-28 19:48:30 +00009030}
9031
9032/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
9033/// GCC as we can manage.
Richard Smith31cfb312019-04-27 02:58:17 +00009034static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
Richard Smith37be3362019-05-04 04:00:45 +00009035 // This evaluation is not permitted to have side-effects, so evaluate it in
9036 // a speculative evaluation context.
9037 SpeculativeEvaluationRAII SpeculativeEval(Info);
9038
Richard Smith31cfb312019-04-27 02:58:17 +00009039 // Constant-folding is always enabled for the operand of __builtin_constant_p
9040 // (even when the enclosing evaluation context otherwise requires a strict
9041 // language-specific constant expression).
9042 FoldConstant Fold(Info, true);
9043
Richard Smith5fab0c92011-12-28 19:48:30 +00009044 QualType ArgType = Arg->getType();
9045
9046 // __builtin_constant_p always has one operand. The rules which gcc follows
9047 // are not precisely documented, but are as follows:
9048 //
9049 // - If the operand is of integral, floating, complex or enumeration type,
9050 // and can be folded to a known value of that type, it returns 1.
Richard Smith31cfb312019-04-27 02:58:17 +00009051 // - If the operand can be folded to a pointer to the first character
9052 // of a string literal (or such a pointer cast to an integral type)
9053 // or to a null pointer or an integer cast to a pointer, it returns 1.
Richard Smith5fab0c92011-12-28 19:48:30 +00009054 //
9055 // Otherwise, it returns 0.
9056 //
9057 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
Richard Smith31cfb312019-04-27 02:58:17 +00009058 // its support for this did not work prior to GCC 9 and is not yet well
9059 // understood.
9060 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
9061 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
9062 ArgType->isNullPtrType()) {
9063 APValue V;
9064 if (!::EvaluateAsRValue(Info, Arg, V)) {
9065 Fold.keepDiagnostics();
Richard Smith5fab0c92011-12-28 19:48:30 +00009066 return false;
Richard Smith31cfb312019-04-27 02:58:17 +00009067 }
Richard Smith5fab0c92011-12-28 19:48:30 +00009068
Richard Smith31cfb312019-04-27 02:58:17 +00009069 // For a pointer (possibly cast to integer), there are special rules.
Richard Smith0c6124b2015-12-03 01:36:22 +00009070 if (V.getKind() == APValue::LValue)
9071 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith31cfb312019-04-27 02:58:17 +00009072
9073 // Otherwise, any constant value is good enough.
Richard Smithe637cbe2019-05-21 23:15:18 +00009074 return V.hasValue();
Richard Smith5fab0c92011-12-28 19:48:30 +00009075 }
9076
9077 // Anything else isn't considered to be sufficiently constant.
9078 return false;
9079}
9080
John McCall95007602010-05-10 23:27:23 +00009081/// Retrieves the "underlying object type" of the given expression,
9082/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00009083static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00009084 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
9085 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00009086 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00009087 } else if (const Expr *E = B.get<const Expr*>()) {
9088 if (isa<CompoundLiteralExpr>(E))
9089 return E->getType();
Richard Smithee0ce3022019-05-17 07:06:46 +00009090 } else if (B.is<TypeInfoLValue>()) {
9091 return B.getTypeInfoType();
John McCall95007602010-05-10 23:27:23 +00009092 }
9093
9094 return QualType();
9095}
9096
George Burgess IV3a03fab2015-09-04 21:28:13 +00009097/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00009098/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00009099/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00009100/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
9101///
9102/// Always returns an RValue with a pointer representation.
9103static const Expr *ignorePointerCastsAndParens(const Expr *E) {
9104 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
9105
9106 auto *NoParens = E->IgnoreParens();
9107 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00009108 if (Cast == nullptr)
9109 return NoParens;
9110
9111 // We only conservatively allow a few kinds of casts, because this code is
9112 // inherently a simple solution that seeks to support the common case.
9113 auto CastKind = Cast->getCastKind();
9114 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
9115 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00009116 return NoParens;
9117
9118 auto *SubExpr = Cast->getSubExpr();
9119 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
9120 return NoParens;
9121 return ignorePointerCastsAndParens(SubExpr);
9122}
9123
George Burgess IVa51c4072015-10-16 01:49:01 +00009124/// Checks to see if the given LValue's Designator is at the end of the LValue's
9125/// record layout. e.g.
9126/// struct { struct { int a, b; } fst, snd; } obj;
9127/// obj.fst // no
9128/// obj.snd // yes
9129/// obj.fst.a // no
9130/// obj.fst.b // no
9131/// obj.snd.a // no
9132/// obj.snd.b // yes
9133///
9134/// Please note: this function is specialized for how __builtin_object_size
9135/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00009136///
Richard Smith6f4f0f12017-10-20 22:56:25 +00009137/// If this encounters an invalid RecordDecl or otherwise cannot determine the
9138/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00009139static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
9140 assert(!LVal.Designator.Invalid);
9141
George Burgess IV4168d752016-06-27 19:40:41 +00009142 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
9143 const RecordDecl *Parent = FD->getParent();
9144 Invalid = Parent->isInvalidDecl();
9145 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00009146 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00009147 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00009148 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
9149 };
9150
9151 auto &Base = LVal.getLValueBase();
9152 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
9153 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00009154 bool Invalid;
9155 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9156 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00009157 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00009158 for (auto *FD : IFD->chain()) {
9159 bool Invalid;
9160 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
9161 return Invalid;
9162 }
George Burgess IVa51c4072015-10-16 01:49:01 +00009163 }
9164 }
9165
George Burgess IVe3763372016-12-22 02:50:20 +00009166 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00009167 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00009168 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00009169 // If we don't know the array bound, conservatively assume we're looking at
9170 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00009171 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00009172 if (BaseType->isIncompleteArrayType())
9173 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
9174 else
9175 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00009176 }
9177
9178 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
9179 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00009180 if (BaseType->isArrayType()) {
9181 // Because __builtin_object_size treats arrays as objects, we can ignore
9182 // the index iff this is the last array in the Designator.
9183 if (I + 1 == E)
9184 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00009185 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
Richard Smith5b5e27a2019-05-10 20:05:31 +00009186 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00009187 if (Index + 1 != CAT->getSize())
9188 return false;
9189 BaseType = CAT->getElementType();
9190 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00009191 const auto *CT = BaseType->castAs<ComplexType>();
Richard Smith5b5e27a2019-05-10 20:05:31 +00009192 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00009193 if (Index != 1)
9194 return false;
9195 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00009196 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00009197 bool Invalid;
9198 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9199 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00009200 BaseType = FD->getType();
9201 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00009202 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00009203 return false;
9204 }
9205 }
9206 return true;
9207}
9208
George Burgess IVe3763372016-12-22 02:50:20 +00009209/// Tests to see if the LValue has a user-specified designator (that isn't
9210/// necessarily valid). Note that this always returns 'true' if the LValue has
9211/// an unsized array as its first designator entry, because there's currently no
9212/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00009213static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00009214 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00009215 return false;
9216
George Burgess IVe3763372016-12-22 02:50:20 +00009217 if (!LVal.Designator.Entries.empty())
9218 return LVal.Designator.isMostDerivedAnUnsizedArray();
9219
George Burgess IVa51c4072015-10-16 01:49:01 +00009220 if (!LVal.InvalidBase)
9221 return true;
9222
George Burgess IVe3763372016-12-22 02:50:20 +00009223 // If `E` is a MemberExpr, then the first part of the designator is hiding in
9224 // the LValueBase.
9225 const auto *E = LVal.Base.dyn_cast<const Expr *>();
9226 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00009227}
9228
George Burgess IVe3763372016-12-22 02:50:20 +00009229/// Attempts to detect a user writing into a piece of memory that's impossible
9230/// to figure out the size of by just using types.
9231static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
9232 const SubobjectDesignator &Designator = LVal.Designator;
9233 // Notes:
9234 // - Users can only write off of the end when we have an invalid base. Invalid
9235 // bases imply we don't know where the memory came from.
9236 // - We used to be a bit more aggressive here; we'd only be conservative if
9237 // the array at the end was flexible, or if it had 0 or 1 elements. This
9238 // broke some common standard library extensions (PR30346), but was
9239 // otherwise seemingly fine. It may be useful to reintroduce this behavior
9240 // with some sort of whitelist. OTOH, it seems that GCC is always
9241 // conservative with the last element in structs (if it's an array), so our
9242 // current behavior is more compatible than a whitelisting approach would
9243 // be.
9244 return LVal.InvalidBase &&
9245 Designator.Entries.size() == Designator.MostDerivedPathLength &&
9246 Designator.MostDerivedIsArrayElement &&
9247 isDesignatorAtObjectEnd(Ctx, LVal);
9248}
9249
9250/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
9251/// Fails if the conversion would cause loss of precision.
9252static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
9253 CharUnits &Result) {
9254 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
9255 if (Int.ugt(CharUnitsMax))
9256 return false;
9257 Result = CharUnits::fromQuantity(Int.getZExtValue());
9258 return true;
9259}
9260
9261/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
9262/// determine how many bytes exist from the beginning of the object to either
9263/// the end of the current subobject, or the end of the object itself, depending
9264/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00009265///
George Burgess IVe3763372016-12-22 02:50:20 +00009266/// If this returns false, the value of Result is undefined.
9267static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
9268 unsigned Type, const LValue &LVal,
9269 CharUnits &EndOffset) {
9270 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009271
George Burgess IV7fb7e362017-01-03 23:35:19 +00009272 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
9273 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
9274 return false;
9275 return HandleSizeof(Info, ExprLoc, Ty, Result);
9276 };
9277
George Burgess IVe3763372016-12-22 02:50:20 +00009278 // We want to evaluate the size of the entire object. This is a valid fallback
9279 // for when Type=1 and the designator is invalid, because we're asked for an
9280 // upper-bound.
9281 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
9282 // Type=3 wants a lower bound, so we can't fall back to this.
9283 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00009284 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00009285
9286 llvm::APInt APEndOffset;
9287 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9288 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9289 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9290
9291 if (LVal.InvalidBase)
9292 return false;
9293
9294 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00009295 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00009296 }
9297
George Burgess IVe3763372016-12-22 02:50:20 +00009298 // We want to evaluate the size of a subobject.
9299 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009300
9301 // The following is a moderately common idiom in C:
9302 //
9303 // struct Foo { int a; char c[1]; };
9304 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
9305 // strcpy(&F->c[0], Bar);
9306 //
George Burgess IVe3763372016-12-22 02:50:20 +00009307 // In order to not break too much legacy code, we need to support it.
9308 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
9309 // If we can resolve this to an alloc_size call, we can hand that back,
9310 // because we know for certain how many bytes there are to write to.
9311 llvm::APInt APEndOffset;
9312 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9313 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9314 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9315
9316 // If we cannot determine the size of the initial allocation, then we can't
9317 // given an accurate upper-bound. However, we are still able to give
9318 // conservative lower-bounds for Type=3.
9319 if (Type == 1)
9320 return false;
9321 }
9322
9323 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00009324 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009325 return false;
9326
George Burgess IVe3763372016-12-22 02:50:20 +00009327 // According to the GCC documentation, we want the size of the subobject
9328 // denoted by the pointer. But that's not quite right -- what we actually
9329 // want is the size of the immediately-enclosing array, if there is one.
9330 int64_t ElemsRemaining;
9331 if (Designator.MostDerivedIsArrayElement &&
9332 Designator.Entries.size() == Designator.MostDerivedPathLength) {
9333 uint64_t ArraySize = Designator.getMostDerivedArraySize();
Richard Smith5b5e27a2019-05-10 20:05:31 +00009334 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00009335 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
9336 } else {
9337 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
9338 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009339
George Burgess IVe3763372016-12-22 02:50:20 +00009340 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
9341 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00009342}
9343
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009344/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00009345/// returns true and stores the result in @p Size.
9346///
9347/// If @p WasError is non-null, this will report whether the failure to evaluate
9348/// is to be treated as an Error in IntExprEvaluator.
9349static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
9350 EvalInfo &Info, uint64_t &Size) {
9351 // Determine the denoted object.
9352 LValue LVal;
9353 {
9354 // The operand of __builtin_object_size is never evaluated for side-effects.
9355 // If there are any, but we can determine the pointed-to object anyway, then
9356 // ignore the side-effects.
9357 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00009358 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00009359
9360 if (E->isGLValue()) {
9361 // It's possible for us to be given GLValues if we're called via
9362 // Expr::tryEvaluateObjectSize.
9363 APValue RVal;
9364 if (!EvaluateAsRValue(Info, E, RVal))
9365 return false;
9366 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00009367 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
9368 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00009369 return false;
9370 }
9371
9372 // If we point to before the start of the object, there are no accessible
9373 // bytes.
9374 if (LVal.getLValueOffset().isNegative()) {
9375 Size = 0;
9376 return true;
9377 }
9378
9379 CharUnits EndOffset;
9380 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
9381 return false;
9382
9383 // If we've fallen outside of the end offset, just pretend there's nothing to
9384 // write to/read from.
9385 if (EndOffset <= LVal.getLValueOffset())
9386 Size = 0;
9387 else
9388 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
9389 return true;
John McCall95007602010-05-10 23:27:23 +00009390}
9391
Fangrui Song407659a2018-11-30 23:41:18 +00009392bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
9393 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
Gauthier Harnischdea9d572019-06-21 08:26:21 +00009394 if (E->getResultAPValueKind() != APValue::None)
9395 return Success(E->getAPValueResult(), E);
Fangrui Song407659a2018-11-30 23:41:18 +00009396 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
9397}
9398
Peter Collingbournee9200682011-05-13 03:29:01 +00009399bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00009400 if (unsigned BuiltinOp = E->getBuiltinCallee())
9401 return VisitBuiltinCallExpr(E, BuiltinOp);
9402
9403 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9404}
9405
9406bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9407 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00009408 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009409 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00009410 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00009411
Erik Pilkington9c3b5882019-01-30 20:34:53 +00009412 case Builtin::BI__builtin_dynamic_object_size:
Mike Stump722cedf2009-10-26 18:35:08 +00009413 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00009414 // The type was checked when we built the expression.
9415 unsigned Type =
9416 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9417 assert(Type <= 3 && "unexpected type");
9418
George Burgess IVe3763372016-12-22 02:50:20 +00009419 uint64_t Size;
9420 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
9421 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00009422
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009423 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00009424 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00009425
Richard Smith01ade172012-05-23 04:13:20 +00009426 // Expression had no side effects, but we couldn't statically determine the
9427 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009428 switch (Info.EvalMode) {
9429 case EvalInfo::EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009430 case EvalInfo::EM_ConstantFold:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009431 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00009432 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009433 return Error(E);
9434 case EvalInfo::EM_ConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00009435 // Reduce it to a constant now.
9436 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009437 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00009438
9439 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00009440 }
9441
Tim Northover314fbfa2018-11-02 13:14:11 +00009442 case Builtin::BI__builtin_os_log_format_buffer_size: {
9443 analyze_os_log::OSLogBufferLayout Layout;
9444 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
9445 return Success(Layout.size().getQuantity(), E);
9446 }
9447
Benjamin Kramera801f4a2012-10-06 14:42:22 +00009448 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00009449 case Builtin::BI__builtin_bswap32:
9450 case Builtin::BI__builtin_bswap64: {
9451 APSInt Val;
9452 if (!EvaluateInteger(E->getArg(0), Val, Info))
9453 return false;
9454
9455 return Success(Val.byteSwap(), E);
9456 }
9457
Richard Smith8889a3d2013-06-13 06:26:32 +00009458 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00009459 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00009460
Craig Topperf95a6d92018-08-08 22:31:12 +00009461 case Builtin::BI__builtin_clrsb:
9462 case Builtin::BI__builtin_clrsbl:
9463 case Builtin::BI__builtin_clrsbll: {
9464 APSInt Val;
9465 if (!EvaluateInteger(E->getArg(0), Val, Info))
9466 return false;
9467
9468 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
9469 }
Richard Smith8889a3d2013-06-13 06:26:32 +00009470
Richard Smith80b3c8e2013-06-13 05:04:16 +00009471 case Builtin::BI__builtin_clz:
9472 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00009473 case Builtin::BI__builtin_clzll:
9474 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00009475 APSInt Val;
9476 if (!EvaluateInteger(E->getArg(0), Val, Info))
9477 return false;
9478 if (!Val)
9479 return Error(E);
9480
9481 return Success(Val.countLeadingZeros(), E);
9482 }
9483
Fangrui Song407659a2018-11-30 23:41:18 +00009484 case Builtin::BI__builtin_constant_p: {
Richard Smith31cfb312019-04-27 02:58:17 +00009485 const Expr *Arg = E->getArg(0);
David Blaikie639b3d12019-05-03 18:11:31 +00009486 if (EvaluateBuiltinConstantP(Info, Arg))
Fangrui Song407659a2018-11-30 23:41:18 +00009487 return Success(true, E);
David Blaikie639b3d12019-05-03 18:11:31 +00009488 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
Richard Smithf7d30482019-05-02 23:21:28 +00009489 // Outside a constant context, eagerly evaluate to false in the presence
9490 // of side-effects in order to avoid -Wunsequenced false-positives in
9491 // a branch on __builtin_constant_p(expr).
Richard Smith31cfb312019-04-27 02:58:17 +00009492 return Success(false, E);
Fangrui Song407659a2018-11-30 23:41:18 +00009493 }
David Blaikie639b3d12019-05-03 18:11:31 +00009494 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9495 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00009496 }
Richard Smith8889a3d2013-06-13 06:26:32 +00009497
Eric Fiselieradd16a82019-04-24 02:23:30 +00009498 case Builtin::BI__builtin_is_constant_evaluated:
9499 return Success(Info.InConstantContext, E);
9500
Richard Smith80b3c8e2013-06-13 05:04:16 +00009501 case Builtin::BI__builtin_ctz:
9502 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00009503 case Builtin::BI__builtin_ctzll:
9504 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00009505 APSInt Val;
9506 if (!EvaluateInteger(E->getArg(0), Val, Info))
9507 return false;
9508 if (!Val)
9509 return Error(E);
9510
9511 return Success(Val.countTrailingZeros(), E);
9512 }
9513
Richard Smith8889a3d2013-06-13 06:26:32 +00009514 case Builtin::BI__builtin_eh_return_data_regno: {
9515 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9516 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
9517 return Success(Operand, E);
9518 }
9519
9520 case Builtin::BI__builtin_expect:
9521 return Visit(E->getArg(0));
9522
9523 case Builtin::BI__builtin_ffs:
9524 case Builtin::BI__builtin_ffsl:
9525 case Builtin::BI__builtin_ffsll: {
9526 APSInt Val;
9527 if (!EvaluateInteger(E->getArg(0), Val, Info))
9528 return false;
9529
9530 unsigned N = Val.countTrailingZeros();
9531 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
9532 }
9533
9534 case Builtin::BI__builtin_fpclassify: {
9535 APFloat Val(0.0);
9536 if (!EvaluateFloat(E->getArg(5), Val, Info))
9537 return false;
9538 unsigned Arg;
9539 switch (Val.getCategory()) {
9540 case APFloat::fcNaN: Arg = 0; break;
9541 case APFloat::fcInfinity: Arg = 1; break;
9542 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
9543 case APFloat::fcZero: Arg = 4; break;
9544 }
9545 return Visit(E->getArg(Arg));
9546 }
9547
9548 case Builtin::BI__builtin_isinf_sign: {
9549 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00009550 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00009551 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
9552 }
9553
Richard Smithea3019d2013-10-15 19:07:14 +00009554 case Builtin::BI__builtin_isinf: {
9555 APFloat Val(0.0);
9556 return EvaluateFloat(E->getArg(0), Val, Info) &&
9557 Success(Val.isInfinity() ? 1 : 0, E);
9558 }
9559
9560 case Builtin::BI__builtin_isfinite: {
9561 APFloat Val(0.0);
9562 return EvaluateFloat(E->getArg(0), Val, Info) &&
9563 Success(Val.isFinite() ? 1 : 0, E);
9564 }
9565
9566 case Builtin::BI__builtin_isnan: {
9567 APFloat Val(0.0);
9568 return EvaluateFloat(E->getArg(0), Val, Info) &&
9569 Success(Val.isNaN() ? 1 : 0, E);
9570 }
9571
9572 case Builtin::BI__builtin_isnormal: {
9573 APFloat Val(0.0);
9574 return EvaluateFloat(E->getArg(0), Val, Info) &&
9575 Success(Val.isNormal() ? 1 : 0, E);
9576 }
9577
Richard Smith8889a3d2013-06-13 06:26:32 +00009578 case Builtin::BI__builtin_parity:
9579 case Builtin::BI__builtin_parityl:
9580 case Builtin::BI__builtin_parityll: {
9581 APSInt Val;
9582 if (!EvaluateInteger(E->getArg(0), Val, Info))
9583 return false;
9584
9585 return Success(Val.countPopulation() % 2, E);
9586 }
9587
Richard Smith80b3c8e2013-06-13 05:04:16 +00009588 case Builtin::BI__builtin_popcount:
9589 case Builtin::BI__builtin_popcountl:
9590 case Builtin::BI__builtin_popcountll: {
9591 APSInt Val;
9592 if (!EvaluateInteger(E->getArg(0), Val, Info))
9593 return false;
9594
9595 return Success(Val.countPopulation(), E);
9596 }
9597
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009598 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00009599 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00009600 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009601 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009602 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00009603 << /*isConstexpr*/0 << /*isConstructor*/0
9604 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00009605 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00009606 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009607 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00009608 case Builtin::BI__builtin_strlen:
9609 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00009610 // As an extension, we support __builtin_strlen() as a constant expression,
9611 // and support folding strlen() to a constant.
9612 LValue String;
9613 if (!EvaluatePointer(E->getArg(0), String, Info))
9614 return false;
9615
Richard Smith8110c9d2016-11-29 19:45:17 +00009616 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
9617
Richard Smithe6c19f22013-11-15 02:10:04 +00009618 // Fast path: if it's a string literal, search the string value.
9619 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
9620 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009621 // The string literal may have embedded null characters. Find the first
9622 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00009623 StringRef Str = S->getBytes();
9624 int64_t Off = String.Offset.getQuantity();
9625 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00009626 S->getCharByteWidth() == 1 &&
9627 // FIXME: Add fast-path for wchar_t too.
9628 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00009629 Str = Str.substr(Off);
9630
9631 StringRef::size_type Pos = Str.find(0);
9632 if (Pos != StringRef::npos)
9633 Str = Str.substr(0, Pos);
9634
9635 return Success(Str.size(), E);
9636 }
9637
9638 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00009639 }
Richard Smithe6c19f22013-11-15 02:10:04 +00009640
9641 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00009642 for (uint64_t Strlen = 0; /**/; ++Strlen) {
9643 APValue Char;
9644 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9645 !Char.isInt())
9646 return false;
9647 if (!Char.getInt())
9648 return Success(Strlen, E);
9649 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9650 return false;
9651 }
9652 }
Eli Friedmana4c26022011-10-17 21:44:23 +00009653
Richard Smithe151bab2016-11-11 23:43:35 +00009654 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009655 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009656 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009657 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009658 case Builtin::BImemcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00009659 case Builtin::BIbcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009660 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009661 // A call to strlen is not a constant expression.
9662 if (Info.getLangOpts().CPlusPlus11)
9663 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9664 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00009665 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00009666 else
9667 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009668 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00009669 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009670 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00009671 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009672 case Builtin::BI__builtin_wcsncmp:
9673 case Builtin::BI__builtin_memcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00009674 case Builtin::BI__builtin_bcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00009675 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00009676 LValue String1, String2;
9677 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9678 !EvaluatePointer(E->getArg(1), String2, Info))
9679 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00009680
Richard Smithe151bab2016-11-11 23:43:35 +00009681 uint64_t MaxLength = uint64_t(-1);
9682 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00009683 BuiltinOp != Builtin::BIwcscmp &&
9684 BuiltinOp != Builtin::BI__builtin_strcmp &&
9685 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00009686 APSInt N;
9687 if (!EvaluateInteger(E->getArg(2), N, Info))
9688 return false;
9689 MaxLength = N.getExtValue();
9690 }
Hubert Tong147b7432018-12-12 16:53:43 +00009691
9692 // Empty substrings compare equal by definition.
9693 if (MaxLength == 0u)
9694 return Success(0, E);
9695
9696 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9697 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9698 String1.Designator.Invalid || String2.Designator.Invalid)
9699 return false;
9700
9701 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9702 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9703
9704 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
Clement Courbet8c3343d2019-02-14 12:00:34 +00009705 BuiltinOp == Builtin::BIbcmp ||
9706 BuiltinOp == Builtin::BI__builtin_memcmp ||
9707 BuiltinOp == Builtin::BI__builtin_bcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00009708
9709 assert(IsRawByte ||
9710 (Info.Ctx.hasSameUnqualifiedType(
9711 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9712 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9713
9714 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9715 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9716 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9717 Char1.isInt() && Char2.isInt();
9718 };
9719 const auto &AdvanceElems = [&] {
9720 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9721 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9722 };
9723
9724 if (IsRawByte) {
9725 uint64_t BytesRemaining = MaxLength;
9726 // Pointers to const void may point to objects of incomplete type.
9727 if (CharTy1->isIncompleteType()) {
9728 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9729 return false;
9730 }
9731 if (CharTy2->isIncompleteType()) {
9732 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9733 return false;
9734 }
9735 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9736 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9737 // Give up on comparing between elements with disparate widths.
9738 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9739 return false;
9740 uint64_t BytesPerElement = CharTy1Size.getQuantity();
9741 assert(BytesRemaining && "BytesRemaining should not be zero: the "
9742 "following loop considers at least one element");
9743 while (true) {
9744 APValue Char1, Char2;
9745 if (!ReadCurElems(Char1, Char2))
9746 return false;
9747 // We have compatible in-memory widths, but a possible type and
9748 // (for `bool`) internal representation mismatch.
9749 // Assuming two's complement representation, including 0 for `false` and
9750 // 1 for `true`, we can check an appropriate number of elements for
9751 // equality even if they are not byte-sized.
9752 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9753 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9754 if (Char1InMem.ne(Char2InMem)) {
9755 // If the elements are byte-sized, then we can produce a three-way
9756 // comparison result in a straightforward manner.
9757 if (BytesPerElement == 1u) {
9758 // memcmp always compares unsigned chars.
9759 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9760 }
9761 // The result is byte-order sensitive, and we have multibyte elements.
9762 // FIXME: We can compare the remaining bytes in the correct order.
9763 return false;
9764 }
9765 if (!AdvanceElems())
9766 return false;
9767 if (BytesRemaining <= BytesPerElement)
9768 break;
9769 BytesRemaining -= BytesPerElement;
9770 }
9771 // Enough elements are equal to account for the memcmp limit.
9772 return Success(0, E);
9773 }
9774
Clement Courbet8c3343d2019-02-14 12:00:34 +00009775 bool StopAtNull =
9776 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9777 BuiltinOp != Builtin::BIwmemcmp &&
9778 BuiltinOp != Builtin::BI__builtin_memcmp &&
9779 BuiltinOp != Builtin::BI__builtin_bcmp &&
9780 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00009781 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9782 BuiltinOp == Builtin::BIwcsncmp ||
9783 BuiltinOp == Builtin::BIwmemcmp ||
9784 BuiltinOp == Builtin::BI__builtin_wcscmp ||
9785 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9786 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00009787
Richard Smithe151bab2016-11-11 23:43:35 +00009788 for (; MaxLength; --MaxLength) {
9789 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +00009790 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +00009791 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00009792 if (Char1.getInt() != Char2.getInt()) {
9793 if (IsWide) // wmemcmp compares with wchar_t signedness.
9794 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9795 // memcmp always compares unsigned chars.
9796 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9797 }
Richard Smithe151bab2016-11-11 23:43:35 +00009798 if (StopAtNull && !Char1.getInt())
9799 return Success(0, E);
9800 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +00009801 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +00009802 return false;
9803 }
9804 // We hit the strncmp / memcmp limit.
9805 return Success(0, E);
9806 }
9807
Richard Smith01ba47d2012-04-13 00:45:38 +00009808 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00009809 case Builtin::BI__atomic_is_lock_free:
9810 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00009811 APSInt SizeVal;
9812 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9813 return false;
9814
9815 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9816 // of two less than the maximum inline atomic width, we know it is
9817 // lock-free. If the size isn't a power of two, or greater than the
9818 // maximum alignment where we promote atomics, we know it is not lock-free
9819 // (at least not in the sense of atomic_is_lock_free). Otherwise,
9820 // the answer can only be determined at runtime; for example, 16-byte
9821 // atomics have lock-free implementations on some, but not all,
9822 // x86-64 processors.
9823
9824 // Check power-of-two.
9825 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00009826 if (Size.isPowerOfTwo()) {
9827 // Check against inlining width.
9828 unsigned InlineWidthBits =
9829 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9830 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9831 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9832 Size == CharUnits::One() ||
9833 E->getArg(1)->isNullPointerConstant(Info.Ctx,
9834 Expr::NPC_NeverValueDependent))
9835 // OK, we will inline appropriately-aligned operations of this size,
9836 // and _Atomic(T) is appropriately-aligned.
9837 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00009838
Richard Smith01ba47d2012-04-13 00:45:38 +00009839 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9840 castAs<PointerType>()->getPointeeType();
9841 if (!PointeeType->isIncompleteType() &&
9842 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9843 // OK, we will inline operations on this object.
9844 return Success(1, E);
9845 }
9846 }
9847 }
Eli Friedmana4c26022011-10-17 21:44:23 +00009848
Richard Smith01ba47d2012-04-13 00:45:38 +00009849 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9850 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00009851 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00009852 case Builtin::BIomp_is_initial_device:
9853 // We can decide statically which value the runtime would return if called.
9854 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00009855 case Builtin::BI__builtin_add_overflow:
9856 case Builtin::BI__builtin_sub_overflow:
9857 case Builtin::BI__builtin_mul_overflow:
9858 case Builtin::BI__builtin_sadd_overflow:
9859 case Builtin::BI__builtin_uadd_overflow:
9860 case Builtin::BI__builtin_uaddl_overflow:
9861 case Builtin::BI__builtin_uaddll_overflow:
9862 case Builtin::BI__builtin_usub_overflow:
9863 case Builtin::BI__builtin_usubl_overflow:
9864 case Builtin::BI__builtin_usubll_overflow:
9865 case Builtin::BI__builtin_umul_overflow:
9866 case Builtin::BI__builtin_umull_overflow:
9867 case Builtin::BI__builtin_umulll_overflow:
9868 case Builtin::BI__builtin_saddl_overflow:
9869 case Builtin::BI__builtin_saddll_overflow:
9870 case Builtin::BI__builtin_ssub_overflow:
9871 case Builtin::BI__builtin_ssubl_overflow:
9872 case Builtin::BI__builtin_ssubll_overflow:
9873 case Builtin::BI__builtin_smul_overflow:
9874 case Builtin::BI__builtin_smull_overflow:
9875 case Builtin::BI__builtin_smulll_overflow: {
9876 LValue ResultLValue;
9877 APSInt LHS, RHS;
9878
9879 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9880 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9881 !EvaluateInteger(E->getArg(1), RHS, Info) ||
9882 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9883 return false;
9884
9885 APSInt Result;
9886 bool DidOverflow = false;
9887
9888 // If the types don't have to match, enlarge all 3 to the largest of them.
9889 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9890 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9891 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9892 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9893 ResultType->isSignedIntegerOrEnumerationType();
9894 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9895 ResultType->isSignedIntegerOrEnumerationType();
9896 uint64_t LHSSize = LHS.getBitWidth();
9897 uint64_t RHSSize = RHS.getBitWidth();
9898 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9899 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9900
9901 // Add an additional bit if the signedness isn't uniformly agreed to. We
9902 // could do this ONLY if there is a signed and an unsigned that both have
9903 // MaxBits, but the code to check that is pretty nasty. The issue will be
9904 // caught in the shrink-to-result later anyway.
9905 if (IsSigned && !AllSigned)
9906 ++MaxBits;
9907
Erich Keanefc3dfd32019-05-30 21:35:32 +00009908 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
9909 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
Erich Keane00958272018-06-13 20:43:27 +00009910 Result = APSInt(MaxBits, !IsSigned);
9911 }
9912
9913 // Find largest int.
9914 switch (BuiltinOp) {
9915 default:
9916 llvm_unreachable("Invalid value for BuiltinOp");
9917 case Builtin::BI__builtin_add_overflow:
9918 case Builtin::BI__builtin_sadd_overflow:
9919 case Builtin::BI__builtin_saddl_overflow:
9920 case Builtin::BI__builtin_saddll_overflow:
9921 case Builtin::BI__builtin_uadd_overflow:
9922 case Builtin::BI__builtin_uaddl_overflow:
9923 case Builtin::BI__builtin_uaddll_overflow:
9924 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
9925 : LHS.uadd_ov(RHS, DidOverflow);
9926 break;
9927 case Builtin::BI__builtin_sub_overflow:
9928 case Builtin::BI__builtin_ssub_overflow:
9929 case Builtin::BI__builtin_ssubl_overflow:
9930 case Builtin::BI__builtin_ssubll_overflow:
9931 case Builtin::BI__builtin_usub_overflow:
9932 case Builtin::BI__builtin_usubl_overflow:
9933 case Builtin::BI__builtin_usubll_overflow:
9934 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
9935 : LHS.usub_ov(RHS, DidOverflow);
9936 break;
9937 case Builtin::BI__builtin_mul_overflow:
9938 case Builtin::BI__builtin_smul_overflow:
9939 case Builtin::BI__builtin_smull_overflow:
9940 case Builtin::BI__builtin_smulll_overflow:
9941 case Builtin::BI__builtin_umul_overflow:
9942 case Builtin::BI__builtin_umull_overflow:
9943 case Builtin::BI__builtin_umulll_overflow:
9944 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
9945 : LHS.umul_ov(RHS, DidOverflow);
9946 break;
9947 }
9948
9949 // In the case where multiple sizes are allowed, truncate and see if
9950 // the values are the same.
9951 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9952 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9953 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9954 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
9955 // since it will give us the behavior of a TruncOrSelf in the case where
9956 // its parameter <= its size. We previously set Result to be at least the
9957 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
9958 // will work exactly like TruncOrSelf.
9959 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
9960 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
9961
9962 if (!APSInt::isSameValue(Temp, Result))
9963 DidOverflow = true;
9964 Result = Temp;
9965 }
9966
9967 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +00009968 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
9969 return false;
Erich Keane00958272018-06-13 20:43:27 +00009970 return Success(DidOverflow, E);
9971 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009972 }
Chris Lattner7174bf32008-07-12 00:38:25 +00009973}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00009974
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009975/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +00009976/// object referred to by the lvalue.
9977static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
9978 const LValue &LV) {
9979 // A null pointer can be viewed as being "past the end" but we don't
9980 // choose to look at it that way here.
9981 if (!LV.getLValueBase())
9982 return false;
9983
9984 // If the designator is valid and refers to a subobject, we're not pointing
9985 // past the end.
9986 if (!LV.getLValueDesignator().Invalid &&
9987 !LV.getLValueDesignator().isOnePastTheEnd())
9988 return false;
9989
David Majnemerc378ca52015-08-29 08:32:55 +00009990 // A pointer to an incomplete type might be past-the-end if the type's size is
9991 // zero. We cannot tell because the type is incomplete.
9992 QualType Ty = getType(LV.getLValueBase());
9993 if (Ty->isIncompleteType())
9994 return true;
9995
Richard Smithd20f1e62014-10-21 23:01:04 +00009996 // We're a past-the-end pointer if we point to the byte after the object,
9997 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00009998 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00009999 return LV.getLValueOffset() == Size;
10000}
10001
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010002namespace {
Richard Smith11562c52011-10-28 17:51:58 +000010003
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010004/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010005///
10006/// We use a data recursive algorithm for binary operators so that we are able
10007/// to handle extreme cases of chained binary operators without causing stack
10008/// overflow.
10009class DataRecursiveIntBinOpEvaluator {
10010 struct EvalResult {
10011 APValue Val;
10012 bool Failed;
10013
10014 EvalResult() : Failed(false) { }
10015
10016 void swap(EvalResult &RHS) {
10017 Val.swap(RHS.Val);
10018 Failed = RHS.Failed;
10019 RHS.Failed = false;
10020 }
10021 };
10022
10023 struct Job {
10024 const Expr *E;
10025 EvalResult LHSResult; // meaningful only for binary operator expression.
10026 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +000010027
David Blaikie73726062015-08-12 23:09:24 +000010028 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +000010029 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +000010030
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010031 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +000010032 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010033 }
George Burgess IV8c892b52016-05-25 22:31:54 +000010034
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010035 private:
George Burgess IV8c892b52016-05-25 22:31:54 +000010036 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010037 };
10038
10039 SmallVector<Job, 16> Queue;
10040
10041 IntExprEvaluator &IntEval;
10042 EvalInfo &Info;
10043 APValue &FinalResult;
10044
10045public:
10046 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
10047 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
10048
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010049 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010050 /// data recursively.
10051 /// We handle binary operators that are comma, logical, or that have operands
10052 /// with integral or enumeration type.
10053 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010054 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
10055 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +000010056 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010057 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +000010058 }
10059
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010060 bool Traverse(const BinaryOperator *E) {
10061 enqueue(E);
10062 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +000010063 while (!Queue.empty())
10064 process(PrevResult);
10065
10066 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010067
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010068 FinalResult.swap(PrevResult.Val);
10069 return true;
10070 }
10071
10072private:
10073 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10074 return IntEval.Success(Value, E, Result);
10075 }
10076 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
10077 return IntEval.Success(Value, E, Result);
10078 }
10079 bool Error(const Expr *E) {
10080 return IntEval.Error(E);
10081 }
10082 bool Error(const Expr *E, diag::kind D) {
10083 return IntEval.Error(E, D);
10084 }
10085
10086 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
10087 return Info.CCEDiag(E, D);
10088 }
10089
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010090 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010091 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010092 bool &SuppressRHSDiags);
10093
10094 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10095 const BinaryOperator *E, APValue &Result);
10096
10097 void EvaluateExpr(const Expr *E, EvalResult &Result) {
10098 Result.Failed = !Evaluate(Result.Val, Info, E);
10099 if (Result.Failed)
10100 Result.Val = APValue();
10101 }
10102
Richard Trieuba4d0872012-03-21 23:30:30 +000010103 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010104
10105 void enqueue(const Expr *E) {
10106 E = E->IgnoreParens();
10107 Queue.resize(Queue.size()+1);
10108 Queue.back().E = E;
10109 Queue.back().Kind = Job::AnyExprKind;
10110 }
10111};
10112
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010113}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010114
10115bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010116 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010117 bool &SuppressRHSDiags) {
10118 if (E->getOpcode() == BO_Comma) {
10119 // Ignore LHS but note if we could not evaluate it.
10120 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +000010121 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010122 return true;
10123 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010124
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010125 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +000010126 bool LHSAsBool;
10127 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010128 // We were able to evaluate the LHS, see if we can get away with not
10129 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +000010130 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
10131 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010132 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010133 }
10134 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +000010135 LHSResult.Failed = true;
10136
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010137 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +000010138 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +000010139 if (!Info.noteSideEffect())
10140 return false;
10141
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010142 // We can't evaluate the LHS; however, sometimes the result
10143 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10144 // Don't ignore RHS and suppress diagnostics from this arm.
10145 SuppressRHSDiags = true;
10146 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010147
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010148 return true;
10149 }
Richard Smith4e66f1f2013-11-06 02:19:10 +000010150
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010151 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10152 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +000010153
George Burgess IVa145e252016-05-25 22:38:36 +000010154 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010155 return false; // Ignore RHS;
10156
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010157 return true;
10158}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010159
Benjamin Kramerf6021ec2017-03-21 21:35:04 +000010160static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
10161 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +000010162 // Compute the new offset in the appropriate width, wrapping at 64 bits.
10163 // FIXME: When compiling for a 32-bit target, we should use 32-bit
10164 // offsets.
10165 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
10166 CharUnits &Offset = LVal.getLValueOffset();
10167 uint64_t Offset64 = Offset.getQuantity();
10168 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
10169 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
10170 : Offset64 + Index64);
10171}
10172
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010173bool DataRecursiveIntBinOpEvaluator::
10174 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10175 const BinaryOperator *E, APValue &Result) {
10176 if (E->getOpcode() == BO_Comma) {
10177 if (RHSResult.Failed)
10178 return false;
10179 Result = RHSResult.Val;
10180 return true;
10181 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010182
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010183 if (E->isLogicalOp()) {
10184 bool lhsResult, rhsResult;
10185 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
10186 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +000010187
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010188 if (LHSIsOK) {
10189 if (RHSIsOK) {
10190 if (E->getOpcode() == BO_LOr)
10191 return Success(lhsResult || rhsResult, E, Result);
10192 else
10193 return Success(lhsResult && rhsResult, E, Result);
10194 }
10195 } else {
10196 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010197 // We can't evaluate the LHS; however, sometimes the result
10198 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10199 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010200 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010201 }
10202 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010203
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +000010204 return false;
10205 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010206
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010207 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10208 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +000010209
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010210 if (LHSResult.Failed || RHSResult.Failed)
10211 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010212
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010213 const APValue &LHSVal = LHSResult.Val;
10214 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +000010215
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010216 // Handle cases like (unsigned long)&a + 4.
10217 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
10218 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000010219 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010220 return true;
10221 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010222
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010223 // Handle cases like 4 + (unsigned long)&a
10224 if (E->getOpcode() == BO_Add &&
10225 RHSVal.isLValue() && LHSVal.isInt()) {
10226 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +000010227 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010228 return true;
10229 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010230
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010231 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
10232 // Handle (intptr_t)&&A - (intptr_t)&&B.
10233 if (!LHSVal.getLValueOffset().isZero() ||
10234 !RHSVal.getLValueOffset().isZero())
10235 return false;
10236 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
10237 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
10238 if (!LHSExpr || !RHSExpr)
10239 return false;
10240 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10241 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10242 if (!LHSAddrExpr || !RHSAddrExpr)
10243 return false;
10244 // Make sure both labels come from the same function.
10245 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10246 RHSAddrExpr->getLabel()->getDeclContext())
10247 return false;
10248 Result = APValue(LHSAddrExpr, RHSAddrExpr);
10249 return true;
10250 }
Richard Smith43e77732013-05-07 04:50:00 +000010251
10252 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010253 if (!LHSVal.isInt() || !RHSVal.isInt())
10254 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +000010255
10256 // Set up the width and signedness manually, in case it can't be deduced
10257 // from the operation we're performing.
10258 // FIXME: Don't do this in the cases where we can deduce it.
10259 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
10260 E->getType()->isUnsignedIntegerOrEnumerationType());
10261 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
10262 RHSVal.getInt(), Value))
10263 return false;
10264 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010265}
10266
Richard Trieuba4d0872012-03-21 23:30:30 +000010267void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010268 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +000010269
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010270 switch (job.Kind) {
10271 case Job::AnyExprKind: {
10272 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
10273 if (shouldEnqueue(Bop)) {
10274 job.Kind = Job::BinOpKind;
10275 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000010276 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010277 }
10278 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010279
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010280 EvaluateExpr(job.E, Result);
10281 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000010282 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010283 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010284
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010285 case Job::BinOpKind: {
10286 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010287 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010288 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010289 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000010290 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010291 }
10292 if (SuppressRHSDiags)
10293 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +000010294 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010295 job.Kind = Job::BinOpVisitedLHSKind;
10296 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +000010297 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010298 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010299
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010300 case Job::BinOpVisitedLHSKind: {
10301 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10302 EvalResult RHS;
10303 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +000010304 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010305 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +000010306 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010307 }
10308 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010309
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010310 llvm_unreachable("Invalid Job::Kind!");
10311}
10312
George Burgess IV8c892b52016-05-25 22:31:54 +000010313namespace {
10314/// Used when we determine that we should fail, but can keep evaluating prior to
10315/// noting that we had a failure.
10316class DelayedNoteFailureRAII {
10317 EvalInfo &Info;
10318 bool NoteFailure;
10319
10320public:
10321 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
10322 : Info(Info), NoteFailure(NoteFailure) {}
10323 ~DelayedNoteFailureRAII() {
10324 if (NoteFailure) {
10325 bool ContinueAfterFailure = Info.noteFailure();
10326 (void)ContinueAfterFailure;
10327 assert(ContinueAfterFailure &&
10328 "Shouldn't have kept evaluating on failure.");
10329 }
10330 }
10331};
10332}
10333
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010334template <class SuccessCB, class AfterCB>
10335static bool
10336EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
10337 SuccessCB &&Success, AfterCB &&DoAfter) {
10338 assert(E->isComparisonOp() && "expected comparison operator");
10339 assert((E->getOpcode() == BO_Cmp ||
10340 E->getType()->isIntegralOrEnumerationType()) &&
10341 "unsupported binary expression evaluation");
10342 auto Error = [&](const Expr *E) {
10343 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10344 return false;
10345 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010346
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010347 using CCR = ComparisonCategoryResult;
10348 bool IsRelational = E->isRelationalOp();
10349 bool IsEquality = E->isEqualityOp();
10350 if (E->getOpcode() == BO_Cmp) {
10351 const ComparisonCategoryInfo &CmpInfo =
10352 Info.Ctx.CompCategories.getInfoForType(E->getType());
10353 IsRelational = CmpInfo.isOrdered();
10354 IsEquality = CmpInfo.isEquality();
10355 }
Eli Friedman5a332ea2008-11-13 06:09:17 +000010356
Anders Carlssonacc79812008-11-16 07:17:21 +000010357 QualType LHSTy = E->getLHS()->getType();
10358 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010359
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010360 if (LHSTy->isIntegralOrEnumerationType() &&
10361 RHSTy->isIntegralOrEnumerationType()) {
10362 APSInt LHS, RHS;
10363 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
10364 if (!LHSOK && !Info.noteFailure())
10365 return false;
10366 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
10367 return false;
10368 if (LHS < RHS)
10369 return Success(CCR::Less, E);
10370 if (LHS > RHS)
10371 return Success(CCR::Greater, E);
10372 return Success(CCR::Equal, E);
10373 }
10374
Leonard Chance1d4f12019-02-21 20:50:09 +000010375 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
10376 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
10377 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
10378
10379 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
10380 if (!LHSOK && !Info.noteFailure())
10381 return false;
10382 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
10383 return false;
10384 if (LHSFX < RHSFX)
10385 return Success(CCR::Less, E);
10386 if (LHSFX > RHSFX)
10387 return Success(CCR::Greater, E);
10388 return Success(CCR::Equal, E);
10389 }
10390
Chandler Carruthb29a7432014-10-11 11:03:30 +000010391 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000010392 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +000010393 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +000010394 if (E->isAssignmentOp()) {
10395 LValue LV;
10396 EvaluateLValue(E->getLHS(), LV, Info);
10397 LHSOK = false;
10398 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +000010399 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
10400 if (LHSOK) {
10401 LHS.makeComplexFloat();
10402 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
10403 }
10404 } else {
10405 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
10406 }
George Burgess IVa145e252016-05-25 22:38:36 +000010407 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010408 return false;
10409
Chandler Carruthb29a7432014-10-11 11:03:30 +000010410 if (E->getRHS()->getType()->isRealFloatingType()) {
10411 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
10412 return false;
10413 RHS.makeComplexFloat();
10414 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
10415 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010416 return false;
10417
10418 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +000010419 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010420 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +000010421 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010422 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010423 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
10424 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010425 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010426 assert(IsEquality && "invalid complex comparison");
10427 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
10428 LHS.getComplexIntImag() == RHS.getComplexIntImag();
10429 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +000010430 }
10431 }
Mike Stump11289f42009-09-09 15:08:12 +000010432
Anders Carlssonacc79812008-11-16 07:17:21 +000010433 if (LHSTy->isRealFloatingType() &&
10434 RHSTy->isRealFloatingType()) {
10435 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +000010436
Richard Smith253c2a32012-01-27 01:14:48 +000010437 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010438 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +000010439 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010440
Richard Smith253c2a32012-01-27 01:14:48 +000010441 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +000010442 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010443
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010444 assert(E->isComparisonOp() && "Invalid binary operator!");
10445 auto GetCmpRes = [&]() {
10446 switch (LHS.compare(RHS)) {
10447 case APFloat::cmpEqual:
10448 return CCR::Equal;
10449 case APFloat::cmpLessThan:
10450 return CCR::Less;
10451 case APFloat::cmpGreaterThan:
10452 return CCR::Greater;
10453 case APFloat::cmpUnordered:
10454 return CCR::Unordered;
10455 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +000010456 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010457 };
10458 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +000010459 }
Mike Stump11289f42009-09-09 15:08:12 +000010460
Eli Friedmana38da572009-04-28 19:17:36 +000010461 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010462 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +000010463
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010464 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10465 if (!LHSOK && !Info.noteFailure())
10466 return false;
Eli Friedman64004332009-03-23 04:38:34 +000010467
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010468 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10469 return false;
Eli Friedman64004332009-03-23 04:38:34 +000010470
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010471 // Reject differing bases from the normal codepath; we special-case
10472 // comparisons to null.
10473 if (!HasSameBase(LHSValue, RHSValue)) {
10474 // Inequalities and subtractions between unrelated pointers have
10475 // unspecified or undefined behavior.
10476 if (!IsEquality)
10477 return Error(E);
10478 // A constant address may compare equal to the address of a symbol.
10479 // The one exception is that address of an object cannot compare equal
10480 // to a null pointer constant.
10481 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
10482 (!RHSValue.Base && !RHSValue.Offset.isZero()))
10483 return Error(E);
10484 // It's implementation-defined whether distinct literals will have
10485 // distinct addresses. In clang, the result of such a comparison is
10486 // unspecified, so it is not a constant expression. However, we do know
10487 // that the address of a literal will be non-null.
10488 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
10489 LHSValue.Base && RHSValue.Base)
10490 return Error(E);
10491 // We can't tell whether weak symbols will end up pointing to the same
10492 // object.
10493 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
10494 return Error(E);
10495 // We can't compare the address of the start of one object with the
10496 // past-the-end address of another object, per C++ DR1652.
10497 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
10498 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
10499 (RHSValue.Base && RHSValue.Offset.isZero() &&
10500 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
10501 return Error(E);
10502 // We can't tell whether an object is at the same address as another
10503 // zero sized object.
10504 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
10505 (LHSValue.Base && isZeroSized(RHSValue)))
10506 return Error(E);
10507 return Success(CCR::Nonequal, E);
10508 }
Eli Friedman64004332009-03-23 04:38:34 +000010509
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010510 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10511 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +000010512
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010513 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10514 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +000010515
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010516 // C++11 [expr.rel]p3:
10517 // Pointers to void (after pointer conversions) can be compared, with a
10518 // result defined as follows: If both pointers represent the same
10519 // address or are both the null pointer value, the result is true if the
10520 // operator is <= or >= and false otherwise; otherwise the result is
10521 // unspecified.
10522 // We interpret this as applying to pointers to *cv* void.
10523 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
10524 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +000010525
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010526 // C++11 [expr.rel]p2:
10527 // - If two pointers point to non-static data members of the same object,
10528 // or to subobjects or array elements fo such members, recursively, the
10529 // pointer to the later declared member compares greater provided the
10530 // two members have the same access control and provided their class is
10531 // not a union.
10532 // [...]
10533 // - Otherwise pointer comparisons are unspecified.
10534 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
10535 bool WasArrayIndex;
10536 unsigned Mismatch = FindDesignatorMismatch(
10537 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
10538 // At the point where the designators diverge, the comparison has a
10539 // specified value if:
10540 // - we are comparing array indices
10541 // - we are comparing fields of a union, or fields with the same access
10542 // Otherwise, the result is unspecified and thus the comparison is not a
10543 // constant expression.
10544 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
10545 Mismatch < RHSDesignator.Entries.size()) {
10546 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
10547 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
10548 if (!LF && !RF)
10549 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
10550 else if (!LF)
10551 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010552 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
10553 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010554 else if (!RF)
10555 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010556 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
10557 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010558 else if (!LF->getParent()->isUnion() &&
10559 LF->getAccess() != RF->getAccess())
10560 Info.CCEDiag(E,
10561 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +000010562 << LF << LF->getAccess() << RF << RF->getAccess()
10563 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +000010564 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +000010565 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010566
10567 // The comparison here must be unsigned, and performed with the same
10568 // width as the pointer.
10569 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
10570 uint64_t CompareLHS = LHSOffset.getQuantity();
10571 uint64_t CompareRHS = RHSOffset.getQuantity();
10572 assert(PtrSize <= 64 && "Unexpected pointer width");
10573 uint64_t Mask = ~0ULL >> (64 - PtrSize);
10574 CompareLHS &= Mask;
10575 CompareRHS &= Mask;
10576
10577 // If there is a base and this is a relational operator, we can only
10578 // compare pointers within the object in question; otherwise, the result
10579 // depends on where the object is located in memory.
10580 if (!LHSValue.Base.isNull() && IsRelational) {
10581 QualType BaseTy = getType(LHSValue.Base);
10582 if (BaseTy->isIncompleteType())
10583 return Error(E);
10584 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
10585 uint64_t OffsetLimit = Size.getQuantity();
10586 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
10587 return Error(E);
10588 }
10589
10590 if (CompareLHS < CompareRHS)
10591 return Success(CCR::Less, E);
10592 if (CompareLHS > CompareRHS)
10593 return Success(CCR::Greater, E);
10594 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +000010595 }
Richard Smith7bb00672012-02-01 01:42:44 +000010596
10597 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010598 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +000010599 assert(RHSTy->isMemberPointerType() && "invalid comparison");
10600
10601 MemberPtr LHSValue, RHSValue;
10602
10603 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010604 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +000010605 return false;
10606
10607 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10608 return false;
10609
10610 // C++11 [expr.eq]p2:
10611 // If both operands are null, they compare equal. Otherwise if only one is
10612 // null, they compare unequal.
10613 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
10614 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010615 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000010616 }
10617
10618 // Otherwise if either is a pointer to a virtual member function, the
10619 // result is unspecified.
10620 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
10621 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010622 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000010623 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
10624 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010625 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +000010626
10627 // Otherwise they compare equal if and only if they would refer to the
10628 // same member of the same most derived object or the same subobject if
10629 // they were dereferenced with a hypothetical object of the associated
10630 // class type.
10631 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010632 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +000010633 }
10634
Richard Smithab44d9b2012-02-14 22:35:28 +000010635 if (LHSTy->isNullPtrType()) {
10636 assert(E->isComparisonOp() && "unexpected nullptr operation");
10637 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10638 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10639 // are compared, the result is true of the operator is <=, >= or ==, and
10640 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010641 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +000010642 }
10643
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010644 return DoAfter();
10645}
10646
10647bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10648 if (!CheckLiteralType(Info, E))
10649 return false;
10650
10651 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10652 const BinaryOperator *E) {
10653 // Evaluation succeeded. Lookup the information for the comparison category
10654 // type and fetch the VarDecl for the result.
10655 const ComparisonCategoryInfo &CmpInfo =
10656 Info.Ctx.CompCategories.getInfoForType(E->getType());
10657 const VarDecl *VD =
10658 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10659 // Check and evaluate the result as a constant expression.
10660 LValue LV;
10661 LV.set(VD);
10662 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10663 return false;
10664 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10665 };
10666 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10667 return ExprEvaluatorBaseTy::VisitBinCmp(E);
10668 });
10669}
10670
10671bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10672 // We don't call noteFailure immediately because the assignment happens after
10673 // we evaluate LHS and RHS.
10674 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10675 return Error(E);
10676
10677 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10678 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10679 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10680
10681 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10682 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010683 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +000010684
10685 if (E->isComparisonOp()) {
10686 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10687 // comparisons and then translating the result.
10688 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10689 const BinaryOperator *E) {
10690 using CCR = ComparisonCategoryResult;
10691 bool IsEqual = ResKind == CCR::Equal,
10692 IsLess = ResKind == CCR::Less,
10693 IsGreater = ResKind == CCR::Greater;
10694 auto Op = E->getOpcode();
10695 switch (Op) {
10696 default:
10697 llvm_unreachable("unsupported binary operator");
10698 case BO_EQ:
10699 case BO_NE:
10700 return Success(IsEqual == (Op == BO_EQ), E);
10701 case BO_LT: return Success(IsLess, E);
10702 case BO_GT: return Success(IsGreater, E);
10703 case BO_LE: return Success(IsEqual || IsLess, E);
10704 case BO_GE: return Success(IsEqual || IsGreater, E);
10705 }
10706 };
10707 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10708 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10709 });
10710 }
10711
10712 QualType LHSTy = E->getLHS()->getType();
10713 QualType RHSTy = E->getRHS()->getType();
10714
10715 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10716 E->getOpcode() == BO_Sub) {
10717 LValue LHSValue, RHSValue;
10718
10719 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10720 if (!LHSOK && !Info.noteFailure())
10721 return false;
10722
10723 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10724 return false;
10725
10726 // Reject differing bases from the normal codepath; we special-case
10727 // comparisons to null.
10728 if (!HasSameBase(LHSValue, RHSValue)) {
10729 // Handle &&A - &&B.
10730 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10731 return Error(E);
10732 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10733 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10734 if (!LHSExpr || !RHSExpr)
10735 return Error(E);
10736 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10737 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10738 if (!LHSAddrExpr || !RHSAddrExpr)
10739 return Error(E);
10740 // Make sure both labels come from the same function.
10741 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10742 RHSAddrExpr->getLabel()->getDeclContext())
10743 return Error(E);
10744 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10745 }
10746 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10747 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10748
10749 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10750 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10751
10752 // C++11 [expr.add]p6:
10753 // Unless both pointers point to elements of the same array object, or
10754 // one past the last element of the array object, the behavior is
10755 // undefined.
10756 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10757 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10758 RHSDesignator))
10759 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10760
10761 QualType Type = E->getLHS()->getType();
10762 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10763
10764 CharUnits ElementSize;
10765 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10766 return false;
10767
10768 // As an extension, a type may have zero size (empty struct or union in
10769 // C, array of zero length). Pointer subtraction in such cases has
10770 // undefined behavior, so is not constant.
10771 if (ElementSize.isZero()) {
10772 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10773 << ElementType;
10774 return false;
10775 }
10776
10777 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10778 // and produce incorrect results when it overflows. Such behavior
10779 // appears to be non-conforming, but is common, so perhaps we should
10780 // assume the standard intended for such cases to be undefined behavior
10781 // and check for them.
10782
10783 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10784 // overflow in the final conversion to ptrdiff_t.
10785 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10786 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10787 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10788 false);
10789 APSInt TrueResult = (LHS - RHS) / ElemSize;
10790 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
10791
10792 if (Result.extend(65) != TrueResult &&
10793 !HandleOverflow(Info, E, TrueResult, E->getType()))
10794 return false;
10795 return Success(Result, E);
10796 }
10797
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +000010798 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +000010799}
10800
Peter Collingbournee190dee2011-03-11 19:24:49 +000010801/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10802/// a result as the expression's type.
10803bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10804 const UnaryExprOrTypeTraitExpr *E) {
10805 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +000010806 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +000010807 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +000010808 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +000010809 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10810 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000010811 else
Richard Smith6822bd72018-10-26 19:26:45 +000010812 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10813 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +000010814 }
Eli Friedman64004332009-03-23 04:38:34 +000010815
Peter Collingbournee190dee2011-03-11 19:24:49 +000010816 case UETT_VecStep: {
10817 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +000010818
Peter Collingbournee190dee2011-03-11 19:24:49 +000010819 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +000010820 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +000010821
Peter Collingbournee190dee2011-03-11 19:24:49 +000010822 // The vec_step built-in functions that take a 3-component
10823 // vector return 4. (OpenCL 1.1 spec 6.11.12)
10824 if (n == 3)
10825 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +000010826
Peter Collingbournee190dee2011-03-11 19:24:49 +000010827 return Success(n, E);
10828 } else
10829 return Success(1, E);
10830 }
10831
10832 case UETT_SizeOf: {
10833 QualType SrcTy = E->getTypeOfArgument();
10834 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10835 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +000010836 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10837 SrcTy = Ref->getPointeeType();
10838
Richard Smithd62306a2011-11-10 06:34:14 +000010839 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +000010840 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +000010841 return false;
Richard Smithd62306a2011-11-10 06:34:14 +000010842 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000010843 }
Alexey Bataev00396512015-07-02 03:40:19 +000010844 case UETT_OpenMPRequiredSimdAlign:
10845 assert(E->isArgumentType());
10846 return Success(
10847 Info.Ctx.toCharUnitsFromBits(
10848 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10849 .getQuantity(),
10850 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +000010851 }
10852
10853 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +000010854}
10855
Peter Collingbournee9200682011-05-13 03:29:01 +000010856bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +000010857 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +000010858 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +000010859 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010860 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +000010861 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +000010862 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +000010863 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +000010864 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +000010865 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +000010866 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +000010867 APSInt IdxResult;
10868 if (!EvaluateInteger(Idx, IdxResult, Info))
10869 return false;
10870 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10871 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010872 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010873 CurrentType = AT->getElementType();
10874 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10875 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +000010876 break;
Douglas Gregor882211c2010-04-28 22:16:22 +000010877 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010878
James Y Knight7281c352015-12-29 22:31:18 +000010879 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +000010880 FieldDecl *MemberDecl = ON.getField();
10881 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000010882 if (!RT)
10883 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010884 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000010885 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +000010886 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +000010887 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +000010888 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +000010889 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +000010890 CurrentType = MemberDecl->getType().getNonReferenceType();
10891 break;
10892 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010893
James Y Knight7281c352015-12-29 22:31:18 +000010894 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +000010895 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +000010896
James Y Knight7281c352015-12-29 22:31:18 +000010897 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +000010898 CXXBaseSpecifier *BaseSpec = ON.getBase();
10899 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +000010900 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000010901
10902 // Find the layout of the class whose base we are looking into.
10903 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +000010904 if (!RT)
10905 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +000010906 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +000010907 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +000010908 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10909
10910 // Find the base class itself.
10911 CurrentType = BaseSpec->getType();
10912 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10913 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010914 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +000010915
Douglas Gregord1702062010-04-29 00:18:15 +000010916 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +000010917 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +000010918 break;
10919 }
Douglas Gregor882211c2010-04-28 22:16:22 +000010920 }
10921 }
Peter Collingbournee9200682011-05-13 03:29:01 +000010922 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +000010923}
10924
Chris Lattnere13042c2008-07-11 19:10:17 +000010925bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010926 switch (E->getOpcode()) {
10927 default:
10928 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
10929 // See C99 6.6p3.
10930 return Error(E);
10931 case UO_Extension:
10932 // FIXME: Should extension allow i-c-e extension expressions in its scope?
10933 // If so, we could clear the diagnostic ID.
10934 return Visit(E->getSubExpr());
10935 case UO_Plus:
10936 // The result is just the value.
10937 return Visit(E->getSubExpr());
10938 case UO_Minus: {
10939 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +000010940 return false;
10941 if (!Result.isInt()) return Error(E);
10942 const APSInt &Value = Result.getInt();
10943 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
10944 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
10945 E->getType()))
10946 return false;
Richard Smithfe800032012-01-31 04:08:20 +000010947 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010948 }
10949 case UO_Not: {
10950 if (!Visit(E->getSubExpr()))
10951 return false;
10952 if (!Result.isInt()) return Error(E);
10953 return Success(~Result.getInt(), E);
10954 }
10955 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +000010956 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +000010957 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +000010958 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +000010959 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +000010960 }
Anders Carlsson9c181652008-07-08 14:35:21 +000010961 }
Anders Carlsson9c181652008-07-08 14:35:21 +000010962}
Mike Stump11289f42009-09-09 15:08:12 +000010963
Chris Lattner477c4be2008-07-12 01:15:53 +000010964/// HandleCast - This is used to evaluate implicit or explicit casts where the
10965/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +000010966bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
10967 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000010968 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +000010969 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +000010970
Eli Friedmanc757de22011-03-25 00:43:55 +000010971 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +000010972 case CK_BaseToDerived:
10973 case CK_DerivedToBase:
10974 case CK_UncheckedDerivedToBase:
10975 case CK_Dynamic:
10976 case CK_ToUnion:
10977 case CK_ArrayToPointerDecay:
10978 case CK_FunctionToPointerDecay:
10979 case CK_NullToPointer:
10980 case CK_NullToMemberPointer:
10981 case CK_BaseToDerivedMemberPointer:
10982 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +000010983 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +000010984 case CK_ConstructorConversion:
10985 case CK_IntegralToPointer:
10986 case CK_ToVoid:
10987 case CK_VectorSplat:
10988 case CK_IntegralToFloating:
10989 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000010990 case CK_CPointerToObjCPointerCast:
10991 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000010992 case CK_AnyPointerToBlockPointerCast:
10993 case CK_ObjCObjectLValueCast:
10994 case CK_FloatingRealToComplex:
10995 case CK_FloatingComplexToReal:
10996 case CK_FloatingComplexCast:
10997 case CK_FloatingComplexToIntegralComplex:
10998 case CK_IntegralRealToComplex:
10999 case CK_IntegralComplexCast:
11000 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +000011001 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000011002 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000011003 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000011004 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000011005 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000011006 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +000011007 case CK_IntegralToFixedPoint:
Eli Friedmanc757de22011-03-25 00:43:55 +000011008 llvm_unreachable("invalid cast kind for integral value");
11009
Eli Friedman9faf2f92011-03-25 19:07:11 +000011010 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +000011011 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000011012 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +000011013 case CK_ARCProduceObject:
11014 case CK_ARCConsumeObject:
11015 case CK_ARCReclaimReturnedObject:
11016 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000011017 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011018 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011019
Richard Smith4ef685b2012-01-17 21:17:26 +000011020 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +000011021 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011022 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +000011023 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000011024 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000011025 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011026
11027 case CK_MemberPointerToBoolean:
11028 case CK_PointerToBoolean:
11029 case CK_IntegralToBoolean:
11030 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +000011031 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +000011032 case CK_FloatingComplexToBoolean:
11033 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011034 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +000011035 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +000011036 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +000011037 uint64_t IntResult = BoolResult;
11038 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
11039 IntResult = (uint64_t)-1;
11040 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +000011041 }
11042
Leonard Chan8f7caae2019-03-06 00:28:43 +000011043 case CK_FixedPointToIntegral: {
11044 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
11045 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11046 return false;
11047 bool Overflowed;
11048 llvm::APSInt Result = Src.convertToInt(
11049 Info.Ctx.getIntWidth(DestType),
11050 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
11051 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11052 return false;
11053 return Success(Result, E);
11054 }
11055
Leonard Chanb4ba4672018-10-23 17:55:35 +000011056 case CK_FixedPointToBoolean: {
11057 // Unsigned padding does not affect this.
11058 APValue Val;
11059 if (!Evaluate(Val, Info, SubExpr))
11060 return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000011061 return Success(Val.getFixedPoint().getBoolValue(), E);
Leonard Chanb4ba4672018-10-23 17:55:35 +000011062 }
11063
Eli Friedmanc757de22011-03-25 00:43:55 +000011064 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +000011065 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +000011066 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +000011067
Eli Friedman742421e2009-02-20 01:15:07 +000011068 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +000011069 // Allow casts of address-of-label differences if they are no-ops
11070 // or narrowing. (The narrowing case isn't actually guaranteed to
11071 // be constant-evaluatable except in some narrow cases which are hard
11072 // to detect here. We let it through on the assumption the user knows
11073 // what they are doing.)
11074 if (Result.isAddrLabelDiff())
11075 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +000011076 // Only allow casts of lvalues if they are lossless.
11077 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
11078 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +000011079
Richard Smith911e1422012-01-30 22:27:01 +000011080 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
11081 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +000011082 }
Mike Stump11289f42009-09-09 15:08:12 +000011083
Eli Friedmanc757de22011-03-25 00:43:55 +000011084 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +000011085 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
11086
John McCall45d55e42010-05-07 21:00:08 +000011087 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +000011088 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +000011089 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +000011090
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011091 if (LV.getLValueBase()) {
11092 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +000011093 // FIXME: Allow a larger integer size than the pointer size, and allow
11094 // narrowing back down to pointer width in subsequent integral casts.
11095 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011096 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011097 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +000011098
Richard Smithcf74da72011-11-16 07:18:12 +000011099 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +000011100 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000011101 return true;
11102 }
11103
Hans Wennborgdd1ea8a2019-03-06 10:26:19 +000011104 APSInt AsInt;
11105 APValue V;
11106 LV.moveInto(V);
11107 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
11108 llvm_unreachable("Can't cast this!");
Yaxun Liu402804b2016-12-15 08:09:08 +000011109
Richard Smith911e1422012-01-30 22:27:01 +000011110 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +000011111 }
Eli Friedman9a156e52008-11-12 09:44:48 +000011112
Eli Friedmanc757de22011-03-25 00:43:55 +000011113 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +000011114 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000011115 if (!EvaluateComplex(SubExpr, C, Info))
11116 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +000011117 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000011118 }
Eli Friedmanc2b50172009-02-22 11:46:18 +000011119
Eli Friedmanc757de22011-03-25 00:43:55 +000011120 case CK_FloatingToIntegral: {
11121 APFloat F(0.0);
11122 if (!EvaluateFloat(SubExpr, F, Info))
11123 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +000011124
Richard Smith357362d2011-12-13 06:39:58 +000011125 APSInt Value;
11126 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
11127 return false;
11128 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +000011129 }
11130 }
Mike Stump11289f42009-09-09 15:08:12 +000011131
Eli Friedmanc757de22011-03-25 00:43:55 +000011132 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +000011133}
Anders Carlssonb5ad0212008-07-08 14:30:00 +000011134
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011135bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11136 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011137 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011138 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11139 return false;
11140 if (!LV.isComplexInt())
11141 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011142 return Success(LV.getComplexIntReal(), E);
11143 }
11144
11145 return Visit(E->getSubExpr());
11146}
11147
Eli Friedman4e7a2412009-02-27 04:45:43 +000011148bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011149 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +000011150 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011151 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11152 return false;
11153 if (!LV.isComplexInt())
11154 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000011155 return Success(LV.getComplexIntImag(), E);
11156 }
11157
Richard Smith4a678122011-10-24 18:44:57 +000011158 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +000011159 return Success(0, E);
11160}
11161
Douglas Gregor820ba7b2011-01-04 17:33:58 +000011162bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
11163 return Success(E->getPackLength(), E);
11164}
11165
Sebastian Redl5f0180d2010-09-10 20:55:47 +000011166bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
11167 return Success(E->getValue(), E);
11168}
11169
Leonard Chandb01c3a2018-06-20 17:19:40 +000011170bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11171 switch (E->getOpcode()) {
11172 default:
11173 // Invalid unary operators
11174 return Error(E);
11175 case UO_Plus:
11176 // The result is just the value.
11177 return Visit(E->getSubExpr());
11178 case UO_Minus: {
11179 if (!Visit(E->getSubExpr())) return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000011180 if (!Result.isFixedPoint())
11181 return Error(E);
11182 bool Overflowed;
11183 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
11184 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
11185 return false;
11186 return Success(Negated, E);
Leonard Chandb01c3a2018-06-20 17:19:40 +000011187 }
11188 case UO_LNot: {
11189 bool bres;
11190 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11191 return false;
11192 return Success(!bres, E);
11193 }
11194 }
11195}
11196
Leonard Chand3f3e162019-01-18 21:04:25 +000011197bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
11198 const Expr *SubExpr = E->getSubExpr();
11199 QualType DestType = E->getType();
11200 assert(DestType->isFixedPointType() &&
11201 "Expected destination type to be a fixed point type");
11202 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
11203
11204 switch (E->getCastKind()) {
11205 case CK_FixedPointCast: {
11206 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
11207 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11208 return false;
11209 bool Overflowed;
11210 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
11211 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11212 return false;
11213 return Success(Result, E);
11214 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000011215 case CK_IntegralToFixedPoint: {
11216 APSInt Src;
11217 if (!EvaluateInteger(SubExpr, Src, Info))
11218 return false;
11219
11220 bool Overflowed;
11221 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11222 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
11223
11224 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
11225 return false;
11226
11227 return Success(IntResult, E);
11228 }
Leonard Chand3f3e162019-01-18 21:04:25 +000011229 case CK_NoOp:
11230 case CK_LValueToRValue:
11231 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11232 default:
11233 return Error(E);
11234 }
11235}
11236
11237bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11238 const Expr *LHS = E->getLHS();
11239 const Expr *RHS = E->getRHS();
11240 FixedPointSemantics ResultFXSema =
11241 Info.Ctx.getFixedPointSemantics(E->getType());
11242
11243 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
11244 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
11245 return false;
11246 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
11247 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
11248 return false;
11249
11250 switch (E->getOpcode()) {
11251 case BO_Add: {
11252 bool AddOverflow, ConversionOverflow;
11253 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
11254 .convert(ResultFXSema, &ConversionOverflow);
11255 if ((AddOverflow || ConversionOverflow) &&
11256 !HandleOverflow(Info, E, Result, E->getType()))
11257 return false;
11258 return Success(Result, E);
11259 }
11260 default:
11261 return false;
11262 }
11263 llvm_unreachable("Should've exited before this");
11264}
11265
Chris Lattner05706e882008-07-11 18:11:29 +000011266//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +000011267// Float Evaluation
11268//===----------------------------------------------------------------------===//
11269
11270namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000011271class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000011272 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +000011273 APFloat &Result;
11274public:
11275 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +000011276 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +000011277
Richard Smith2e312c82012-03-03 22:46:17 +000011278 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011279 Result = V.getFloat();
11280 return true;
11281 }
Eli Friedman24c01542008-08-22 00:06:13 +000011282
Richard Smithfddd3842011-12-30 21:15:51 +000011283 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +000011284 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
11285 return true;
11286 }
11287
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011288 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +000011289
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011290 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +000011291 bool VisitBinaryOperator(const BinaryOperator *E);
11292 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000011293 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +000011294
John McCallb1fb0d32010-05-07 22:08:54 +000011295 bool VisitUnaryReal(const UnaryOperator *E);
11296 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +000011297
Richard Smithfddd3842011-12-30 21:15:51 +000011298 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +000011299};
11300} // end anonymous namespace
11301
11302static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000011303 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +000011304 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +000011305}
11306
Jay Foad39c79802011-01-12 09:06:06 +000011307static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +000011308 QualType ResultTy,
11309 const Expr *Arg,
11310 bool SNaN,
11311 llvm::APFloat &Result) {
11312 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
11313 if (!S) return false;
11314
11315 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
11316
11317 llvm::APInt fill;
11318
11319 // Treat empty strings as if they were zero.
11320 if (S->getString().empty())
11321 fill = llvm::APInt(32, 0);
11322 else if (S->getString().getAsInteger(0, fill))
11323 return false;
11324
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +000011325 if (Context.getTargetInfo().isNan2008()) {
11326 if (SNaN)
11327 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11328 else
11329 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11330 } else {
11331 // Prior to IEEE 754-2008, architectures were allowed to choose whether
11332 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
11333 // a different encoding to what became a standard in 2008, and for pre-
11334 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
11335 // sNaN. This is now known as "legacy NaN" encoding.
11336 if (SNaN)
11337 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11338 else
11339 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11340 }
11341
John McCall16291492010-02-28 13:00:19 +000011342 return true;
11343}
11344
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011345bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000011346 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011347 default:
11348 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11349
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011350 case Builtin::BI__builtin_huge_val:
11351 case Builtin::BI__builtin_huge_valf:
11352 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011353 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011354 case Builtin::BI__builtin_inf:
11355 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011356 case Builtin::BI__builtin_infl:
11357 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000011358 const llvm::fltSemantics &Sem =
11359 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000011360 Result = llvm::APFloat::getInf(Sem);
11361 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000011362 }
Mike Stump11289f42009-09-09 15:08:12 +000011363
John McCall16291492010-02-28 13:00:19 +000011364 case Builtin::BI__builtin_nans:
11365 case Builtin::BI__builtin_nansf:
11366 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011367 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011368 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11369 true, Result))
11370 return Error(E);
11371 return true;
John McCall16291492010-02-28 13:00:19 +000011372
Chris Lattner0b7282e2008-10-06 06:31:58 +000011373 case Builtin::BI__builtin_nan:
11374 case Builtin::BI__builtin_nanf:
11375 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011376 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000011377 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000011378 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000011379 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11380 false, Result))
11381 return Error(E);
11382 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011383
11384 case Builtin::BI__builtin_fabs:
11385 case Builtin::BI__builtin_fabsf:
11386 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011387 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011388 if (!EvaluateFloat(E->getArg(0), Result, Info))
11389 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011390
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011391 if (Result.isNegative())
11392 Result.changeSign();
11393 return true;
11394
Richard Smith8889a3d2013-06-13 06:26:32 +000011395 // FIXME: Builtin::BI__builtin_powi
11396 // FIXME: Builtin::BI__builtin_powif
11397 // FIXME: Builtin::BI__builtin_powil
11398
Mike Stump11289f42009-09-09 15:08:12 +000011399 case Builtin::BI__builtin_copysign:
11400 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000011401 case Builtin::BI__builtin_copysignl:
11402 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011403 APFloat RHS(0.);
11404 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
11405 !EvaluateFloat(E->getArg(1), RHS, Info))
11406 return false;
11407 Result.copySign(RHS);
11408 return true;
11409 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011410 }
11411}
11412
John McCallb1fb0d32010-05-07 22:08:54 +000011413bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000011414 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11415 ComplexValue CV;
11416 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11417 return false;
11418 Result = CV.FloatReal;
11419 return true;
11420 }
11421
11422 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000011423}
11424
11425bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000011426 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11427 ComplexValue CV;
11428 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11429 return false;
11430 Result = CV.FloatImag;
11431 return true;
11432 }
11433
Richard Smith4a678122011-10-24 18:44:57 +000011434 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000011435 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
11436 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000011437 return true;
11438}
11439
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011440bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011441 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011442 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000011443 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000011444 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000011445 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000011446 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
11447 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011448 Result.changeSign();
11449 return true;
11450 }
11451}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000011452
Eli Friedman24c01542008-08-22 00:06:13 +000011453bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000011454 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11455 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000011456
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000011457 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000011458 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000011459 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000011460 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000011461 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
11462 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000011463}
11464
11465bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
11466 Result = E->getValue();
11467 return true;
11468}
11469
Peter Collingbournee9200682011-05-13 03:29:01 +000011470bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
11471 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000011472
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011473 switch (E->getCastKind()) {
11474 default:
Richard Smith11562c52011-10-28 17:51:58 +000011475 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011476
11477 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011478 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000011479 return EvaluateInteger(SubExpr, IntResult, Info) &&
11480 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
11481 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000011482 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011483
11484 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000011485 if (!Visit(SubExpr))
11486 return false;
Richard Smith357362d2011-12-13 06:39:58 +000011487 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
11488 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000011489 }
John McCalld7646252010-11-14 08:17:51 +000011490
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011491 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000011492 ComplexValue V;
11493 if (!EvaluateComplex(SubExpr, V, Info))
11494 return false;
11495 Result = V.getComplexFloatReal();
11496 return true;
11497 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000011498 }
Eli Friedman9a156e52008-11-12 09:44:48 +000011499}
11500
Eli Friedman24c01542008-08-22 00:06:13 +000011501//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011502// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000011503//===----------------------------------------------------------------------===//
11504
11505namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000011506class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000011507 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000011508 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000011509
Anders Carlsson537969c2008-11-16 20:27:53 +000011510public:
John McCall93d91dc2010-05-07 17:22:02 +000011511 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000011512 : ExprEvaluatorBaseTy(info), Result(Result) {}
11513
Richard Smith2e312c82012-03-03 22:46:17 +000011514 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000011515 Result.setFrom(V);
11516 return true;
11517 }
Mike Stump11289f42009-09-09 15:08:12 +000011518
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011519 bool ZeroInitialization(const Expr *E);
11520
Anders Carlsson537969c2008-11-16 20:27:53 +000011521 //===--------------------------------------------------------------------===//
11522 // Visitor Methods
11523 //===--------------------------------------------------------------------===//
11524
Peter Collingbournee9200682011-05-13 03:29:01 +000011525 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000011526 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000011527 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011528 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011529 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000011530};
11531} // end anonymous namespace
11532
John McCall93d91dc2010-05-07 17:22:02 +000011533static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
11534 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000011535 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000011536 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000011537}
11538
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011539bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000011540 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011541 if (ElemTy->isRealFloatingType()) {
11542 Result.makeComplexFloat();
11543 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
11544 Result.FloatReal = Zero;
11545 Result.FloatImag = Zero;
11546 } else {
11547 Result.makeComplexInt();
11548 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
11549 Result.IntReal = Zero;
11550 Result.IntImag = Zero;
11551 }
11552 return true;
11553}
11554
Peter Collingbournee9200682011-05-13 03:29:01 +000011555bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
11556 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011557
11558 if (SubExpr->getType()->isRealFloatingType()) {
11559 Result.makeComplexFloat();
11560 APFloat &Imag = Result.FloatImag;
11561 if (!EvaluateFloat(SubExpr, Imag, Info))
11562 return false;
11563
11564 Result.FloatReal = APFloat(Imag.getSemantics());
11565 return true;
11566 } else {
11567 assert(SubExpr->getType()->isIntegerType() &&
11568 "Unexpected imaginary literal.");
11569
11570 Result.makeComplexInt();
11571 APSInt &Imag = Result.IntImag;
11572 if (!EvaluateInteger(SubExpr, Imag, Info))
11573 return false;
11574
11575 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
11576 return true;
11577 }
11578}
11579
Peter Collingbournee9200682011-05-13 03:29:01 +000011580bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011581
John McCallfcef3cf2010-12-14 17:51:41 +000011582 switch (E->getCastKind()) {
11583 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011584 case CK_BaseToDerived:
11585 case CK_DerivedToBase:
11586 case CK_UncheckedDerivedToBase:
11587 case CK_Dynamic:
11588 case CK_ToUnion:
11589 case CK_ArrayToPointerDecay:
11590 case CK_FunctionToPointerDecay:
11591 case CK_NullToPointer:
11592 case CK_NullToMemberPointer:
11593 case CK_BaseToDerivedMemberPointer:
11594 case CK_DerivedToBaseMemberPointer:
11595 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000011596 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000011597 case CK_ConstructorConversion:
11598 case CK_IntegralToPointer:
11599 case CK_PointerToIntegral:
11600 case CK_PointerToBoolean:
11601 case CK_ToVoid:
11602 case CK_VectorSplat:
11603 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000011604 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000011605 case CK_IntegralToBoolean:
11606 case CK_IntegralToFloating:
11607 case CK_FloatingToIntegral:
11608 case CK_FloatingToBoolean:
11609 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000011610 case CK_CPointerToObjCPointerCast:
11611 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011612 case CK_AnyPointerToBlockPointerCast:
11613 case CK_ObjCObjectLValueCast:
11614 case CK_FloatingComplexToReal:
11615 case CK_FloatingComplexToBoolean:
11616 case CK_IntegralComplexToReal:
11617 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000011618 case CK_ARCProduceObject:
11619 case CK_ARCConsumeObject:
11620 case CK_ARCReclaimReturnedObject:
11621 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000011622 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000011623 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000011624 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000011625 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000011626 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000011627 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000011628 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000011629 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +000011630 case CK_FixedPointToIntegral:
11631 case CK_IntegralToFixedPoint:
John McCallfcef3cf2010-12-14 17:51:41 +000011632 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000011633
John McCallfcef3cf2010-12-14 17:51:41 +000011634 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011635 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000011636 case CK_NoOp:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000011637 case CK_LValueToRValueBitCast:
Richard Smith11562c52011-10-28 17:51:58 +000011638 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000011639
11640 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000011641 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000011642 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011643 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000011644
11645 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011646 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000011647 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011648 return false;
11649
John McCallfcef3cf2010-12-14 17:51:41 +000011650 Result.makeComplexFloat();
11651 Result.FloatImag = APFloat(Real.getSemantics());
11652 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011653 }
11654
John McCallfcef3cf2010-12-14 17:51:41 +000011655 case CK_FloatingComplexCast: {
11656 if (!Visit(E->getSubExpr()))
11657 return false;
11658
11659 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11660 QualType From
11661 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11662
Richard Smith357362d2011-12-13 06:39:58 +000011663 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11664 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011665 }
11666
11667 case CK_FloatingComplexToIntegralComplex: {
11668 if (!Visit(E->getSubExpr()))
11669 return false;
11670
11671 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11672 QualType From
11673 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11674 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000011675 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11676 To, Result.IntReal) &&
11677 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11678 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011679 }
11680
11681 case CK_IntegralRealToComplex: {
11682 APSInt &Real = Result.IntReal;
11683 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11684 return false;
11685
11686 Result.makeComplexInt();
11687 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11688 return true;
11689 }
11690
11691 case CK_IntegralComplexCast: {
11692 if (!Visit(E->getSubExpr()))
11693 return false;
11694
11695 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11696 QualType From
11697 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11698
Richard Smith911e1422012-01-30 22:27:01 +000011699 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11700 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011701 return true;
11702 }
11703
11704 case CK_IntegralComplexToFloatingComplex: {
11705 if (!Visit(E->getSubExpr()))
11706 return false;
11707
Ted Kremenek28831752012-08-23 20:46:57 +000011708 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000011709 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000011710 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000011711 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000011712 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11713 To, Result.FloatReal) &&
11714 HandleIntToFloatCast(Info, E, From, Result.IntImag,
11715 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000011716 }
11717 }
11718
11719 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000011720}
11721
John McCall93d91dc2010-05-07 17:22:02 +000011722bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000011723 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000011724 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11725
Chandler Carrutha216cad2014-10-11 00:57:18 +000011726 // Track whether the LHS or RHS is real at the type system level. When this is
11727 // the case we can simplify our evaluation strategy.
11728 bool LHSReal = false, RHSReal = false;
11729
11730 bool LHSOK;
11731 if (E->getLHS()->getType()->isRealFloatingType()) {
11732 LHSReal = true;
11733 APFloat &Real = Result.FloatReal;
11734 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11735 if (LHSOK) {
11736 Result.makeComplexFloat();
11737 Result.FloatImag = APFloat(Real.getSemantics());
11738 }
11739 } else {
11740 LHSOK = Visit(E->getLHS());
11741 }
George Burgess IVa145e252016-05-25 22:38:36 +000011742 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000011743 return false;
Mike Stump11289f42009-09-09 15:08:12 +000011744
John McCall93d91dc2010-05-07 17:22:02 +000011745 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011746 if (E->getRHS()->getType()->isRealFloatingType()) {
11747 RHSReal = true;
11748 APFloat &Real = RHS.FloatReal;
11749 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11750 return false;
11751 RHS.makeComplexFloat();
11752 RHS.FloatImag = APFloat(Real.getSemantics());
11753 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000011754 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011755
Chandler Carrutha216cad2014-10-11 00:57:18 +000011756 assert(!(LHSReal && RHSReal) &&
11757 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011758 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011759 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000011760 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011761 if (Result.isComplexFloat()) {
11762 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11763 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011764 if (LHSReal)
11765 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11766 else if (!RHSReal)
11767 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11768 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011769 } else {
11770 Result.getComplexIntReal() += RHS.getComplexIntReal();
11771 Result.getComplexIntImag() += RHS.getComplexIntImag();
11772 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011773 break;
John McCalle3027922010-08-25 11:45:40 +000011774 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011775 if (Result.isComplexFloat()) {
11776 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11777 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011778 if (LHSReal) {
11779 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11780 Result.getComplexFloatImag().changeSign();
11781 } else if (!RHSReal) {
11782 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11783 APFloat::rmNearestTiesToEven);
11784 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000011785 } else {
11786 Result.getComplexIntReal() -= RHS.getComplexIntReal();
11787 Result.getComplexIntImag() -= RHS.getComplexIntImag();
11788 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011789 break;
John McCalle3027922010-08-25 11:45:40 +000011790 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011791 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000011792 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000011793 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000011794 // following naming scheme:
11795 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000011796 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011797 APFloat &A = LHS.getComplexFloatReal();
11798 APFloat &B = LHS.getComplexFloatImag();
11799 APFloat &C = RHS.getComplexFloatReal();
11800 APFloat &D = RHS.getComplexFloatImag();
11801 APFloat &ResR = Result.getComplexFloatReal();
11802 APFloat &ResI = Result.getComplexFloatImag();
11803 if (LHSReal) {
11804 assert(!RHSReal && "Cannot have two real operands for a complex op!");
11805 ResR = A * C;
11806 ResI = A * D;
11807 } else if (RHSReal) {
11808 ResR = C * A;
11809 ResI = C * B;
11810 } else {
11811 // In the fully general case, we need to handle NaNs and infinities
11812 // robustly.
11813 APFloat AC = A * C;
11814 APFloat BD = B * D;
11815 APFloat AD = A * D;
11816 APFloat BC = B * C;
11817 ResR = AC - BD;
11818 ResI = AD + BC;
11819 if (ResR.isNaN() && ResI.isNaN()) {
11820 bool Recalc = false;
11821 if (A.isInfinity() || B.isInfinity()) {
11822 A = APFloat::copySign(
11823 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11824 B = APFloat::copySign(
11825 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11826 if (C.isNaN())
11827 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11828 if (D.isNaN())
11829 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11830 Recalc = true;
11831 }
11832 if (C.isInfinity() || D.isInfinity()) {
11833 C = APFloat::copySign(
11834 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11835 D = APFloat::copySign(
11836 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11837 if (A.isNaN())
11838 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11839 if (B.isNaN())
11840 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11841 Recalc = true;
11842 }
11843 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11844 AD.isInfinity() || BC.isInfinity())) {
11845 if (A.isNaN())
11846 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11847 if (B.isNaN())
11848 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11849 if (C.isNaN())
11850 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11851 if (D.isNaN())
11852 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11853 Recalc = true;
11854 }
11855 if (Recalc) {
11856 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11857 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11858 }
11859 }
11860 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011861 } else {
John McCall93d91dc2010-05-07 17:22:02 +000011862 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000011863 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011864 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11865 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000011866 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000011867 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11868 LHS.getComplexIntImag() * RHS.getComplexIntReal());
11869 }
11870 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011871 case BO_Div:
11872 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000011873 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000011874 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000011875 // following naming scheme:
11876 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011877 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000011878 APFloat &A = LHS.getComplexFloatReal();
11879 APFloat &B = LHS.getComplexFloatImag();
11880 APFloat &C = RHS.getComplexFloatReal();
11881 APFloat &D = RHS.getComplexFloatImag();
11882 APFloat &ResR = Result.getComplexFloatReal();
11883 APFloat &ResI = Result.getComplexFloatImag();
11884 if (RHSReal) {
11885 ResR = A / C;
11886 ResI = B / C;
11887 } else {
11888 if (LHSReal) {
11889 // No real optimizations we can do here, stub out with zero.
11890 B = APFloat::getZero(A.getSemantics());
11891 }
11892 int DenomLogB = 0;
11893 APFloat MaxCD = maxnum(abs(C), abs(D));
11894 if (MaxCD.isFinite()) {
11895 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000011896 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11897 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011898 }
11899 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000011900 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11901 APFloat::rmNearestTiesToEven);
11902 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11903 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000011904 if (ResR.isNaN() && ResI.isNaN()) {
11905 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11906 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11907 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11908 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11909 D.isFinite()) {
11910 A = APFloat::copySign(
11911 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11912 B = APFloat::copySign(
11913 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11914 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11915 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11916 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11917 C = APFloat::copySign(
11918 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11919 D = APFloat::copySign(
11920 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11921 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
11922 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
11923 }
11924 }
11925 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011926 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011927 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
11928 return Error(E, diag::note_expr_divide_by_zero);
11929
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011930 ComplexValue LHS = Result;
11931 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
11932 RHS.getComplexIntImag() * RHS.getComplexIntImag();
11933 Result.getComplexIntReal() =
11934 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
11935 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
11936 Result.getComplexIntImag() =
11937 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
11938 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
11939 }
11940 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011941 }
11942
John McCall93d91dc2010-05-07 17:22:02 +000011943 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000011944}
11945
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011946bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11947 // Get the operand value into 'Result'.
11948 if (!Visit(E->getSubExpr()))
11949 return false;
11950
11951 switch (E->getOpcode()) {
11952 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000011953 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000011954 case UO_Extension:
11955 return true;
11956 case UO_Plus:
11957 // The result is always just the subexpr.
11958 return true;
11959 case UO_Minus:
11960 if (Result.isComplexFloat()) {
11961 Result.getComplexFloatReal().changeSign();
11962 Result.getComplexFloatImag().changeSign();
11963 }
11964 else {
11965 Result.getComplexIntReal() = -Result.getComplexIntReal();
11966 Result.getComplexIntImag() = -Result.getComplexIntImag();
11967 }
11968 return true;
11969 case UO_Not:
11970 if (Result.isComplexFloat())
11971 Result.getComplexFloatImag().changeSign();
11972 else
11973 Result.getComplexIntImag() = -Result.getComplexIntImag();
11974 return true;
11975 }
11976}
11977
Eli Friedmanc4b251d2012-01-10 04:58:17 +000011978bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11979 if (E->getNumInits() == 2) {
11980 if (E->getType()->isComplexType()) {
11981 Result.makeComplexFloat();
11982 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
11983 return false;
11984 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
11985 return false;
11986 } else {
11987 Result.makeComplexInt();
11988 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
11989 return false;
11990 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
11991 return false;
11992 }
11993 return true;
11994 }
11995 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
11996}
11997
Anders Carlsson537969c2008-11-16 20:27:53 +000011998//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000011999// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
12000// implicit conversion.
12001//===----------------------------------------------------------------------===//
12002
12003namespace {
12004class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000012005 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000012006 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000012007 APValue &Result;
12008public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000012009 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
12010 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000012011
12012 bool Success(const APValue &V, const Expr *E) {
12013 Result = V;
12014 return true;
12015 }
12016
12017 bool ZeroInitialization(const Expr *E) {
12018 ImplicitValueInitExpr VIE(
12019 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000012020 // For atomic-qualified class (and array) types in C++, initialize the
12021 // _Atomic-wrapped subobject directly, in-place.
12022 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
12023 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000012024 }
12025
12026 bool VisitCastExpr(const CastExpr *E) {
12027 switch (E->getCastKind()) {
12028 default:
12029 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12030 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000012031 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
12032 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000012033 }
12034 }
12035};
12036} // end anonymous namespace
12037
Richard Smith64cb9ca2017-02-22 22:09:50 +000012038static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
12039 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000012040 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000012041 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000012042}
12043
12044//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000012045// Void expression evaluation, primarily for a cast to void on the LHS of a
12046// comma operator
12047//===----------------------------------------------------------------------===//
12048
12049namespace {
12050class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000012051 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000012052public:
12053 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
12054
Richard Smith2e312c82012-03-03 22:46:17 +000012055 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000012056
Richard Smith7cd577b2017-08-17 19:35:50 +000012057 bool ZeroInitialization(const Expr *E) { return true; }
12058
Richard Smith42d3af92011-12-07 00:43:50 +000012059 bool VisitCastExpr(const CastExpr *E) {
12060 switch (E->getCastKind()) {
12061 default:
12062 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12063 case CK_ToVoid:
12064 VisitIgnoredValue(E->getSubExpr());
12065 return true;
12066 }
12067 }
Hal Finkela8443c32014-07-17 14:49:58 +000012068
12069 bool VisitCallExpr(const CallExpr *E) {
12070 switch (E->getBuiltinCallee()) {
12071 default:
12072 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12073 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000012074 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000012075 // The argument is not evaluated!
12076 return true;
12077 }
12078 }
Richard Smith42d3af92011-12-07 00:43:50 +000012079};
12080} // end anonymous namespace
12081
12082static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
12083 assert(E->isRValue() && E->getType()->isVoidType());
12084 return VoidExprEvaluator(Info).Visit(E);
12085}
12086
12087//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000012088// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000012089//===----------------------------------------------------------------------===//
12090
Richard Smith2e312c82012-03-03 22:46:17 +000012091static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000012092 // In C, function designators are not lvalues, but we evaluate them as if they
12093 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000012094 QualType T = E->getType();
12095 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000012096 LValue LV;
12097 if (!EvaluateLValue(E, LV, Info))
12098 return false;
12099 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000012100 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000012101 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000012102 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012103 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000012104 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012105 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012106 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000012107 LValue LV;
12108 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012109 return false;
Richard Smith725810a2011-10-16 21:26:27 +000012110 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000012111 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000012112 llvm::APFloat F(0.0);
12113 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012114 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000012115 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000012116 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000012117 ComplexValue C;
12118 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012119 return false;
Richard Smith725810a2011-10-16 21:26:27 +000012120 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000012121 } else if (T->isFixedPointType()) {
12122 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012123 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000012124 MemberPtr P;
12125 if (!EvaluateMemberPointer(E, P, Info))
12126 return false;
12127 P.moveInto(Result);
12128 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000012129 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000012130 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000012131 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000012132 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000012133 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000012134 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000012135 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000012136 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000012137 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000012138 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000012139 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000012140 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000012141 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012142 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000012143 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000012144 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000012145 if (!EvaluateVoid(E, Info))
12146 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000012147 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000012148 QualType Unqual = T.getAtomicUnqualifiedType();
12149 if (Unqual->isArrayType() || Unqual->isRecordType()) {
12150 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000012151 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012152 if (!EvaluateAtomic(E, &LV, Value, Info))
12153 return false;
12154 } else {
12155 if (!EvaluateAtomic(E, nullptr, Result, Info))
12156 return false;
12157 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012158 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000012159 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000012160 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012161 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000012162 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000012163 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000012164 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000012165
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000012166 return true;
12167}
12168
Richard Smithb228a862012-02-15 02:18:13 +000012169/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
12170/// cases, the in-place evaluation is essential, since later initializers for
12171/// an object can indirectly refer to subobjects which were initialized earlier.
12172static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000012173 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000012174 assert(!E->isValueDependent());
12175
Richard Smith7525ff62013-05-09 07:14:00 +000012176 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000012177 return false;
12178
12179 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000012180 // Evaluate arrays and record types in-place, so that later initializers can
12181 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000012182 QualType T = E->getType();
12183 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000012184 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012185 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000012186 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000012187 else if (T->isAtomicType()) {
12188 QualType Unqual = T.getAtomicUnqualifiedType();
12189 if (Unqual->isArrayType() || Unqual->isRecordType())
12190 return EvaluateAtomic(E, &This, Result, Info);
12191 }
Richard Smithed5165f2011-11-04 05:33:44 +000012192 }
12193
12194 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000012195 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000012196}
12197
Richard Smithf57d8cb2011-12-09 22:58:01 +000012198/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
12199/// lvalue-to-rvalue cast if it is an lvalue.
12200static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Nandor Licker950b70d2019-09-13 09:46:16 +000012201 if (Info.EnableNewConstInterp) {
12202 auto &InterpCtx = Info.Ctx.getInterpContext();
12203 switch (InterpCtx.evaluateAsRValue(Info, E, Result)) {
12204 case interp::InterpResult::Success:
12205 return true;
12206 case interp::InterpResult::Fail:
12207 return false;
12208 case interp::InterpResult::Bail:
12209 break;
12210 }
12211 }
12212
James Dennett0492ef02014-03-14 17:44:10 +000012213 if (E->getType().isNull())
12214 return false;
12215
Nick Lewyckyc190f962017-05-02 01:06:16 +000012216 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000012217 return false;
12218
Richard Smith2e312c82012-03-03 22:46:17 +000012219 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000012220 return false;
12221
12222 if (E->isGLValue()) {
12223 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000012224 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000012225 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000012226 return false;
12227 }
12228
Richard Smith2e312c82012-03-03 22:46:17 +000012229 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000012230 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000012231}
Richard Smith11562c52011-10-28 17:51:58 +000012232
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012233static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000012234 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012235 // Fast-path evaluations of integer literals, since we sometimes see files
12236 // containing vast quantities of these.
12237 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
12238 Result.Val = APValue(APSInt(L->getValue(),
12239 L->getType()->isUnsignedIntegerType()));
12240 IsConst = true;
12241 return true;
12242 }
James Dennett0492ef02014-03-14 17:44:10 +000012243
12244 // This case should be rare, but we need to check it before we check on
12245 // the type below.
12246 if (Exp->getType().isNull()) {
12247 IsConst = false;
12248 return true;
12249 }
Fangrui Song6907ce22018-07-30 19:24:48 +000012250
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012251 // FIXME: Evaluating values of large array and record types can cause
12252 // performance problems. Only do so in C++11 for now.
12253 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
12254 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000012255 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012256 IsConst = false;
12257 return true;
12258 }
12259 return false;
12260}
12261
Fangrui Song407659a2018-11-30 23:41:18 +000012262static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
12263 Expr::SideEffectsKind SEK) {
12264 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
12265 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
12266}
12267
12268static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
12269 const ASTContext &Ctx, EvalInfo &Info) {
12270 bool IsConst;
12271 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
12272 return IsConst;
12273
12274 return EvaluateAsRValue(Info, E, Result.Val);
12275}
12276
12277static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
12278 const ASTContext &Ctx,
12279 Expr::SideEffectsKind AllowSideEffects,
12280 EvalInfo &Info) {
12281 if (!E->getType()->isIntegralOrEnumerationType())
12282 return false;
12283
12284 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
12285 !ExprResult.Val.isInt() ||
12286 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12287 return false;
12288
12289 return true;
12290}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012291
Leonard Chand3f3e162019-01-18 21:04:25 +000012292static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
12293 const ASTContext &Ctx,
12294 Expr::SideEffectsKind AllowSideEffects,
12295 EvalInfo &Info) {
12296 if (!E->getType()->isFixedPointType())
12297 return false;
12298
12299 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
12300 return false;
12301
12302 if (!ExprResult.Val.isFixedPoint() ||
12303 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12304 return false;
12305
12306 return true;
12307}
12308
Richard Smith7b553f12011-10-29 00:50:52 +000012309/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000012310/// any crazy technique (that has nothing to do with language standards) that
12311/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000012312/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
12313/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000012314bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
12315 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012316 assert(!isValueDependent() &&
12317 "Expression evaluator can't be called on a dependent expression.");
Richard Smith6d4c6582013-11-05 22:18:15 +000012318 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000012319 Info.InConstantContext = InConstantContext;
12320 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000012321}
12322
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012323bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
12324 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012325 assert(!isValueDependent() &&
12326 "Expression evaluator can't be called on a dependent expression.");
Richard Smith11562c52011-10-28 17:51:58 +000012327 EvalResult Scratch;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012328 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
Richard Smith2e312c82012-03-03 22:46:17 +000012329 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000012330}
12331
Fangrui Song407659a2018-11-30 23:41:18 +000012332bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012333 SideEffectsKind AllowSideEffects,
12334 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012335 assert(!isValueDependent() &&
12336 "Expression evaluator can't be called on a dependent expression.");
Fangrui Song407659a2018-11-30 23:41:18 +000012337 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012338 Info.InConstantContext = InConstantContext;
Fangrui Song407659a2018-11-30 23:41:18 +000012339 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000012340}
12341
Leonard Chand3f3e162019-01-18 21:04:25 +000012342bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012343 SideEffectsKind AllowSideEffects,
12344 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012345 assert(!isValueDependent() &&
12346 "Expression evaluator can't be called on a dependent expression.");
Leonard Chand3f3e162019-01-18 21:04:25 +000012347 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012348 Info.InConstantContext = InConstantContext;
Leonard Chand3f3e162019-01-18 21:04:25 +000012349 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
12350}
12351
Richard Trieube234c32016-04-21 21:04:55 +000012352bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012353 SideEffectsKind AllowSideEffects,
12354 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012355 assert(!isValueDependent() &&
12356 "Expression evaluator can't be called on a dependent expression.");
12357
Richard Trieube234c32016-04-21 21:04:55 +000012358 if (!getType()->isRealFloatingType())
12359 return false;
12360
12361 EvalResult ExprResult;
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012362 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
12363 !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000012364 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000012365 return false;
12366
12367 Result = ExprResult.Val.getFloat();
12368 return true;
12369}
12370
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012371bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
12372 bool InConstantContext) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012373 assert(!isValueDependent() &&
12374 "Expression evaluator can't be called on a dependent expression.");
12375
Richard Smith6d4c6582013-11-05 22:18:15 +000012376 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000012377 Info.InConstantContext = InConstantContext;
John McCall45d55e42010-05-07 21:00:08 +000012378 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000012379 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
12380 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000012381 Ctx.getLValueReferenceType(getType()), LV,
12382 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000012383 return false;
12384
Richard Smith2e312c82012-03-03 22:46:17 +000012385 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000012386 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000012387}
12388
Reid Kleckner1a840d22018-05-10 18:57:35 +000012389bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
12390 const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012391 assert(!isValueDependent() &&
12392 "Expression evaluator can't be called on a dependent expression.");
12393
Reid Kleckner1a840d22018-05-10 18:57:35 +000012394 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
12395 EvalInfo Info(Ctx, Result, EM);
Eric Fiselier680e8652019-03-08 22:06:48 +000012396 Info.InConstantContext = true;
Eric Fiselieradd16a82019-04-24 02:23:30 +000012397
Reid Kleckner1a840d22018-05-10 18:57:35 +000012398 if (!::Evaluate(Result.Val, Info, this))
12399 return false;
12400
12401 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
12402 Usage);
12403}
12404
Richard Smithd0b4dd62011-12-19 06:19:21 +000012405bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
12406 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012407 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012408 assert(!isValueDependent() &&
12409 "Expression evaluator can't be called on a dependent expression.");
12410
Richard Smithdafff942012-01-14 04:30:29 +000012411 // FIXME: Evaluating initializers for large array and record types can cause
12412 // performance problems. Only do so in C++11 for now.
12413 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012414 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000012415 return false;
12416
Richard Smithd0b4dd62011-12-19 06:19:21 +000012417 Expr::EvalStatus EStatus;
12418 EStatus.Diag = &Notes;
12419
Nandor Licker950b70d2019-09-13 09:46:16 +000012420 EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
Richard Smith0c6124b2015-12-03 01:36:22 +000012421 ? EvalInfo::EM_ConstantExpression
12422 : EvalInfo::EM_ConstantFold);
Nandor Licker950b70d2019-09-13 09:46:16 +000012423 Info.setEvaluatingDecl(VD, Value);
12424 Info.InConstantContext = true;
12425
12426 SourceLocation DeclLoc = VD->getLocation();
12427 QualType DeclTy = VD->getType();
12428
12429 if (Info.EnableNewConstInterp) {
12430 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
12431 switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) {
12432 case interp::InterpResult::Fail:
12433 // Bail out if an error was encountered.
12434 return false;
12435 case interp::InterpResult::Success:
12436 // Evaluation succeeded and value was set.
12437 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
12438 case interp::InterpResult::Bail:
12439 // Evaluate the value again for the tree evaluator to use.
12440 break;
12441 }
12442 }
Richard Smithd0b4dd62011-12-19 06:19:21 +000012443
12444 LValue LVal;
12445 LVal.set(VD);
12446
Richard Smithfddd3842011-12-30 21:15:51 +000012447 // C++11 [basic.start.init]p2:
12448 // Variables with static storage duration or thread storage duration shall be
12449 // zero-initialized before any other initialization takes place.
12450 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012451 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Nandor Licker950b70d2019-09-13 09:46:16 +000012452 !DeclTy->isReferenceType()) {
12453 ImplicitValueInitExpr VIE(DeclTy);
12454 if (!EvaluateInPlace(Value, Info, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000012455 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000012456 return false;
12457 }
12458
Nandor Licker950b70d2019-09-13 09:46:16 +000012459 if (!EvaluateInPlace(Value, Info, LVal, this,
Richard Smith7525ff62013-05-09 07:14:00 +000012460 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000012461 EStatus.HasSideEffects)
12462 return false;
12463
Nandor Licker950b70d2019-09-13 09:46:16 +000012464 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000012465}
12466
Richard Smith7b553f12011-10-29 00:50:52 +000012467/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
12468/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000012469bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012470 assert(!isValueDependent() &&
12471 "Expression evaluator can't be called on a dependent expression.");
12472
Anders Carlsson5b3638b2008-12-01 06:44:05 +000012473 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000012474 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000012475 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000012476}
Anders Carlsson59689ed2008-11-22 21:04:56 +000012477
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000012478APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012479 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012480 assert(!isValueDependent() &&
12481 "Expression evaluator can't be called on a dependent expression.");
12482
Fangrui Song407659a2018-11-30 23:41:18 +000012483 EvalResult EVResult;
12484 EVResult.Diag = Diag;
12485 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12486 Info.InConstantContext = true;
12487
12488 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000012489 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000012490 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000012491 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000012492
Fangrui Song407659a2018-11-30 23:41:18 +000012493 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000012494}
John McCall864e3962010-05-07 05:32:02 +000012495
David Bolvansky3b6ae572018-10-18 20:49:06 +000012496APSInt Expr::EvaluateKnownConstIntCheckOverflow(
12497 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012498 assert(!isValueDependent() &&
12499 "Expression evaluator can't be called on a dependent expression.");
12500
Fangrui Song407659a2018-11-30 23:41:18 +000012501 EvalResult EVResult;
12502 EVResult.Diag = Diag;
Richard Smith045b2272019-09-10 21:24:09 +000012503 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000012504 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000012505 Info.CheckingForUndefinedBehavior = true;
Fangrui Song407659a2018-11-30 23:41:18 +000012506
12507 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000012508 (void)Result;
12509 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000012510 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000012511
Fangrui Song407659a2018-11-30 23:41:18 +000012512 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000012513}
12514
Richard Smithe9ff7702013-11-05 22:23:30 +000012515void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000012516 assert(!isValueDependent() &&
12517 "Expression evaluator can't be called on a dependent expression.");
12518
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012519 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000012520 EvalResult EVResult;
12521 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
Richard Smith045b2272019-09-10 21:24:09 +000012522 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12523 Info.CheckingForUndefinedBehavior = true;
Fangrui Song407659a2018-11-30 23:41:18 +000012524 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012525 }
12526}
12527
Richard Smithe6c01442013-06-05 00:46:14 +000012528bool Expr::EvalResult::isGlobalLValue() const {
12529 assert(Val.isLValue());
12530 return IsGlobalLValue(Val.getLValueBase());
12531}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000012532
12533
John McCall864e3962010-05-07 05:32:02 +000012534/// isIntegerConstantExpr - this recursive routine will test if an expression is
12535/// an integer constant expression.
12536
12537/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
12538/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000012539
12540// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000012541// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
12542// and a (possibly null) SourceLocation indicating the location of the problem.
12543//
John McCall864e3962010-05-07 05:32:02 +000012544// Note that to reduce code duplication, this helper does no evaluation
12545// itself; the caller checks whether the expression is evaluatable, and
12546// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000012547// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000012548
Dan Gohman28ade552010-07-26 21:25:24 +000012549namespace {
12550
Richard Smith9e575da2012-12-28 13:25:52 +000012551enum ICEKind {
12552 /// This expression is an ICE.
12553 IK_ICE,
12554 /// This expression is not an ICE, but if it isn't evaluated, it's
12555 /// a legal subexpression for an ICE. This return value is used to handle
12556 /// the comma operator in C99 mode, and non-constant subexpressions.
12557 IK_ICEIfUnevaluated,
12558 /// This expression is not an ICE, and is not a legal subexpression for one.
12559 IK_NotICE
12560};
12561
John McCall864e3962010-05-07 05:32:02 +000012562struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000012563 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000012564 SourceLocation Loc;
12565
Richard Smith9e575da2012-12-28 13:25:52 +000012566 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000012567};
12568
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012569}
Dan Gohman28ade552010-07-26 21:25:24 +000012570
Richard Smith9e575da2012-12-28 13:25:52 +000012571static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
12572
12573static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000012574
Craig Toppera31a8822013-08-22 07:09:37 +000012575static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000012576 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000012577 Expr::EvalStatus Status;
12578 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12579
12580 Info.InConstantContext = true;
12581 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000012582 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012583 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000012584
John McCall864e3962010-05-07 05:32:02 +000012585 return NoDiag();
12586}
12587
Craig Toppera31a8822013-08-22 07:09:37 +000012588static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000012589 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000012590 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012591 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012592
12593 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000012594#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000012595#define STMT(Node, Base) case Expr::Node##Class:
12596#define EXPR(Node, Base)
12597#include "clang/AST/StmtNodes.inc"
12598 case Expr::PredefinedExprClass:
12599 case Expr::FloatingLiteralClass:
12600 case Expr::ImaginaryLiteralClass:
12601 case Expr::StringLiteralClass:
12602 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000012603 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000012604 case Expr::MemberExprClass:
12605 case Expr::CompoundAssignOperatorClass:
12606 case Expr::CompoundLiteralExprClass:
12607 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000012608 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000012609 case Expr::ArrayInitLoopExprClass:
12610 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000012611 case Expr::NoInitExprClass:
12612 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000012613 case Expr::ImplicitValueInitExprClass:
12614 case Expr::ParenListExprClass:
12615 case Expr::VAArgExprClass:
12616 case Expr::AddrLabelExprClass:
12617 case Expr::StmtExprClass:
12618 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000012619 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000012620 case Expr::CXXDynamicCastExprClass:
12621 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000012622 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000012623 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000012624 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000012625 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000012626 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012627 case Expr::CXXThisExprClass:
12628 case Expr::CXXThrowExprClass:
12629 case Expr::CXXNewExprClass:
12630 case Expr::CXXDeleteExprClass:
12631 case Expr::CXXPseudoDestructorExprClass:
12632 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000012633 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000012634 case Expr::DependentScopeDeclRefExprClass:
12635 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000012636 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000012637 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000012638 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000012639 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000012640 case Expr::CXXTemporaryObjectExprClass:
12641 case Expr::CXXUnresolvedConstructExprClass:
12642 case Expr::CXXDependentScopeMemberExprClass:
12643 case Expr::UnresolvedMemberExprClass:
12644 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000012645 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012646 case Expr::ObjCArrayLiteralClass:
12647 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012648 case Expr::ObjCEncodeExprClass:
12649 case Expr::ObjCMessageExprClass:
12650 case Expr::ObjCSelectorExprClass:
12651 case Expr::ObjCProtocolExprClass:
12652 case Expr::ObjCIvarRefExprClass:
12653 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012654 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000012655 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000012656 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000012657 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000012658 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000012659 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000012660 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000012661 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000012662 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000012663 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000012664 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000012665 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000012666 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000012667 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000012668 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000012669 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000012670 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000012671 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000012672 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000012673 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000012674 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012675 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000012676
Richard Smithf137f932014-01-25 20:50:08 +000012677 case Expr::InitListExprClass: {
12678 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
12679 // form "T x = { a };" is equivalent to "T x = a;".
12680 // Unless we're initializing a reference, T is a scalar as it is known to be
12681 // of integral or enumeration type.
12682 if (E->isRValue())
12683 if (cast<InitListExpr>(E)->getNumInits() == 1)
12684 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012685 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000012686 }
12687
Douglas Gregor820ba7b2011-01-04 17:33:58 +000012688 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000012689 case Expr::GNUNullExprClass:
Eric Fiselier708afb52019-05-16 21:04:15 +000012690 case Expr::SourceLocExprClass:
John McCall864e3962010-05-07 05:32:02 +000012691 return NoDiag();
12692
John McCall7c454bb2011-07-15 05:09:51 +000012693 case Expr::SubstNonTypeTemplateParmExprClass:
12694 return
12695 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12696
Bill Wendling7c44da22018-10-31 03:48:47 +000012697 case Expr::ConstantExprClass:
12698 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12699
John McCall864e3962010-05-07 05:32:02 +000012700 case Expr::ParenExprClass:
12701 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000012702 case Expr::GenericSelectionExprClass:
12703 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012704 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000012705 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000012706 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000012707 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000012708 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000012709 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000012710 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000012711 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000012712 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000012713 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000012714 return NoDiag();
12715 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000012716 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000012717 // C99 6.6/3 allows function calls within unevaluated subexpressions of
12718 // constant expressions, but they can never be ICEs because an ICE cannot
12719 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000012720 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000012721 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000012722 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012723 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012724 }
Richard Smith6365c912012-02-24 22:12:32 +000012725 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000012726 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12727 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000012728 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000012729 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000012730 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000012731 // Parameter variables are never constants. Without this check,
12732 // getAnyInitializer() can find a default argument, which leads
12733 // to chaos.
12734 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000012735 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000012736
12737 // C++ 7.1.5.1p2
12738 // A variable of non-volatile const-qualified integral or enumeration
12739 // type initialized by an ICE can be used in ICEs.
12740 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000012741 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000012742 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000012743
Richard Smithd0b4dd62011-12-19 06:19:21 +000012744 const VarDecl *VD;
12745 // Look for a declaration of this variable that has an initializer, and
12746 // check whether it is an ICE.
12747 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12748 return NoDiag();
12749 else
Richard Smith9e575da2012-12-28 13:25:52 +000012750 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000012751 }
12752 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012753 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000012754 }
John McCall864e3962010-05-07 05:32:02 +000012755 case Expr::UnaryOperatorClass: {
12756 const UnaryOperator *Exp = cast<UnaryOperator>(E);
12757 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000012758 case UO_PostInc:
12759 case UO_PostDec:
12760 case UO_PreInc:
12761 case UO_PreDec:
12762 case UO_AddrOf:
12763 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000012764 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000012765 // C99 6.6/3 allows increment and decrement within unevaluated
12766 // subexpressions of constant expressions, but they can never be ICEs
12767 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012768 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000012769 case UO_Extension:
12770 case UO_LNot:
12771 case UO_Plus:
12772 case UO_Minus:
12773 case UO_Not:
12774 case UO_Real:
12775 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000012776 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012777 }
Reid Klecknere540d972018-11-01 17:51:48 +000012778 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000012779 }
12780 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000012781 // Note that per C99, offsetof must be an ICE. And AFAIK, using
12782 // EvaluateAsRValue matches the proposed gcc behavior for cases like
12783 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
12784 // compliance: we should warn earlier for offsetof expressions with
12785 // array subscripts that aren't ICEs, and if the array subscripts
12786 // are ICEs, the value of the offsetof must be an integer constant.
12787 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000012788 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000012789 case Expr::UnaryExprOrTypeTraitExprClass: {
12790 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12791 if ((Exp->getKind() == UETT_SizeOf) &&
12792 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012793 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012794 return NoDiag();
12795 }
12796 case Expr::BinaryOperatorClass: {
12797 const BinaryOperator *Exp = cast<BinaryOperator>(E);
12798 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000012799 case BO_PtrMemD:
12800 case BO_PtrMemI:
12801 case BO_Assign:
12802 case BO_MulAssign:
12803 case BO_DivAssign:
12804 case BO_RemAssign:
12805 case BO_AddAssign:
12806 case BO_SubAssign:
12807 case BO_ShlAssign:
12808 case BO_ShrAssign:
12809 case BO_AndAssign:
12810 case BO_XorAssign:
12811 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000012812 // C99 6.6/3 allows assignments within unevaluated subexpressions of
12813 // constant expressions, but they can never be ICEs because an ICE cannot
12814 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012815 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012816
John McCalle3027922010-08-25 11:45:40 +000012817 case BO_Mul:
12818 case BO_Div:
12819 case BO_Rem:
12820 case BO_Add:
12821 case BO_Sub:
12822 case BO_Shl:
12823 case BO_Shr:
12824 case BO_LT:
12825 case BO_GT:
12826 case BO_LE:
12827 case BO_GE:
12828 case BO_EQ:
12829 case BO_NE:
12830 case BO_And:
12831 case BO_Xor:
12832 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000012833 case BO_Comma:
12834 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000012835 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12836 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000012837 if (Exp->getOpcode() == BO_Div ||
12838 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000012839 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000012840 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000012841 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000012842 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000012843 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012844 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012845 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000012846 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000012847 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012848 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012849 }
12850 }
12851 }
John McCalle3027922010-08-25 11:45:40 +000012852 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012853 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000012854 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12855 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000012856 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012857 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012858 } else {
12859 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012860 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000012861 }
12862 }
Richard Smith9e575da2012-12-28 13:25:52 +000012863 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000012864 }
John McCalle3027922010-08-25 11:45:40 +000012865 case BO_LAnd:
12866 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000012867 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12868 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012869 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000012870 // Rare case where the RHS has a comma "side-effect"; we need
12871 // to actually check the condition to see whether the side
12872 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000012873 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000012874 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000012875 return RHSResult;
12876 return NoDiag();
12877 }
12878
Richard Smith9e575da2012-12-28 13:25:52 +000012879 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000012880 }
12881 }
Reid Klecknere540d972018-11-01 17:51:48 +000012882 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000012883 }
12884 case Expr::ImplicitCastExprClass:
12885 case Expr::CStyleCastExprClass:
12886 case Expr::CXXFunctionalCastExprClass:
12887 case Expr::CXXStaticCastExprClass:
12888 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000012889 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000012890 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000012891 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000012892 if (isa<ExplicitCastExpr>(E)) {
12893 if (const FloatingLiteral *FL
12894 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12895 unsigned DestWidth = Ctx.getIntWidth(E->getType());
12896 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12897 APSInt IgnoredVal(DestWidth, !DestSigned);
12898 bool Ignored;
12899 // If the value does not fit in the destination type, the behavior is
12900 // undefined, so we are not required to treat it as a constant
12901 // expression.
12902 if (FL->getValue().convertToInteger(IgnoredVal,
12903 llvm::APFloat::rmTowardZero,
12904 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012905 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000012906 return NoDiag();
12907 }
12908 }
Eli Friedman76d4e432011-09-29 21:49:34 +000012909 switch (cast<CastExpr>(E)->getCastKind()) {
12910 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000012911 case CK_AtomicToNonAtomic:
12912 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000012913 case CK_NoOp:
12914 case CK_IntegralToBoolean:
12915 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000012916 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000012917 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012918 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000012919 }
John McCall864e3962010-05-07 05:32:02 +000012920 }
John McCallc07a0c72011-02-17 10:25:35 +000012921 case Expr::BinaryConditionalOperatorClass: {
12922 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12923 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012924 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000012925 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012926 if (FalseResult.Kind == IK_NotICE) return FalseResult;
12927 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12928 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000012929 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000012930 return FalseResult;
12931 }
John McCall864e3962010-05-07 05:32:02 +000012932 case Expr::ConditionalOperatorClass: {
12933 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12934 // If the condition (ignoring parens) is a __builtin_constant_p call,
12935 // then only the true side is actually considered in an integer constant
12936 // expression, and it is fully evaluated. This is an important GNU
12937 // extension. See GCC PR38377 for discussion.
12938 if (const CallExpr *CallCE
12939 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000012940 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000012941 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000012942 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000012943 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012944 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000012945
Richard Smithf57d8cb2011-12-09 22:58:01 +000012946 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12947 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000012948
Richard Smith9e575da2012-12-28 13:25:52 +000012949 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012950 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012951 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000012952 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012953 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000012954 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000012955 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000012956 return NoDiag();
12957 // Rare case where the diagnostics depend on which side is evaluated
12958 // Note that if we get here, CondResult is 0, and at least one of
12959 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000012960 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000012961 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000012962 return TrueResult;
12963 }
12964 case Expr::CXXDefaultArgExprClass:
12965 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000012966 case Expr::CXXDefaultInitExprClass:
12967 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012968 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000012969 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000012970 }
Erik Pilkingtoneee944e2019-07-02 18:28:13 +000012971 case Expr::BuiltinBitCastExprClass: {
12972 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
12973 return ICEDiag(IK_NotICE, E->getBeginLoc());
12974 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
12975 }
John McCall864e3962010-05-07 05:32:02 +000012976 }
12977
David Blaikiee4d798f2012-01-20 21:50:17 +000012978 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000012979}
12980
Richard Smithf57d8cb2011-12-09 22:58:01 +000012981/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000012982static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000012983 const Expr *E,
12984 llvm::APSInt *Value,
12985 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000012986 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000012987 if (Loc) *Loc = E->getExprLoc();
12988 return false;
12989 }
12990
Richard Smith66e05fe2012-01-18 05:21:49 +000012991 APValue Result;
12992 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000012993 return false;
12994
Richard Smith98710fc2014-11-13 23:03:19 +000012995 if (!Result.isInt()) {
12996 if (Loc) *Loc = E->getExprLoc();
12997 return false;
12998 }
12999
Richard Smith66e05fe2012-01-18 05:21:49 +000013000 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000013001 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000013002}
13003
Craig Toppera31a8822013-08-22 07:09:37 +000013004bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
13005 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013006 assert(!isValueDependent() &&
13007 "Expression evaluator can't be called on a dependent expression.");
13008
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013009 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000013010 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000013011
Richard Smith9e575da2012-12-28 13:25:52 +000013012 ICEDiag D = CheckICE(this, Ctx);
13013 if (D.Kind != IK_ICE) {
13014 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000013015 return false;
13016 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000013017 return true;
13018}
13019
Craig Toppera31a8822013-08-22 07:09:37 +000013020bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000013021 SourceLocation *Loc, bool isEvaluated) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013022 assert(!isValueDependent() &&
13023 "Expression evaluator can't be called on a dependent expression.");
13024
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013025 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000013026 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
13027
13028 if (!isIntegerConstantExpr(Ctx, Loc))
13029 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000013030
Richard Smith5c40f092015-12-04 03:00:44 +000013031 // The only possible side-effects here are due to UB discovered in the
13032 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
13033 // required to treat the expression as an ICE, so we produce the folded
13034 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000013035 EvalResult ExprResult;
13036 Expr::EvalStatus Status;
13037 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
13038 Info.InConstantContext = true;
13039
13040 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000013041 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000013042
13043 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000013044 return true;
13045}
Richard Smith66e05fe2012-01-18 05:21:49 +000013046
Craig Toppera31a8822013-08-22 07:09:37 +000013047bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013048 assert(!isValueDependent() &&
13049 "Expression evaluator can't be called on a dependent expression.");
13050
Richard Smith9e575da2012-12-28 13:25:52 +000013051 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000013052}
13053
Craig Toppera31a8822013-08-22 07:09:37 +000013054bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000013055 SourceLocation *Loc) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013056 assert(!isValueDependent() &&
13057 "Expression evaluator can't be called on a dependent expression.");
13058
Richard Smith66e05fe2012-01-18 05:21:49 +000013059 // We support this checking in C++98 mode in order to diagnose compatibility
13060 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013061 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000013062
Richard Smith98a0a492012-02-14 21:38:30 +000013063 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000013064 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013065 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000013066 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000013067 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000013068
13069 APValue Scratch;
13070 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
13071
13072 if (!Diags.empty()) {
13073 IsConstExpr = false;
13074 if (Loc) *Loc = Diags[0].first;
13075 } else if (!IsConstExpr) {
13076 // FIXME: This shouldn't happen.
13077 if (Loc) *Loc = getExprLoc();
13078 }
13079
13080 return IsConstExpr;
13081}
Richard Smith253c2a32012-01-27 01:14:48 +000013082
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013083bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
13084 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000013085 ArrayRef<const Expr*> Args,
13086 const Expr *This) const {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013087 assert(!isValueDependent() &&
13088 "Expression evaluator can't be called on a dependent expression.");
13089
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013090 Expr::EvalStatus Status;
13091 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000013092 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013093
George Burgess IV177399e2017-01-09 04:12:14 +000013094 LValue ThisVal;
13095 const LValue *ThisPtr = nullptr;
13096 if (This) {
13097#ifndef NDEBUG
13098 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
13099 assert(MD && "Don't provide `this` for non-methods.");
13100 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
13101#endif
13102 if (EvaluateObjectArgument(Info, This, ThisVal))
13103 ThisPtr = &ThisVal;
13104 if (Info.EvalStatus.HasSideEffects)
13105 return false;
13106 }
13107
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013108 ArgVector ArgValues(Args.size());
13109 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
13110 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000013111 if ((*I)->isValueDependent() ||
13112 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013113 // If evaluation fails, throw away the argument entirely.
13114 ArgValues[I - Args.begin()] = APValue();
13115 if (Info.EvalStatus.HasSideEffects)
13116 return false;
13117 }
13118
13119 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000013120 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013121 ArgValues.data());
13122 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
13123}
13124
Richard Smith253c2a32012-01-27 01:14:48 +000013125bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013126 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000013127 PartialDiagnosticAt> &Diags) {
13128 // FIXME: It would be useful to check constexpr function templates, but at the
13129 // moment the constant expression evaluator cannot cope with the non-rigorous
13130 // ASTs which we build for dependent expressions.
13131 if (FD->isDependentContext())
13132 return true;
13133
13134 Expr::EvalStatus Status;
13135 Status.Diag = &Diags;
13136
Richard Smith045b2272019-09-10 21:24:09 +000013137 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000013138 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000013139 Info.CheckingPotentialConstantExpression = true;
Richard Smith253c2a32012-01-27 01:14:48 +000013140
Nandor Licker950b70d2019-09-13 09:46:16 +000013141 // The constexpr VM attempts to compile all methods to bytecode here.
13142 if (Info.EnableNewConstInterp) {
13143 auto &InterpCtx = Info.Ctx.getInterpContext();
13144 switch (InterpCtx.isPotentialConstantExpr(Info, FD)) {
13145 case interp::InterpResult::Success:
13146 case interp::InterpResult::Fail:
13147 return Diags.empty();
13148 case interp::InterpResult::Bail:
13149 break;
13150 }
13151 }
13152
Richard Smith253c2a32012-01-27 01:14:48 +000013153 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000013154 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000013155
Richard Smith7525ff62013-05-09 07:14:00 +000013156 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000013157 // is a temporary being used as the 'this' pointer.
13158 LValue This;
13159 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000013160 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000013161
Richard Smith253c2a32012-01-27 01:14:48 +000013162 ArrayRef<const Expr*> Args;
13163
Richard Smith2e312c82012-03-03 22:46:17 +000013164 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000013165 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
13166 // Evaluate the call as a constant initializer, to allow the construction
13167 // of objects of non-literal types.
13168 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000013169 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
13170 } else {
13171 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000013172 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000013173 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000013174 }
Richard Smith253c2a32012-01-27 01:14:48 +000013175
13176 return Diags.empty();
13177}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013178
13179bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
13180 const FunctionDecl *FD,
13181 SmallVectorImpl<
13182 PartialDiagnosticAt> &Diags) {
Dmitri Gribenko04323c22019-05-17 17:16:53 +000013183 assert(!E->isValueDependent() &&
13184 "Expression evaluator can't be called on a dependent expression.");
13185
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013186 Expr::EvalStatus Status;
13187 Status.Diag = &Diags;
13188
13189 EvalInfo Info(FD->getASTContext(), Status,
Richard Smith045b2272019-09-10 21:24:09 +000013190 EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000013191 Info.InConstantContext = true;
Richard Smith045b2272019-09-10 21:24:09 +000013192 Info.CheckingPotentialConstantExpression = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013193
13194 // Fabricate a call stack frame to give the arguments a plausible cover story.
13195 ArrayRef<const Expr*> Args;
13196 ArgVector ArgValues(0);
Gauthier Harnisch0bb4d462019-06-15 08:32:56 +000013197 bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013198 (void)Success;
13199 assert(Success &&
13200 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000013201 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000013202
13203 APValue ResultScratch;
13204 Evaluate(ResultScratch, Info, E);
13205 return Diags.empty();
13206}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000013207
13208bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
13209 unsigned Type) const {
13210 if (!getType()->isPointerType())
13211 return false;
13212
13213 Expr::EvalStatus Status;
13214 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000013215 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000013216}