blob: ea36072bd9c8970f2126b345f3048157b408d2f3 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson7a241ba2008-07-03 04:20:39 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
Richard Smith253c2a32012-01-27 01:14:48 +000011// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000025// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000027//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000033//===----------------------------------------------------------------------===//
34
35#include "clang/AST/APValue.h"
36#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000037#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000038#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Tim Northover314fbfa2018-11-02 13:14:11 +000041#include "clang/AST/OSLog.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000042#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000043#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000044#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000045#include "clang/Basic/Builtins.h"
Leonard Chand3f3e162019-01-18 21:04:25 +000046#include "clang/Basic/FixedPoint.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000047#include "clang/Basic/TargetInfo.h"
Fangrui Song407659a2018-11-30 23:41:18 +000048#include "llvm/Support/SaveAndRestore.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000049#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000050#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000051#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000052
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000053#define DEBUG_TYPE "exprconstant"
54
Anders Carlsson7a241ba2008-07-03 04:20:39 +000055using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000056using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000057using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000058
Richard Smithb228a862012-02-15 02:18:13 +000059static bool IsGlobalLValue(APValue::LValueBase B);
60
John McCall93d91dc2010-05-07 17:22:02 +000061namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000062 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000063 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000064 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000065
Richard Smithb228a862012-02-15 02:18:13 +000066 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000067 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000068 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000069 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000070 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000071 //
72 // extern int arr[]; void f() { extern int arr[3]; };
73 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000074 //
75 // For now, we take the array bound from the most recent declaration.
76 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
77 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
78 QualType T = Redecl->getType();
79 if (!T->isIncompleteArrayType())
80 return T;
81 }
82 return D->getType();
83 }
Richard Smith84401042013-06-03 05:03:02 +000084
85 const Expr *Base = B.get<const Expr*>();
86
87 // For a materialized temporary, the type of the temporary we materialized
88 // may not be the type of the expression.
89 if (const MaterializeTemporaryExpr *MTE =
90 dyn_cast<MaterializeTemporaryExpr>(Base)) {
91 SmallVector<const Expr *, 2> CommaLHSs;
92 SmallVector<SubobjectAdjustment, 2> Adjustments;
93 const Expr *Temp = MTE->GetTemporaryExpr();
94 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
95 Adjustments);
96 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000097 // for it directly. Otherwise use the type after adjustment.
98 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000099 return Inner->getType();
100 }
101
102 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000103 }
104
Richard Smithd62306a2011-11-10 06:34:14 +0000105 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000106 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000107 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000108 return dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000109 }
110 /// Get an LValue path entry, which is known to not be an array index, as a
111 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000112 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000113 return dyn_cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000114 }
115 /// Determine whether this LValue path entry for a base class names a virtual
116 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000117 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000118 return E.getAsBaseOrMember().getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000119 }
120
George Burgess IVe3763372016-12-22 02:50:20 +0000121 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
122 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
123 const FunctionDecl *Callee = CE->getDirectCallee();
124 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
125 }
126
127 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
128 /// This will look through a single cast.
129 ///
130 /// Returns null if we couldn't unwrap a function with alloc_size.
131 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
132 if (!E->getType()->isPointerType())
133 return nullptr;
134
135 E = E->IgnoreParens();
136 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000137 // probably be a cast of some kind. In exotic cases, we might also see a
138 // top-level ExprWithCleanups. Ignore them either way.
Bill Wendling7c44da22018-10-31 03:48:47 +0000139 if (const auto *FE = dyn_cast<FullExpr>(E))
140 E = FE->getSubExpr()->IgnoreParens();
George Burgess IV47638762018-03-07 04:52:34 +0000141
George Burgess IVe3763372016-12-22 02:50:20 +0000142 if (const auto *Cast = dyn_cast<CastExpr>(E))
143 E = Cast->getSubExpr()->IgnoreParens();
144
145 if (const auto *CE = dyn_cast<CallExpr>(E))
146 return getAllocSizeAttr(CE) ? CE : nullptr;
147 return nullptr;
148 }
149
150 /// Determines whether or not the given Base contains a call to a function
151 /// with the alloc_size attribute.
152 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
153 const auto *E = Base.dyn_cast<const Expr *>();
154 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
155 }
156
Richard Smith6f4f0f12017-10-20 22:56:25 +0000157 /// The bound to claim that an array of unknown bound has.
158 /// The value in MostDerivedArraySize is undefined in this case. So, set it
159 /// to an arbitrary value that's likely to loudly break things if it's used.
160 static const uint64_t AssumedSizeForUnsizedArray =
161 std::numeric_limits<uint64_t>::max() / 2;
162
George Burgess IVe3763372016-12-22 02:50:20 +0000163 /// Determines if an LValue with the given LValueBase will have an unsized
164 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000165 /// Find the path length and type of the most-derived subobject in the given
166 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000167 static unsigned
168 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
169 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000170 uint64_t &ArraySize, QualType &Type, bool &IsArray,
171 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000172 // This only accepts LValueBases from APValues, and APValues don't support
173 // arrays that lack size info.
174 assert(!isBaseAnAllocSizeCall(Base) &&
175 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000176 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000177 Type = getType(Base);
178
Richard Smith80815602011-11-07 05:07:52 +0000179 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000180 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000181 const ArrayType *AT = Ctx.getAsArrayType(Type);
182 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000183 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000184 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000185
186 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
187 ArraySize = CAT->getSize().getZExtValue();
188 } else {
189 assert(I == 0 && "unexpected unsized array designator");
190 FirstEntryIsUnsizedArray = true;
191 ArraySize = AssumedSizeForUnsizedArray;
192 }
Richard Smith66c96992012-02-18 22:04:06 +0000193 } else if (Type->isAnyComplexType()) {
194 const ComplexType *CT = Type->castAs<ComplexType>();
195 Type = CT->getElementType();
196 ArraySize = 2;
197 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000198 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000199 } else if (const FieldDecl *FD = getAsField(Path[I])) {
200 Type = FD->getType();
201 ArraySize = 0;
202 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000203 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000204 } else {
Richard Smith80815602011-11-07 05:07:52 +0000205 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000206 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000207 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000208 }
Richard Smith80815602011-11-07 05:07:52 +0000209 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000210 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000211 }
212
Richard Smitha8105bc2012-01-06 16:39:00 +0000213 // The order of this enum is important for diagnostics.
214 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000215 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smithdebad642019-05-12 09:39:08 +0000216 CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 };
218
Richard Smith96e0c102011-11-04 02:25:55 +0000219 /// A path from a glvalue to a subobject of that glvalue.
220 struct SubobjectDesignator {
221 /// True if the subobject was named in a manner not supported by C++11. Such
222 /// lvalues can still be folded, but they are not core constant expressions
223 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000224 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000225
Richard Smitha8105bc2012-01-06 16:39:00 +0000226 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000227 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000228
Daniel Jasperffdee092017-05-02 19:21:42 +0000229 /// Indicator of whether the first entry is an unsized array.
230 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000231
George Burgess IVa51c4072015-10-16 01:49:01 +0000232 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000233 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000234
Richard Smitha8105bc2012-01-06 16:39:00 +0000235 /// The length of the path to the most-derived object of which this is a
236 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000237 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000238
George Burgess IVa51c4072015-10-16 01:49:01 +0000239 /// The size of the array of which the most-derived object is an element.
240 /// This will always be 0 if the most-derived object is not an array
241 /// element. 0 is not an indicator of whether or not the most-derived object
242 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000243 ///
244 /// If the current array is an unsized array, the value of this is
245 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000246 uint64_t MostDerivedArraySize;
247
248 /// The type of the most derived object referred to by this address.
249 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000250
Richard Smith80815602011-11-07 05:07:52 +0000251 typedef APValue::LValuePathEntry PathEntry;
252
Richard Smith96e0c102011-11-04 02:25:55 +0000253 /// The entries on the path from the glvalue to the designated subobject.
254 SmallVector<PathEntry, 8> Entries;
255
Richard Smitha8105bc2012-01-06 16:39:00 +0000256 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000257
Richard Smitha8105bc2012-01-06 16:39:00 +0000258 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000259 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000260 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000261 MostDerivedPathLength(0), MostDerivedArraySize(0),
262 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000263
264 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000265 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000266 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000267 MostDerivedPathLength(0), MostDerivedArraySize(0) {
268 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000269 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000270 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000271 ArrayRef<PathEntry> VEntries = V.getLValuePath();
272 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000273 if (V.getLValueBase()) {
274 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000275 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000276 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000277 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000278 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000279 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000280 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000281 }
Richard Smith80815602011-11-07 05:07:52 +0000282 }
283 }
284
Richard Smith96e0c102011-11-04 02:25:55 +0000285 void setInvalid() {
286 Invalid = true;
287 Entries.clear();
288 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000289
George Burgess IVe3763372016-12-22 02:50:20 +0000290 /// Determine whether the most derived subobject is an array without a
291 /// known bound.
292 bool isMostDerivedAnUnsizedArray() const {
293 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000294 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000295 }
296
297 /// Determine what the most derived array's size is. Results in an assertion
298 /// failure if the most derived array lacks a size.
299 uint64_t getMostDerivedArraySize() const {
300 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
301 return MostDerivedArraySize;
302 }
303
Richard Smitha8105bc2012-01-06 16:39:00 +0000304 /// Determine whether this is a one-past-the-end pointer.
305 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000306 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000307 if (IsOnePastTheEnd)
308 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000309 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smith5b5e27a2019-05-10 20:05:31 +0000310 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
311 MostDerivedArraySize)
Richard Smitha8105bc2012-01-06 16:39:00 +0000312 return true;
313 return false;
314 }
315
Richard Smith06f71b52018-08-04 00:57:17 +0000316 /// Get the range of valid index adjustments in the form
317 /// {maximum value that can be subtracted from this pointer,
318 /// maximum value that can be added to this pointer}
319 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
320 if (Invalid || isMostDerivedAnUnsizedArray())
321 return {0, 0};
322
323 // [expr.add]p4: For the purposes of these operators, a pointer to a
324 // nonarray object behaves the same as a pointer to the first element of
325 // an array of length one with the type of the object as its element type.
326 bool IsArray = MostDerivedPathLength == Entries.size() &&
327 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000328 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
329 : (uint64_t)IsOnePastTheEnd;
Richard Smith06f71b52018-08-04 00:57:17 +0000330 uint64_t ArraySize =
331 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
332 return {ArrayIndex, ArraySize - ArrayIndex};
333 }
334
Richard Smitha8105bc2012-01-06 16:39:00 +0000335 /// Check that this refers to a valid subobject.
336 bool isValidSubobject() const {
337 if (Invalid)
338 return false;
339 return !isOnePastTheEnd();
340 }
341 /// Check that this refers to a valid subobject, and if not, produce a
342 /// relevant diagnostic and set the designator as invalid.
343 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
344
Richard Smith06f71b52018-08-04 00:57:17 +0000345 /// Get the type of the designated object.
346 QualType getType(ASTContext &Ctx) const {
347 assert(!Invalid && "invalid designator has no subobject type");
348 return MostDerivedPathLength == Entries.size()
349 ? MostDerivedType
350 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
351 }
352
Richard Smitha8105bc2012-01-06 16:39:00 +0000353 /// Update this designator to refer to the first element within this array.
354 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000355 Entries.push_back(PathEntry::ArrayIndex(0));
Richard Smitha8105bc2012-01-06 16:39:00 +0000356
357 // This is a most-derived object.
358 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000359 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000360 MostDerivedArraySize = CAT->getSize().getZExtValue();
361 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000362 }
George Burgess IVe3763372016-12-22 02:50:20 +0000363 /// Update this designator to refer to the first element within the array of
364 /// elements of type T. This is an array of unknown size.
365 void addUnsizedArrayUnchecked(QualType ElemTy) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000366 Entries.push_back(PathEntry::ArrayIndex(0));
George Burgess IVe3763372016-12-22 02:50:20 +0000367
368 MostDerivedType = ElemTy;
369 MostDerivedIsArrayElement = true;
370 // The value in MostDerivedArraySize is undefined in this case. So, set it
371 // to an arbitrary value that's likely to loudly break things if it's
372 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000373 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000374 MostDerivedPathLength = Entries.size();
375 }
Richard Smith96e0c102011-11-04 02:25:55 +0000376 /// Update this designator to refer to the given base or member of this
377 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000378 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000379 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
Richard Smitha8105bc2012-01-06 16:39:00 +0000380
381 // If this isn't a base class, it's a new most-derived object.
382 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
383 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000384 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000385 MostDerivedArraySize = 0;
386 MostDerivedPathLength = Entries.size();
387 }
Richard Smith96e0c102011-11-04 02:25:55 +0000388 }
Richard Smith66c96992012-02-18 22:04:06 +0000389 /// Update this designator to refer to the given complex component.
390 void addComplexUnchecked(QualType EltTy, bool Imag) {
Richard Smith5b5e27a2019-05-10 20:05:31 +0000391 Entries.push_back(PathEntry::ArrayIndex(Imag));
Richard Smith66c96992012-02-18 22:04:06 +0000392
393 // This is technically a most-derived object, though in practice this
394 // is unlikely to matter.
395 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000396 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000397 MostDerivedArraySize = 2;
398 MostDerivedPathLength = Entries.size();
399 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000400 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000401 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
402 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000403 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000404 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
405 if (Invalid || !N) return;
406 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
407 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000408 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000409 // Can't verify -- trust that the user is doing the right thing (or if
410 // not, trust that the caller will catch the bad behavior).
411 // FIXME: Should we reject if this overflows, at least?
Richard Smith5b5e27a2019-05-10 20:05:31 +0000412 Entries.back() = PathEntry::ArrayIndex(
413 Entries.back().getAsArrayIndex() + TruncatedN);
Daniel Jasperffdee092017-05-02 19:21:42 +0000414 return;
415 }
416
417 // [expr.add]p4: For the purposes of these operators, a pointer to a
418 // nonarray object behaves the same as a pointer to the first element of
419 // an array of length one with the type of the object as its element type.
420 bool IsArray = MostDerivedPathLength == Entries.size() &&
421 MostDerivedIsArrayElement;
Richard Smith5b5e27a2019-05-10 20:05:31 +0000422 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
423 : (uint64_t)IsOnePastTheEnd;
Daniel Jasperffdee092017-05-02 19:21:42 +0000424 uint64_t ArraySize =
425 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
426
427 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
428 // Calculate the actual index in a wide enough type, so we can include
429 // it in the note.
430 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
431 (llvm::APInt&)N += ArrayIndex;
432 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
433 diagnosePointerArithmetic(Info, E, N);
434 setInvalid();
435 return;
436 }
437
438 ArrayIndex += TruncatedN;
439 assert(ArrayIndex <= ArraySize &&
440 "bounds check succeeded for out-of-bounds index");
441
442 if (IsArray)
Richard Smith5b5e27a2019-05-10 20:05:31 +0000443 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
Daniel Jasperffdee092017-05-02 19:21:42 +0000444 else
445 IsOnePastTheEnd = (ArrayIndex != 0);
446 }
Richard Smith96e0c102011-11-04 02:25:55 +0000447 };
448
Richard Smith254a73d2011-10-28 22:34:42 +0000449 /// A stack frame in the constexpr call stack.
450 struct CallStackFrame {
451 EvalInfo &Info;
452
453 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000454 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000455
Richard Smithf6f003a2011-12-16 19:06:07 +0000456 /// Callee - The function which was called.
457 const FunctionDecl *Callee;
458
Richard Smithd62306a2011-11-10 06:34:14 +0000459 /// This - The binding for the this pointer in this call, if any.
460 const LValue *This;
461
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000462 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000463 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000464 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000465
Eli Friedman4830ec82012-06-25 21:21:08 +0000466 // Note that we intentionally use std::map here so that references to
467 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000468 typedef std::pair<const void *, unsigned> MapKeyTy;
469 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000470 /// Temporaries - Temporary lvalues materialized within this stack frame.
471 MapTy Temporaries;
472
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000473 /// CallLoc - The location of the call expression for this call.
474 SourceLocation CallLoc;
475
476 /// Index - The call index of this call.
477 unsigned Index;
478
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000479 /// The stack of integers for tracking version numbers for temporaries.
480 SmallVector<unsigned, 2> TempVersionStack = {1};
481 unsigned CurTempVersion = TempVersionStack.back();
482
483 unsigned getTempVersion() const { return TempVersionStack.back(); }
484
485 void pushTempVersion() {
486 TempVersionStack.push_back(++CurTempVersion);
487 }
488
489 void popTempVersion() {
490 TempVersionStack.pop_back();
491 }
492
Faisal Vali051e3a22017-02-16 04:12:21 +0000493 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000494 // on the overall stack usage of deeply-recursing constexpr evaluations.
Faisal Vali051e3a22017-02-16 04:12:21 +0000495 // (We should cache this map rather than recomputing it repeatedly.)
496 // But let's try this and see how it goes; we can look into caching the map
497 // as a later change.
498
499 /// LambdaCaptureFields - Mapping from captured variables/this to
500 /// corresponding data members in the closure class.
501 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
502 FieldDecl *LambdaThisCaptureField;
503
Richard Smithf6f003a2011-12-16 19:06:07 +0000504 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
505 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000506 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000507 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000508
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000509 // Return the temporary for Key whose version number is Version.
510 APValue *getTemporary(const void *Key, unsigned Version) {
511 MapKeyTy KV(Key, Version);
512 auto LB = Temporaries.lower_bound(KV);
513 if (LB != Temporaries.end() && LB->first == KV)
514 return &LB->second;
515 // Pair (Key,Version) wasn't found in the map. Check that no elements
516 // in the map have 'Key' as their key.
517 assert((LB == Temporaries.end() || LB->first.first != Key) &&
518 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
519 "Element with key 'Key' found in map");
520 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000521 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000522
523 // Return the current temporary for Key in the map.
524 APValue *getCurrentTemporary(const void *Key) {
525 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
526 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
527 return &std::prev(UB)->second;
528 return nullptr;
529 }
530
531 // Return the version number of the current temporary for Key.
532 unsigned getCurrentTemporaryVersion(const void *Key) const {
533 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
534 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
535 return std::prev(UB)->first.second;
536 return 0;
537 }
538
Richard Smith08d6a2c2013-07-24 07:11:57 +0000539 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000540 };
541
Richard Smith852c9db2013-04-20 22:23:05 +0000542 /// Temporarily override 'this'.
543 class ThisOverrideRAII {
544 public:
545 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
546 : Frame(Frame), OldThis(Frame.This) {
547 if (Enable)
548 Frame.This = NewThis;
549 }
550 ~ThisOverrideRAII() {
551 Frame.This = OldThis;
552 }
553 private:
554 CallStackFrame &Frame;
555 const LValue *OldThis;
556 };
557
Richard Smith92b1ce02011-12-12 09:28:41 +0000558 /// A partial diagnostic which we might know in advance that we are not going
559 /// to emit.
560 class OptionalDiagnostic {
561 PartialDiagnostic *Diag;
562
563 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000564 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
565 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000566
567 template<typename T>
568 OptionalDiagnostic &operator<<(const T &v) {
569 if (Diag)
570 *Diag << v;
571 return *this;
572 }
Richard Smithfe800032012-01-31 04:08:20 +0000573
574 OptionalDiagnostic &operator<<(const APSInt &I) {
575 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000576 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000577 I.toString(Buffer);
578 *Diag << StringRef(Buffer.data(), Buffer.size());
579 }
580 return *this;
581 }
582
583 OptionalDiagnostic &operator<<(const APFloat &F) {
584 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000585 // FIXME: Force the precision of the source value down so we don't
586 // print digits which are usually useless (we don't really care here if
587 // we truncate a digit by accident in edge cases). Ideally,
Fangrui Song6907ce22018-07-30 19:24:48 +0000588 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000589 // representation which rounds to the correct value, but it's a bit
590 // tricky to implement.
591 unsigned precision =
592 llvm::APFloat::semanticsPrecision(F.getSemantics());
593 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000594 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000595 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000596 *Diag << StringRef(Buffer.data(), Buffer.size());
597 }
598 return *this;
599 }
Leonard Chand3f3e162019-01-18 21:04:25 +0000600
601 OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
602 if (Diag) {
603 SmallVector<char, 32> Buffer;
604 FX.toString(Buffer);
605 *Diag << StringRef(Buffer.data(), Buffer.size());
606 }
607 return *this;
608 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000609 };
610
Richard Smith08d6a2c2013-07-24 07:11:57 +0000611 /// A cleanup, and a flag indicating whether it is lifetime-extended.
612 class Cleanup {
613 llvm::PointerIntPair<APValue*, 1, bool> Value;
614
615 public:
616 Cleanup(APValue *Val, bool IsLifetimeExtended)
617 : Value(Val, IsLifetimeExtended) {}
618
619 bool isLifetimeExtended() const { return Value.getInt(); }
620 void endLifetime() {
621 *Value.getPointer() = APValue();
622 }
623 };
624
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000625 /// A reference to an object whose construction we are currently evaluating.
626 struct ObjectUnderConstruction {
627 APValue::LValueBase Base;
628 ArrayRef<APValue::LValuePathEntry> Path;
629 friend bool operator==(const ObjectUnderConstruction &LHS,
630 const ObjectUnderConstruction &RHS) {
631 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
632 }
633 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
634 return llvm::hash_combine(Obj.Base, Obj.Path);
635 }
636 };
637 enum class ConstructionPhase { None, Bases, AfterBases };
638}
639
640namespace llvm {
641template<> struct DenseMapInfo<ObjectUnderConstruction> {
642 using Base = DenseMapInfo<APValue::LValueBase>;
643 static ObjectUnderConstruction getEmptyKey() {
644 return {Base::getEmptyKey(), {}}; }
645 static ObjectUnderConstruction getTombstoneKey() {
646 return {Base::getTombstoneKey(), {}};
647 }
648 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
649 return hash_value(Object);
650 }
651 static bool isEqual(const ObjectUnderConstruction &LHS,
652 const ObjectUnderConstruction &RHS) {
653 return LHS == RHS;
654 }
655};
656}
657
658namespace {
Richard Smithb228a862012-02-15 02:18:13 +0000659 /// EvalInfo - This is a private struct used by the evaluator to capture
660 /// information about a subexpression as it is folded. It retains information
661 /// about the AST context, but also maintains information about the folded
662 /// expression.
663 ///
664 /// If an expression could be evaluated, it is still possible it is not a C
665 /// "integer constant expression" or constant expression. If not, this struct
666 /// captures information about how and why not.
667 ///
668 /// One bit of information passed *into* the request for constant folding
669 /// indicates whether the subexpression is "evaluated" or not according to C
670 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
671 /// evaluate the expression regardless of what the RHS is, but C only allows
672 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000673 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000674 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000675
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000676 /// EvalStatus - Contains information about the evaluation.
677 Expr::EvalStatus &EvalStatus;
678
679 /// CurrentCall - The top of the constexpr call stack.
680 CallStackFrame *CurrentCall;
681
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000682 /// CallStackDepth - The number of calls in the call stack right now.
683 unsigned CallStackDepth;
684
Richard Smithb228a862012-02-15 02:18:13 +0000685 /// NextCallIndex - The next call index to assign.
686 unsigned NextCallIndex;
687
Richard Smitha3d3bd22013-05-08 02:12:03 +0000688 /// StepsLeft - The remaining number of evaluation steps we're permitted
689 /// to perform. This is essentially a limit for the number of statements
690 /// we will evaluate.
691 unsigned StepsLeft;
692
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000693 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000694 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000695 CallStackFrame BottomFrame;
696
Richard Smith08d6a2c2013-07-24 07:11:57 +0000697 /// A stack of values whose lifetimes end at the end of some surrounding
698 /// evaluation frame.
699 llvm::SmallVector<Cleanup, 16> CleanupStack;
700
Richard Smithd62306a2011-11-10 06:34:14 +0000701 /// EvaluatingDecl - This is the declaration whose initializer is being
702 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000703 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000704
705 /// EvaluatingDeclValue - This is the value being constructed for the
706 /// declaration whose initializer is being evaluated, if any.
707 APValue *EvaluatingDeclValue;
708
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000709 /// Set of objects that are currently being constructed.
710 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
711 ObjectsUnderConstruction;
Erik Pilkington42925492017-10-04 00:18:55 +0000712
713 struct EvaluatingConstructorRAII {
714 EvalInfo &EI;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000715 ObjectUnderConstruction Object;
Erik Pilkington42925492017-10-04 00:18:55 +0000716 bool DidInsert;
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000717 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
718 bool HasBases)
Erik Pilkington42925492017-10-04 00:18:55 +0000719 : EI(EI), Object(Object) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000720 DidInsert =
721 EI.ObjectsUnderConstruction
722 .insert({Object, HasBases ? ConstructionPhase::Bases
723 : ConstructionPhase::AfterBases})
724 .second;
725 }
726 void finishedConstructingBases() {
727 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
Erik Pilkington42925492017-10-04 00:18:55 +0000728 }
729 ~EvaluatingConstructorRAII() {
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000730 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
Erik Pilkington42925492017-10-04 00:18:55 +0000731 }
732 };
733
Richard Smithd3d6f4f2019-05-12 08:57:59 +0000734 ConstructionPhase
735 isEvaluatingConstructor(APValue::LValueBase Base,
736 ArrayRef<APValue::LValuePathEntry> Path) {
737 return ObjectsUnderConstruction.lookup({Base, Path});
Erik Pilkington42925492017-10-04 00:18:55 +0000738 }
739
Richard Smith37be3362019-05-04 04:00:45 +0000740 /// If we're currently speculatively evaluating, the outermost call stack
741 /// depth at which we can mutate state, otherwise 0.
742 unsigned SpeculativeEvaluationDepth = 0;
743
Richard Smith410306b2016-12-12 02:53:20 +0000744 /// The current array initialization index, if we're performing array
745 /// initialization.
746 uint64_t ArrayInitIndex = -1;
747
Richard Smith357362d2011-12-13 06:39:58 +0000748 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
749 /// notes attached to it will also be stored, otherwise they will not be.
750 bool HasActiveDiagnostic;
751
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000752 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000753 /// fold (not just why it's not strictly a constant expression)?
754 bool HasFoldFailureDiagnostic;
755
Fangrui Song407659a2018-11-30 23:41:18 +0000756 /// Whether or not we're in a context where the front end requires a
757 /// constant value.
758 bool InConstantContext;
759
Richard Smith6d4c6582013-11-05 22:18:15 +0000760 enum EvaluationMode {
761 /// Evaluate as a constant expression. Stop if we find that the expression
762 /// is not a constant expression.
763 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000764
Richard Smith6d4c6582013-11-05 22:18:15 +0000765 /// Evaluate as a potential constant expression. Keep going if we hit a
766 /// construct that we can't evaluate yet (because we don't yet know the
767 /// value of something) but stop if we hit something that could never be
768 /// a constant expression.
769 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000770
Richard Smith6d4c6582013-11-05 22:18:15 +0000771 /// Fold the expression to a constant. Stop if we hit a side-effect that
772 /// we can't model.
773 EM_ConstantFold,
774
775 /// Evaluate the expression looking for integer overflow and similar
776 /// issues. Don't worry about side-effects, and try to visit all
777 /// subexpressions.
778 EM_EvaluateForOverflow,
779
780 /// Evaluate in any way we know how. Don't worry about side-effects that
781 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000782 EM_IgnoreSideEffects,
783
784 /// Evaluate as a constant expression. Stop if we find that the expression
785 /// is not a constant expression. Some expressions can be retried in the
786 /// optimizer if we don't constant fold them here, but in an unevaluated
787 /// context we try to fold them immediately since the optimizer never
788 /// gets a chance to look at it.
789 EM_ConstantExpressionUnevaluated,
790
791 /// Evaluate as a potential constant expression. Keep going if we hit a
792 /// construct that we can't evaluate yet (because we don't yet know the
793 /// value of something) but stop if we hit something that could never be
794 /// a constant expression. Some expressions can be retried in the
795 /// optimizer if we don't constant fold them here, but in an unevaluated
796 /// context we try to fold them immediately since the optimizer never
797 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000798 EM_PotentialConstantExpressionUnevaluated,
Richard Smith6d4c6582013-11-05 22:18:15 +0000799 } EvalMode;
800
801 /// Are we checking whether the expression is a potential constant
802 /// expression?
803 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000804 return EvalMode == EM_PotentialConstantExpression ||
805 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000806 }
807
808 /// Are we checking an expression for overflow?
809 // FIXME: We should check for any kind of undefined or suspicious behavior
810 // in such constructs, not just overflow.
811 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
812
813 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000814 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000815 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000816 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000817 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
818 EvaluatingDecl((const ValueDecl *)nullptr),
819 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
Richard Smith37be3362019-05-04 04:00:45 +0000820 HasFoldFailureDiagnostic(false),
Fangrui Song407659a2018-11-30 23:41:18 +0000821 InConstantContext(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000822
Richard Smith7525ff62013-05-09 07:14:00 +0000823 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
824 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000825 EvaluatingDeclValue = &Value;
826 }
827
David Blaikiebbafb8a2012-03-11 07:00:24 +0000828 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000829
Richard Smith357362d2011-12-13 06:39:58 +0000830 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000831 // Don't perform any constexpr calls (other than the call we're checking)
832 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000833 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000834 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000835 if (NextCallIndex == 0) {
836 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000837 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000838 return false;
839 }
Richard Smith357362d2011-12-13 06:39:58 +0000840 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
841 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000842 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000843 << getLangOpts().ConstexprCallDepth;
844 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000845 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000846
Richard Smith37be3362019-05-04 04:00:45 +0000847 std::pair<CallStackFrame *, unsigned>
848 getCallFrameAndDepth(unsigned CallIndex) {
849 assert(CallIndex && "no call index in getCallFrameAndDepth");
Richard Smithb228a862012-02-15 02:18:13 +0000850 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
851 // be null in this loop.
Richard Smith37be3362019-05-04 04:00:45 +0000852 unsigned Depth = CallStackDepth;
Richard Smithb228a862012-02-15 02:18:13 +0000853 CallStackFrame *Frame = CurrentCall;
Richard Smith37be3362019-05-04 04:00:45 +0000854 while (Frame->Index > CallIndex) {
Richard Smithb228a862012-02-15 02:18:13 +0000855 Frame = Frame->Caller;
Richard Smith37be3362019-05-04 04:00:45 +0000856 --Depth;
857 }
858 if (Frame->Index == CallIndex)
859 return {Frame, Depth};
860 return {nullptr, 0};
Richard Smithb228a862012-02-15 02:18:13 +0000861 }
862
Richard Smitha3d3bd22013-05-08 02:12:03 +0000863 bool nextStep(const Stmt *S) {
864 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000865 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000866 return false;
867 }
868 --StepsLeft;
869 return true;
870 }
871
Richard Smith357362d2011-12-13 06:39:58 +0000872 private:
873 /// Add a diagnostic to the diagnostics list.
874 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
875 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
876 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
877 return EvalStatus.Diag->back().second;
878 }
879
Richard Smithf6f003a2011-12-16 19:06:07 +0000880 /// Add notes containing a call stack to the current point of evaluation.
881 void addCallStack(unsigned Limit);
882
Faisal Valie690b7a2016-07-02 22:34:24 +0000883 private:
884 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
885 unsigned ExtraNotes, bool IsCCEDiag) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000886
Richard Smith92b1ce02011-12-12 09:28:41 +0000887 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000888 // If we have a prior diagnostic, it will be noting that the expression
889 // isn't a constant expression. This diagnostic is more important,
890 // unless we require this evaluation to produce a constant expression.
891 //
892 // FIXME: We might want to show both diagnostics to the user in
893 // EM_ConstantFold mode.
894 if (!EvalStatus.Diag->empty()) {
895 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000896 case EM_ConstantFold:
897 case EM_IgnoreSideEffects:
898 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000899 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000900 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000901 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000902 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000903 case EM_ConstantExpression:
904 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000905 case EM_ConstantExpressionUnevaluated:
906 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000907 HasActiveDiagnostic = false;
908 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000909 }
910 }
911
Richard Smithf6f003a2011-12-16 19:06:07 +0000912 unsigned CallStackNotes = CallStackDepth - 1;
913 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
914 if (Limit)
915 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000916 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000917 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000918
Richard Smith357362d2011-12-13 06:39:58 +0000919 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000920 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000921 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000922 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
923 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000924 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000925 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000926 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000927 }
Richard Smith357362d2011-12-13 06:39:58 +0000928 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000929 return OptionalDiagnostic();
930 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000931 public:
932 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
933 OptionalDiagnostic
934 FFDiag(SourceLocation Loc,
935 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
936 unsigned ExtraNotes = 0) {
937 return Diag(Loc, DiagId, ExtraNotes, false);
938 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000939
Faisal Valie690b7a2016-07-02 22:34:24 +0000940 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000941 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000942 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000943 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000944 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000945 HasActiveDiagnostic = false;
946 return OptionalDiagnostic();
947 }
948
Richard Smith92b1ce02011-12-12 09:28:41 +0000949 /// Diagnose that the evaluation does not produce a C++11 core constant
950 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000951 ///
952 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
953 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000954 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000955 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000956 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000957 // Don't override a previous diagnostic. Don't bother collecting
958 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000959 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000960 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000961 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000962 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000963 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000964 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000965 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
966 = diag::note_invalid_subexpr_in_const_expr,
967 unsigned ExtraNotes = 0) {
968 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
969 }
Richard Smith357362d2011-12-13 06:39:58 +0000970 /// Add a note to a prior diagnostic.
971 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
972 if (!HasActiveDiagnostic)
973 return OptionalDiagnostic();
974 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000975 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000976
977 /// Add a stack of notes to a prior diagnostic.
978 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
979 if (HasActiveDiagnostic) {
980 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
981 Diags.begin(), Diags.end());
982 }
983 }
Richard Smith253c2a32012-01-27 01:14:48 +0000984
Richard Smith6d4c6582013-11-05 22:18:15 +0000985 /// Should we continue evaluation after encountering a side-effect that we
986 /// couldn't model?
987 bool keepEvaluatingAfterSideEffect() {
988 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000989 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000990 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000991 case EM_EvaluateForOverflow:
992 case EM_IgnoreSideEffects:
993 return true;
994
Richard Smith6d4c6582013-11-05 22:18:15 +0000995 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000996 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000997 case EM_ConstantFold:
998 return false;
999 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001000 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +00001001 }
1002
1003 /// Note that we have had a side-effect, and determine whether we should
1004 /// keep evaluating.
1005 bool noteSideEffect() {
1006 EvalStatus.HasSideEffects = true;
1007 return keepEvaluatingAfterSideEffect();
1008 }
1009
Richard Smithce8eca52015-12-08 03:21:47 +00001010 /// Should we continue evaluation after encountering undefined behavior?
1011 bool keepEvaluatingAfterUndefinedBehavior() {
1012 switch (EvalMode) {
1013 case EM_EvaluateForOverflow:
1014 case EM_IgnoreSideEffects:
1015 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +00001016 return true;
1017
1018 case EM_PotentialConstantExpression:
1019 case EM_PotentialConstantExpressionUnevaluated:
1020 case EM_ConstantExpression:
1021 case EM_ConstantExpressionUnevaluated:
1022 return false;
1023 }
1024 llvm_unreachable("Missed EvalMode case");
1025 }
1026
1027 /// Note that we hit something that was technically undefined behavior, but
1028 /// that we can evaluate past it (such as signed overflow or floating-point
1029 /// division by zero.)
1030 bool noteUndefinedBehavior() {
1031 EvalStatus.HasUndefinedBehavior = true;
1032 return keepEvaluatingAfterUndefinedBehavior();
1033 }
1034
Richard Smith253c2a32012-01-27 01:14:48 +00001035 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001036 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +00001037 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +00001038 if (!StepsLeft)
1039 return false;
1040
1041 switch (EvalMode) {
1042 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001043 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001044 case EM_EvaluateForOverflow:
1045 return true;
1046
1047 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001048 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001049 case EM_ConstantFold:
1050 case EM_IgnoreSideEffects:
1051 return false;
1052 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001053 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001054 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001055
George Burgess IV8c892b52016-05-25 22:31:54 +00001056 /// Notes that we failed to evaluate an expression that other expressions
1057 /// directly depend on, and determine if we should keep evaluating. This
1058 /// should only be called if we actually intend to keep evaluating.
1059 ///
1060 /// Call noteSideEffect() instead if we may be able to ignore the value that
1061 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1062 ///
1063 /// (Foo(), 1) // use noteSideEffect
1064 /// (Foo() || true) // use noteSideEffect
1065 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001066 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001067 // Failure when evaluating some expression often means there is some
1068 // subexpression whose evaluation was skipped. Therefore, (because we
1069 // don't track whether we skipped an expression when unwinding after an
1070 // evaluation failure) every evaluation failure that bubbles up from a
1071 // subexpression implies that a side-effect has potentially happened. We
1072 // skip setting the HasSideEffects flag to true until we decide to
1073 // continue evaluating after that point, which happens here.
1074 bool KeepGoing = keepEvaluatingAfterFailure();
1075 EvalStatus.HasSideEffects |= KeepGoing;
1076 return KeepGoing;
1077 }
1078
Richard Smith410306b2016-12-12 02:53:20 +00001079 class ArrayInitLoopIndex {
1080 EvalInfo &Info;
1081 uint64_t OuterIndex;
1082
1083 public:
1084 ArrayInitLoopIndex(EvalInfo &Info)
1085 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1086 Info.ArrayInitIndex = 0;
1087 }
1088 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1089
1090 operator uint64_t&() { return Info.ArrayInitIndex; }
1091 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001092 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001093
1094 /// Object used to treat all foldable expressions as constant expressions.
1095 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001096 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001097 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001098 bool HadNoPriorDiags;
1099 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001100
Richard Smith6d4c6582013-11-05 22:18:15 +00001101 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1102 : Info(Info),
1103 Enabled(Enabled),
1104 HadNoPriorDiags(Info.EvalStatus.Diag &&
1105 Info.EvalStatus.Diag->empty() &&
1106 !Info.EvalStatus.HasSideEffects),
1107 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001108 if (Enabled &&
1109 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1110 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001111 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001112 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001113 void keepDiagnostics() { Enabled = false; }
1114 ~FoldConstant() {
1115 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001116 !Info.EvalStatus.HasSideEffects)
1117 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001118 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001119 }
1120 };
Richard Smith17100ba2012-02-16 02:46:34 +00001121
James Y Knight892b09b2018-10-10 02:53:43 +00001122 /// RAII object used to set the current evaluation mode to ignore
1123 /// side-effects.
1124 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001125 EvalInfo &Info;
1126 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001127 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001128 : Info(Info), OldMode(Info.EvalMode) {
1129 if (!Info.checkingPotentialConstantExpression())
James Y Knight892b09b2018-10-10 02:53:43 +00001130 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001131 }
1132
James Y Knight892b09b2018-10-10 02:53:43 +00001133 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001134 };
1135
George Burgess IV8c892b52016-05-25 22:31:54 +00001136 /// RAII object used to optionally suppress diagnostics and side-effects from
1137 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001138 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001139 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001140 Expr::EvalStatus OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001141 unsigned OldSpeculativeEvaluationDepth;
Richard Smith17100ba2012-02-16 02:46:34 +00001142
George Burgess IV8c892b52016-05-25 22:31:54 +00001143 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001144 Info = Other.Info;
1145 OldStatus = Other.OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001146 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001147 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001148 }
1149
1150 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001151 if (!Info)
1152 return;
1153
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001154 Info->EvalStatus = OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001155 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
George Burgess IV8c892b52016-05-25 22:31:54 +00001156 }
1157
Richard Smith17100ba2012-02-16 02:46:34 +00001158 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001159 SpeculativeEvaluationRAII() = default;
1160
1161 SpeculativeEvaluationRAII(
1162 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001163 : Info(&Info), OldStatus(Info.EvalStatus),
Richard Smith37be3362019-05-04 04:00:45 +00001164 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
Richard Smith17100ba2012-02-16 02:46:34 +00001165 Info.EvalStatus.Diag = NewDiag;
Richard Smith37be3362019-05-04 04:00:45 +00001166 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
Richard Smith17100ba2012-02-16 02:46:34 +00001167 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001168
1169 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1170 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1171 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001172 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001173
1174 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1175 maybeRestoreState();
1176 moveFromAndCancel(std::move(Other));
1177 return *this;
1178 }
1179
1180 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001181 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001182
1183 /// RAII object wrapping a full-expression or block scope, and handling
1184 /// the ending of the lifetime of temporaries created within it.
1185 template<bool IsFullExpression>
1186 class ScopeRAII {
1187 EvalInfo &Info;
1188 unsigned OldStackSize;
1189 public:
1190 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001191 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1192 // Push a new temporary version. This is needed to distinguish between
1193 // temporaries created in different iterations of a loop.
1194 Info.CurrentCall->pushTempVersion();
1195 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001196 ~ScopeRAII() {
1197 // Body moved to a static method to encourage the compiler to inline away
1198 // instances of this class.
1199 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001200 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001201 }
1202 private:
1203 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1204 unsigned NewEnd = OldStackSize;
1205 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1206 I != N; ++I) {
1207 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1208 // Full-expression cleanup of a lifetime-extended temporary: nothing
1209 // to do, just move this cleanup to the right place in the stack.
1210 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1211 ++NewEnd;
1212 } else {
1213 // End the lifetime of the object.
1214 Info.CleanupStack[I].endLifetime();
1215 }
1216 }
1217 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1218 Info.CleanupStack.end());
1219 }
1220 };
1221 typedef ScopeRAII<false> BlockScopeRAII;
1222 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001223}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001224
Richard Smitha8105bc2012-01-06 16:39:00 +00001225bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1226 CheckSubobjectKind CSK) {
1227 if (Invalid)
1228 return false;
1229 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001230 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001231 << CSK;
1232 setInvalid();
1233 return false;
1234 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001235 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1236 // must actually be at least one array element; even a VLA cannot have a
1237 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001238 return true;
1239}
1240
Richard Smith6f4f0f12017-10-20 22:56:25 +00001241void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1242 const Expr *E) {
1243 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1244 // Do not set the designator as invalid: we can represent this situation,
1245 // and correct handling of __builtin_object_size requires us to do so.
1246}
1247
Richard Smitha8105bc2012-01-06 16:39:00 +00001248void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001249 const Expr *E,
1250 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001251 // If we're complaining, we must be able to statically determine the size of
1252 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001253 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001254 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001255 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001256 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001257 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001258 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001259 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001260 setInvalid();
1261}
1262
Richard Smithf6f003a2011-12-16 19:06:07 +00001263CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1264 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001265 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001266 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1267 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001268 Info.CurrentCall = this;
1269 ++Info.CallStackDepth;
1270}
1271
1272CallStackFrame::~CallStackFrame() {
1273 assert(Info.CurrentCall == this && "calls retired out of order");
1274 --Info.CallStackDepth;
1275 Info.CurrentCall = Caller;
1276}
1277
Richard Smith08d6a2c2013-07-24 07:11:57 +00001278APValue &CallStackFrame::createTemporary(const void *Key,
1279 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001280 unsigned Version = Info.CurrentCall->getTempVersion();
1281 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smith08d6a2c2013-07-24 07:11:57 +00001282 assert(Result.isUninit() && "temporary created multiple times");
1283 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1284 return Result;
1285}
1286
Richard Smith84401042013-06-03 05:03:02 +00001287static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001288
1289void EvalInfo::addCallStack(unsigned Limit) {
1290 // Determine which calls to skip, if any.
1291 unsigned ActiveCalls = CallStackDepth - 1;
1292 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1293 if (Limit && Limit < ActiveCalls) {
1294 SkipStart = Limit / 2 + Limit % 2;
1295 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001296 }
1297
Richard Smithf6f003a2011-12-16 19:06:07 +00001298 // Walk the call stack and add the diagnostics.
1299 unsigned CallIdx = 0;
1300 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1301 Frame = Frame->Caller, ++CallIdx) {
1302 // Skip this call?
1303 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1304 if (CallIdx == SkipStart) {
1305 // Note that we're skipping calls.
1306 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1307 << unsigned(ActiveCalls - Limit);
1308 }
1309 continue;
1310 }
1311
Richard Smith5179eb72016-06-28 19:03:57 +00001312 // Use a different note for an inheriting constructor, because from the
1313 // user's perspective it's not really a function at all.
1314 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1315 if (CD->isInheritingConstructor()) {
1316 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1317 << CD->getParent();
1318 continue;
1319 }
1320 }
1321
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001322 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001323 llvm::raw_svector_ostream Out(Buffer);
1324 describeCall(Frame, Out);
1325 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1326 }
1327}
1328
Richard Smithdebad642019-05-12 09:39:08 +00001329/// Kinds of access we can perform on an object, for diagnostics. Note that
1330/// we consider a member function call to be a kind of access, even though
1331/// it is not formally an access of the object, because it has (largely) the
1332/// same set of semantic restrictions.
Hubert Tong147b7432018-12-12 16:53:43 +00001333enum AccessKinds {
1334 AK_Read,
1335 AK_Assign,
1336 AK_Increment,
Richard Smithdebad642019-05-12 09:39:08 +00001337 AK_Decrement,
1338 AK_MemberCall,
Hubert Tong147b7432018-12-12 16:53:43 +00001339};
1340
Richard Smithdebad642019-05-12 09:39:08 +00001341static bool isModification(AccessKinds AK) {
1342 return AK != AK_Read && AK != AK_MemberCall;
1343}
1344
Richard Smithf6f003a2011-12-16 19:06:07 +00001345namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001346 struct ComplexValue {
1347 private:
1348 bool IsInt;
1349
1350 public:
1351 APSInt IntReal, IntImag;
1352 APFloat FloatReal, FloatImag;
1353
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001354 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001355
1356 void makeComplexFloat() { IsInt = false; }
1357 bool isComplexFloat() const { return !IsInt; }
1358 APFloat &getComplexFloatReal() { return FloatReal; }
1359 APFloat &getComplexFloatImag() { return FloatImag; }
1360
1361 void makeComplexInt() { IsInt = true; }
1362 bool isComplexInt() const { return IsInt; }
1363 APSInt &getComplexIntReal() { return IntReal; }
1364 APSInt &getComplexIntImag() { return IntImag; }
1365
Richard Smith2e312c82012-03-03 22:46:17 +00001366 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001367 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001368 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001369 else
Richard Smith2e312c82012-03-03 22:46:17 +00001370 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001371 }
Richard Smith2e312c82012-03-03 22:46:17 +00001372 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001373 assert(v.isComplexFloat() || v.isComplexInt());
1374 if (v.isComplexFloat()) {
1375 makeComplexFloat();
1376 FloatReal = v.getComplexFloatReal();
1377 FloatImag = v.getComplexFloatImag();
1378 } else {
1379 makeComplexInt();
1380 IntReal = v.getComplexIntReal();
1381 IntImag = v.getComplexIntImag();
1382 }
1383 }
John McCall93d91dc2010-05-07 17:22:02 +00001384 };
John McCall45d55e42010-05-07 21:00:08 +00001385
1386 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001387 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001388 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001389 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001390 bool IsNullPtr : 1;
1391 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001392
Richard Smithce40ad62011-11-12 22:28:03 +00001393 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001394 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001395 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001396 SubobjectDesignator &getLValueDesignator() { return Designator; }
1397 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001398 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001399
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001400 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1401 unsigned getLValueVersion() const { return Base.getVersion(); }
1402
Richard Smith2e312c82012-03-03 22:46:17 +00001403 void moveInto(APValue &V) const {
1404 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001405 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001406 else {
1407 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001408 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001409 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001410 }
John McCall45d55e42010-05-07 21:00:08 +00001411 }
Richard Smith2e312c82012-03-03 22:46:17 +00001412 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001413 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001414 Base = V.getLValueBase();
1415 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001416 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001417 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001418 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001419 }
1420
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001421 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001422#ifndef NDEBUG
1423 // We only allow a few types of invalid bases. Enforce that here.
1424 if (BInvalid) {
1425 const auto *E = B.get<const Expr *>();
1426 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1427 "Unexpected type of invalid base");
1428 }
1429#endif
1430
Richard Smithce40ad62011-11-12 22:28:03 +00001431 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001432 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001433 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001434 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001435 IsNullPtr = false;
1436 }
1437
1438 void setNull(QualType PointerTy, uint64_t TargetVal) {
1439 Base = (Expr *)nullptr;
1440 Offset = CharUnits::fromQuantity(TargetVal);
1441 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001442 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1443 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001444 }
1445
George Burgess IV3a03fab2015-09-04 21:28:13 +00001446 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001447 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001448 }
1449
Hubert Tong147b7432018-12-12 16:53:43 +00001450 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001451 // Check that this LValue is not based on a null pointer. If it is, produce
1452 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001453 template <typename GenDiagType>
1454 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001455 if (Designator.Invalid)
1456 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001457 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001458 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001459 Designator.setInvalid();
1460 return false;
1461 }
1462 return true;
1463 }
1464
Hubert Tong147b7432018-12-12 16:53:43 +00001465 public:
1466 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1467 CheckSubobjectKind CSK) {
1468 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1469 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1470 });
1471 }
1472
1473 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1474 AccessKinds AK) {
1475 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1476 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1477 });
1478 }
1479
Richard Smitha8105bc2012-01-06 16:39:00 +00001480 // Check this LValue refers to an object. If not, set the designator to be
1481 // invalid and emit a diagnostic.
1482 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001483 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001484 Designator.checkSubobject(Info, E, CSK);
1485 }
1486
1487 void addDecl(EvalInfo &Info, const Expr *E,
1488 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001489 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1490 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001491 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001492 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1493 if (!Designator.Entries.empty()) {
1494 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1495 Designator.setInvalid();
1496 return;
1497 }
Richard Smithefdb5032017-11-15 03:03:56 +00001498 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1499 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1500 Designator.FirstEntryIsAnUnsizedArray = true;
1501 Designator.addUnsizedArrayUnchecked(ElemTy);
1502 }
George Burgess IVe3763372016-12-22 02:50:20 +00001503 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001504 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001505 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1506 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001507 }
Richard Smith66c96992012-02-18 22:04:06 +00001508 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001509 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1510 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001511 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001512 void clearIsNullPointer() {
1513 IsNullPtr = false;
1514 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001515 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1516 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001517 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1518 // but we're not required to diagnose it and it's valid in C++.)
1519 if (!Index)
1520 return;
1521
1522 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1523 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1524 // offsets.
1525 uint64_t Offset64 = Offset.getQuantity();
1526 uint64_t ElemSize64 = ElementSize.getQuantity();
1527 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1528 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1529
1530 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001531 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001532 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001533 }
1534 void adjustOffset(CharUnits N) {
1535 Offset += N;
1536 if (N.getQuantity())
1537 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001538 }
John McCall45d55e42010-05-07 21:00:08 +00001539 };
Richard Smith027bf112011-11-17 22:56:20 +00001540
1541 struct MemberPtr {
1542 MemberPtr() {}
1543 explicit MemberPtr(const ValueDecl *Decl) :
1544 DeclAndIsDerivedMember(Decl, false), Path() {}
1545
1546 /// The member or (direct or indirect) field referred to by this member
1547 /// pointer, or 0 if this is a null member pointer.
1548 const ValueDecl *getDecl() const {
1549 return DeclAndIsDerivedMember.getPointer();
1550 }
1551 /// Is this actually a member of some type derived from the relevant class?
1552 bool isDerivedMember() const {
1553 return DeclAndIsDerivedMember.getInt();
1554 }
1555 /// Get the class which the declaration actually lives in.
1556 const CXXRecordDecl *getContainingRecord() const {
1557 return cast<CXXRecordDecl>(
1558 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1559 }
1560
Richard Smith2e312c82012-03-03 22:46:17 +00001561 void moveInto(APValue &V) const {
1562 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001563 }
Richard Smith2e312c82012-03-03 22:46:17 +00001564 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001565 assert(V.isMemberPointer());
1566 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1567 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1568 Path.clear();
1569 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1570 Path.insert(Path.end(), P.begin(), P.end());
1571 }
1572
1573 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1574 /// whether the member is a member of some class derived from the class type
1575 /// of the member pointer.
1576 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1577 /// Path - The path of base/derived classes from the member declaration's
1578 /// class (exclusive) to the class type of the member pointer (inclusive).
1579 SmallVector<const CXXRecordDecl*, 4> Path;
1580
1581 /// Perform a cast towards the class of the Decl (either up or down the
1582 /// hierarchy).
1583 bool castBack(const CXXRecordDecl *Class) {
1584 assert(!Path.empty());
1585 const CXXRecordDecl *Expected;
1586 if (Path.size() >= 2)
1587 Expected = Path[Path.size() - 2];
1588 else
1589 Expected = getContainingRecord();
1590 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1591 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1592 // if B does not contain the original member and is not a base or
1593 // derived class of the class containing the original member, the result
1594 // of the cast is undefined.
1595 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1596 // (D::*). We consider that to be a language defect.
1597 return false;
1598 }
1599 Path.pop_back();
1600 return true;
1601 }
1602 /// Perform a base-to-derived member pointer cast.
1603 bool castToDerived(const CXXRecordDecl *Derived) {
1604 if (!getDecl())
1605 return true;
1606 if (!isDerivedMember()) {
1607 Path.push_back(Derived);
1608 return true;
1609 }
1610 if (!castBack(Derived))
1611 return false;
1612 if (Path.empty())
1613 DeclAndIsDerivedMember.setInt(false);
1614 return true;
1615 }
1616 /// Perform a derived-to-base member pointer cast.
1617 bool castToBase(const CXXRecordDecl *Base) {
1618 if (!getDecl())
1619 return true;
1620 if (Path.empty())
1621 DeclAndIsDerivedMember.setInt(true);
1622 if (isDerivedMember()) {
1623 Path.push_back(Base);
1624 return true;
1625 }
1626 return castBack(Base);
1627 }
1628 };
Richard Smith357362d2011-12-13 06:39:58 +00001629
Richard Smith7bb00672012-02-01 01:42:44 +00001630 /// Compare two member pointers, which are assumed to be of the same type.
1631 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1632 if (!LHS.getDecl() || !RHS.getDecl())
1633 return !LHS.getDecl() && !RHS.getDecl();
1634 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1635 return false;
1636 return LHS.Path == RHS.Path;
1637 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001638}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001639
Richard Smith2e312c82012-03-03 22:46:17 +00001640static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001641static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1642 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001643 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001644static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1645 bool InvalidBaseOK = false);
1646static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1647 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001648static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1649 EvalInfo &Info);
1650static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001651static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001652static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001653 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001654static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001655static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001656static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1657 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001658static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001659
Leonard Chand3f3e162019-01-18 21:04:25 +00001660/// Evaluate an integer or fixed point expression into an APResult.
1661static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1662 EvalInfo &Info);
1663
1664/// Evaluate only a fixed point expression into an APResult.
1665static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1666 EvalInfo &Info);
1667
Chris Lattner05706e882008-07-11 18:11:29 +00001668//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001669// Misc utilities
1670//===----------------------------------------------------------------------===//
1671
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001672/// A helper function to create a temporary and set an LValue.
1673template <class KeyTy>
1674static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1675 LValue &LV, CallStackFrame &Frame) {
1676 LV.set({Key, Frame.Info.CurrentCall->Index,
1677 Frame.Info.CurrentCall->getTempVersion()});
1678 return Frame.createTemporary(Key, IsLifetimeExtended);
1679}
1680
Richard Smithd6cc1982017-01-31 02:23:02 +00001681/// Negate an APSInt in place, converting it to a signed form if necessary, and
1682/// preserving its value (by extending by up to one bit as needed).
1683static void negateAsSigned(APSInt &Int) {
1684 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1685 Int = Int.extend(Int.getBitWidth() + 1);
1686 Int.setIsSigned(true);
1687 }
1688 Int = -Int;
1689}
1690
Richard Smith84401042013-06-03 05:03:02 +00001691/// Produce a string describing the given constexpr call.
1692static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1693 unsigned ArgIndex = 0;
1694 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1695 !isa<CXXConstructorDecl>(Frame->Callee) &&
1696 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1697
1698 if (!IsMemberCall)
1699 Out << *Frame->Callee << '(';
1700
1701 if (Frame->This && IsMemberCall) {
1702 APValue Val;
1703 Frame->This->moveInto(Val);
1704 Val.printPretty(Out, Frame->Info.Ctx,
1705 Frame->This->Designator.MostDerivedType);
1706 // FIXME: Add parens around Val if needed.
1707 Out << "->" << *Frame->Callee << '(';
1708 IsMemberCall = false;
1709 }
1710
1711 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1712 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1713 if (ArgIndex > (unsigned)IsMemberCall)
1714 Out << ", ";
1715
1716 const ParmVarDecl *Param = *I;
1717 const APValue &Arg = Frame->Arguments[ArgIndex];
1718 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1719
1720 if (ArgIndex == 0 && IsMemberCall)
1721 Out << "->" << *Frame->Callee << '(';
1722 }
1723
1724 Out << ')';
1725}
1726
Richard Smithd9f663b2013-04-22 15:31:51 +00001727/// Evaluate an expression to see if it had side-effects, and discard its
1728/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001729/// \return \c true if the caller should keep evaluating.
1730static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001731 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001732 if (!Evaluate(Scratch, Info, E))
1733 // We don't need the value, but we might have skipped a side effect here.
1734 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001735 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001736}
1737
Richard Smithd62306a2011-11-10 06:34:14 +00001738/// Should this call expression be treated as a string literal?
1739static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001740 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001741 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1742 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1743}
1744
Richard Smithce40ad62011-11-12 22:28:03 +00001745static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001746 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1747 // constant expression of pointer type that evaluates to...
1748
1749 // ... a null pointer value, or a prvalue core constant expression of type
1750 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001751 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001752
Richard Smithce40ad62011-11-12 22:28:03 +00001753 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1754 // ... the address of an object with static storage duration,
1755 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1756 return VD->hasGlobalStorage();
1757 // ... the address of a function,
1758 return isa<FunctionDecl>(D);
1759 }
1760
1761 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001762 switch (E->getStmtClass()) {
1763 default:
1764 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001765 case Expr::CompoundLiteralExprClass: {
1766 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1767 return CLE->isFileScope() && CLE->isLValue();
1768 }
Richard Smithe6c01442013-06-05 00:46:14 +00001769 case Expr::MaterializeTemporaryExprClass:
1770 // A materialized temporary might have been lifetime-extended to static
1771 // storage duration.
1772 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001773 // A string literal has static storage duration.
1774 case Expr::StringLiteralClass:
1775 case Expr::PredefinedExprClass:
1776 case Expr::ObjCStringLiteralClass:
1777 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001778 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001779 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001780 return true;
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001781 case Expr::ObjCBoxedExprClass:
1782 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
Richard Smithd62306a2011-11-10 06:34:14 +00001783 case Expr::CallExprClass:
1784 return IsStringLiteralCall(cast<CallExpr>(E));
1785 // For GCC compatibility, &&label has static storage duration.
1786 case Expr::AddrLabelExprClass:
1787 return true;
1788 // A Block literal expression may be used as the initialization value for
1789 // Block variables at global or local static scope.
1790 case Expr::BlockExprClass:
1791 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001792 case Expr::ImplicitValueInitExprClass:
1793 // FIXME:
1794 // We can never form an lvalue with an implicit value initialization as its
1795 // base through expression evaluation, so these only appear in one case: the
1796 // implicit variable declaration we invent when checking whether a constexpr
1797 // constructor can produce a constant expression. We must assume that such
1798 // an expression might be a global lvalue.
1799 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001800 }
John McCall95007602010-05-10 23:27:23 +00001801}
1802
Richard Smith06f71b52018-08-04 00:57:17 +00001803static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1804 return LVal.Base.dyn_cast<const ValueDecl*>();
1805}
1806
1807static bool IsLiteralLValue(const LValue &Value) {
1808 if (Value.getLValueCallIndex())
1809 return false;
1810 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1811 return E && !isa<MaterializeTemporaryExpr>(E);
1812}
1813
1814static bool IsWeakLValue(const LValue &Value) {
1815 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1816 return Decl && Decl->isWeak();
1817}
1818
1819static bool isZeroSized(const LValue &Value) {
1820 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1821 if (Decl && isa<VarDecl>(Decl)) {
1822 QualType Ty = Decl->getType();
1823 if (Ty->isArrayType())
1824 return Ty->isIncompleteType() ||
1825 Decl->getASTContext().getTypeSize(Ty) == 0;
1826 }
1827 return false;
1828}
1829
1830static bool HasSameBase(const LValue &A, const LValue &B) {
1831 if (!A.getLValueBase())
1832 return !B.getLValueBase();
1833 if (!B.getLValueBase())
1834 return false;
1835
1836 if (A.getLValueBase().getOpaqueValue() !=
1837 B.getLValueBase().getOpaqueValue()) {
1838 const Decl *ADecl = GetLValueBaseDecl(A);
1839 if (!ADecl)
1840 return false;
1841 const Decl *BDecl = GetLValueBaseDecl(B);
1842 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1843 return false;
1844 }
1845
1846 return IsGlobalLValue(A.getLValueBase()) ||
1847 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1848 A.getLValueVersion() == B.getLValueVersion());
1849}
1850
Richard Smithb228a862012-02-15 02:18:13 +00001851static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1852 assert(Base && "no location for a null lvalue");
1853 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1854 if (VD)
1855 Info.Note(VD->getLocation(), diag::note_declared_at);
1856 else
Ted Kremenek28831752012-08-23 20:46:57 +00001857 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001858 diag::note_constexpr_temporary_here);
1859}
1860
Richard Smith80815602011-11-07 05:07:52 +00001861/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001862/// value for an address or reference constant expression. Return true if we
1863/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001864static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001865 QualType Type, const LValue &LVal,
1866 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001867 bool IsReferenceType = Type->isReferenceType();
1868
Richard Smith357362d2011-12-13 06:39:58 +00001869 APValue::LValueBase Base = LVal.getLValueBase();
1870 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1871
Richard Smith0dea49e2012-02-18 04:58:18 +00001872 // Check that the object is a global. Note that the fake 'this' object we
1873 // manufacture when checking potential constant expressions is conservatively
1874 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001875 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001876 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001877 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001878 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001879 << IsReferenceType << !Designator.Entries.empty()
1880 << !!VD << VD;
1881 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001882 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001883 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001884 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001885 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001886 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001887 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001888 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001889 LVal.getLValueCallIndex() == 0) &&
1890 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001891
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001892 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1893 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001894 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001895 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001896 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001897
Hans Wennborg82dd8772014-06-25 22:19:48 +00001898 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001899 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001900 return false;
1901 }
1902 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1903 // __declspec(dllimport) must be handled very carefully:
1904 // We must never initialize an expression with the thunk in C++.
1905 // Doing otherwise would allow the same id-expression to yield
1906 // different addresses for the same function in different translation
1907 // units. However, this means that we must dynamically initialize the
1908 // expression with the contents of the import address table at runtime.
1909 //
1910 // The C language has no notion of ODR; furthermore, it has no notion of
1911 // dynamic initialization. This means that we are permitted to
1912 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001913 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1914 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001915 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001916 }
1917 }
1918
Richard Smitha8105bc2012-01-06 16:39:00 +00001919 // Allow address constant expressions to be past-the-end pointers. This is
1920 // an extension: the standard requires them to point to an object.
1921 if (!IsReferenceType)
1922 return true;
1923
1924 // A reference constant expression must refer to an object.
1925 if (!Base) {
1926 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001927 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001928 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001929 }
1930
Richard Smith357362d2011-12-13 06:39:58 +00001931 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001932 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001933 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001934 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001935 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001936 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001937 }
1938
Richard Smith80815602011-11-07 05:07:52 +00001939 return true;
1940}
1941
Reid Klecknercd016d82017-07-07 22:04:29 +00001942/// Member pointers are constant expressions unless they point to a
1943/// non-virtual dllimport member function.
1944static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1945 SourceLocation Loc,
1946 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001947 const APValue &Value,
1948 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00001949 const ValueDecl *Member = Value.getMemberPointerDecl();
1950 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1951 if (!FD)
1952 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001953 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1954 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00001955}
1956
Richard Smithfddd3842011-12-30 21:15:51 +00001957/// Check that this core constant expression is of literal type, and if not,
1958/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001959static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001960 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001961 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001962 return true;
1963
Richard Smith7525ff62013-05-09 07:14:00 +00001964 // C++1y: A constant initializer for an object o [...] may also invoke
1965 // constexpr constructors for o and its subobjects even if those objects
1966 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001967 //
1968 // C++11 missed this detail for aggregates, so classes like this:
1969 // struct foo_t { union { int i; volatile int j; } u; };
1970 // are not (obviously) initializable like so:
1971 // __attribute__((__require_constant_initialization__))
1972 // static const foo_t x = {{0}};
1973 // because "i" is a subobject with non-literal initialization (due to the
1974 // volatile member of the union). See:
1975 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1976 // Therefore, we use the C++1y behavior.
1977 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001978 return true;
1979
Richard Smithfddd3842011-12-30 21:15:51 +00001980 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001981 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001982 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001983 << E->getType();
1984 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001985 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001986 return false;
1987}
1988
Richard Smith0b0a0b62011-10-29 20:57:55 +00001989/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001990/// constant expression. If not, report an appropriate diagnostic. Does not
1991/// check that the expression is of literal type.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001992static bool
1993CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1994 const APValue &Value,
1995 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
Richard Smith1a90f592013-06-18 17:51:51 +00001996 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001997 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001998 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001999 return false;
2000 }
2001
Richard Smith77be48a2014-07-31 06:31:19 +00002002 // We allow _Atomic(T) to be initialized from anything that T can be
2003 // initialized from.
2004 if (const AtomicType *AT = Type->getAs<AtomicType>())
2005 Type = AT->getValueType();
2006
Richard Smithb228a862012-02-15 02:18:13 +00002007 // Core issue 1454: For a literal constant expression of array or class type,
2008 // each subobject of its value shall have been initialized by a constant
2009 // expression.
2010 if (Value.isArray()) {
2011 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2012 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2013 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
Reid Kleckner1a840d22018-05-10 18:57:35 +00002014 Value.getArrayInitializedElt(I), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00002015 return false;
2016 }
2017 if (!Value.hasArrayFiller())
2018 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002019 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
2020 Usage);
Richard Smith80815602011-11-07 05:07:52 +00002021 }
Richard Smithb228a862012-02-15 02:18:13 +00002022 if (Value.isUnion() && Value.getUnionField()) {
2023 return CheckConstantExpression(Info, DiagLoc,
2024 Value.getUnionField()->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00002025 Value.getUnionValue(), Usage);
Richard Smithb228a862012-02-15 02:18:13 +00002026 }
2027 if (Value.isStruct()) {
2028 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2029 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2030 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002031 for (const CXXBaseSpecifier &BS : CD->bases()) {
2032 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
2033 Value.getStructBase(BaseIndex), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00002034 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002035 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00002036 }
2037 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002038 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00002039 if (I->isUnnamedBitfield())
2040 continue;
2041
David Blaikie2d7c57e2012-04-30 02:36:29 +00002042 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00002043 Value.getStructField(I->getFieldIndex()),
2044 Usage))
Richard Smithb228a862012-02-15 02:18:13 +00002045 return false;
2046 }
2047 }
2048
2049 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00002050 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00002051 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00002052 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00002053 }
2054
Reid Klecknercd016d82017-07-07 22:04:29 +00002055 if (Value.isMemberPointer())
Reid Kleckner1a840d22018-05-10 18:57:35 +00002056 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00002057
Richard Smithb228a862012-02-15 02:18:13 +00002058 // Everything else is fine.
2059 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002060}
2061
Richard Smith2e312c82012-03-03 22:46:17 +00002062static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00002063 // A null base expression indicates a null pointer. These are always
2064 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00002065 if (!Value.getLValueBase()) {
2066 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002067 return true;
2068 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002069
Richard Smith027bf112011-11-17 22:56:20 +00002070 // We have a non-null base. These are generally known to be true, but if it's
2071 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002072 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002073 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002074 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002075}
2076
Richard Smith2e312c82012-03-03 22:46:17 +00002077static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002078 switch (Val.getKind()) {
2079 case APValue::Uninitialized:
2080 return false;
2081 case APValue::Int:
2082 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002083 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00002084 case APValue::FixedPoint:
2085 Result = Val.getFixedPoint().getBoolValue();
2086 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002087 case APValue::Float:
2088 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002089 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002090 case APValue::ComplexInt:
2091 Result = Val.getComplexIntReal().getBoolValue() ||
2092 Val.getComplexIntImag().getBoolValue();
2093 return true;
2094 case APValue::ComplexFloat:
2095 Result = !Val.getComplexFloatReal().isZero() ||
2096 !Val.getComplexFloatImag().isZero();
2097 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002098 case APValue::LValue:
2099 return EvalPointerValueAsBool(Val, Result);
2100 case APValue::MemberPointer:
2101 Result = Val.getMemberPointerDecl();
2102 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002103 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002104 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002105 case APValue::Struct:
2106 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002107 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002108 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002109 }
2110
Richard Smith11562c52011-10-28 17:51:58 +00002111 llvm_unreachable("unknown APValue kind");
2112}
2113
2114static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2115 EvalInfo &Info) {
2116 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002117 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002118 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002119 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002120 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002121}
2122
Richard Smith357362d2011-12-13 06:39:58 +00002123template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002124static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002125 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002126 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002127 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002128 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002129}
2130
2131static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2132 QualType SrcType, const APFloat &Value,
2133 QualType DestType, APSInt &Result) {
2134 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002135 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002136 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002137
Richard Smith357362d2011-12-13 06:39:58 +00002138 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002139 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002140 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2141 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002142 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002143 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002144}
2145
Richard Smith357362d2011-12-13 06:39:58 +00002146static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2147 QualType SrcType, QualType DestType,
2148 APFloat &Result) {
2149 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002150 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002151 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2152 APFloat::rmNearestTiesToEven, &ignored)
2153 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002154 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002155 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002156}
2157
Richard Smith911e1422012-01-30 22:27:01 +00002158static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2159 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002160 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002161 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002162 // Figure out if this is a truncate, extend or noop cast.
2163 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002164 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002165 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002166 if (DestType->isBooleanType())
2167 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002168 return Result;
2169}
2170
Richard Smith357362d2011-12-13 06:39:58 +00002171static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2172 QualType SrcType, const APSInt &Value,
2173 QualType DestType, APFloat &Result) {
2174 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2175 if (Result.convertFromAPInt(Value, Value.isSigned(),
2176 APFloat::rmNearestTiesToEven)
2177 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002178 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002179 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002180}
2181
Richard Smith49ca8aa2013-08-06 07:09:20 +00002182static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2183 APValue &Value, const FieldDecl *FD) {
2184 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2185
2186 if (!Value.isInt()) {
2187 // Trying to store a pointer-cast-to-integer into a bitfield.
2188 // FIXME: In this case, we should provide the diagnostic for casting
2189 // a pointer to an integer.
2190 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002191 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002192 return false;
2193 }
2194
2195 APSInt &Int = Value.getInt();
2196 unsigned OldBitWidth = Int.getBitWidth();
2197 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2198 if (NewBitWidth < OldBitWidth)
2199 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2200 return true;
2201}
2202
Eli Friedman803acb32011-12-22 03:51:45 +00002203static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2204 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002205 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002206 if (!Evaluate(SVal, Info, E))
2207 return false;
2208 if (SVal.isInt()) {
2209 Res = SVal.getInt();
2210 return true;
2211 }
2212 if (SVal.isFloat()) {
2213 Res = SVal.getFloat().bitcastToAPInt();
2214 return true;
2215 }
2216 if (SVal.isVector()) {
2217 QualType VecTy = E->getType();
2218 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2219 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2220 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2221 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2222 Res = llvm::APInt::getNullValue(VecSize);
2223 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2224 APValue &Elt = SVal.getVectorElt(i);
2225 llvm::APInt EltAsInt;
2226 if (Elt.isInt()) {
2227 EltAsInt = Elt.getInt();
2228 } else if (Elt.isFloat()) {
2229 EltAsInt = Elt.getFloat().bitcastToAPInt();
2230 } else {
2231 // Don't try to handle vectors of anything other than int or float
2232 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002233 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002234 return false;
2235 }
2236 unsigned BaseEltSize = EltAsInt.getBitWidth();
2237 if (BigEndian)
2238 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2239 else
2240 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2241 }
2242 return true;
2243 }
2244 // Give up if the input isn't an int, float, or vector. For example, we
2245 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002246 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002247 return false;
2248}
2249
Richard Smith43e77732013-05-07 04:50:00 +00002250/// Perform the given integer operation, which is known to need at most BitWidth
2251/// bits, and check for overflow in the original type (if that type was not an
2252/// unsigned type).
2253template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002254static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2255 const APSInt &LHS, const APSInt &RHS,
2256 unsigned BitWidth, Operation Op,
2257 APSInt &Result) {
2258 if (LHS.isUnsigned()) {
2259 Result = Op(LHS, RHS);
2260 return true;
2261 }
Richard Smith43e77732013-05-07 04:50:00 +00002262
2263 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002264 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002265 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002266 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002267 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002268 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002269 << Result.toString(10) << E->getType();
2270 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002271 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002272 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002273 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002274}
2275
2276/// Perform the given binary integer operation.
2277static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2278 BinaryOperatorKind Opcode, APSInt RHS,
2279 APSInt &Result) {
2280 switch (Opcode) {
2281 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002282 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002283 return false;
2284 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002285 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2286 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002287 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002288 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2289 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002290 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002291 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2292 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002293 case BO_And: Result = LHS & RHS; return true;
2294 case BO_Xor: Result = LHS ^ RHS; return true;
2295 case BO_Or: Result = LHS | RHS; return true;
2296 case BO_Div:
2297 case BO_Rem:
2298 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002299 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002300 return false;
2301 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002302 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2303 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2304 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002305 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2306 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002307 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2308 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002309 return true;
2310 case BO_Shl: {
2311 if (Info.getLangOpts().OpenCL)
2312 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2313 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2314 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2315 RHS.isUnsigned());
2316 else if (RHS.isSigned() && RHS.isNegative()) {
2317 // During constant-folding, a negative shift is an opposite shift. Such
2318 // a shift is not a constant expression.
2319 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2320 RHS = -RHS;
2321 goto shift_right;
2322 }
2323 shift_left:
2324 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2325 // the shifted type.
2326 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2327 if (SA != RHS) {
2328 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2329 << RHS << E->getType() << LHS.getBitWidth();
2330 } else if (LHS.isSigned()) {
2331 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2332 // operand, and must not overflow the corresponding unsigned type.
2333 if (LHS.isNegative())
2334 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2335 else if (LHS.countLeadingZeros() < SA)
2336 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2337 }
2338 Result = LHS << SA;
2339 return true;
2340 }
2341 case BO_Shr: {
2342 if (Info.getLangOpts().OpenCL)
2343 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2344 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2345 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2346 RHS.isUnsigned());
2347 else if (RHS.isSigned() && RHS.isNegative()) {
2348 // During constant-folding, a negative shift is an opposite shift. Such a
2349 // shift is not a constant expression.
2350 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2351 RHS = -RHS;
2352 goto shift_left;
2353 }
2354 shift_right:
2355 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2356 // shifted type.
2357 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2358 if (SA != RHS)
2359 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2360 << RHS << E->getType() << LHS.getBitWidth();
2361 Result = LHS >> SA;
2362 return true;
2363 }
2364
2365 case BO_LT: Result = LHS < RHS; return true;
2366 case BO_GT: Result = LHS > RHS; return true;
2367 case BO_LE: Result = LHS <= RHS; return true;
2368 case BO_GE: Result = LHS >= RHS; return true;
2369 case BO_EQ: Result = LHS == RHS; return true;
2370 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002371 case BO_Cmp:
2372 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002373 }
2374}
2375
Richard Smith861b5b52013-05-07 23:34:45 +00002376/// Perform the given binary floating-point operation, in-place, on LHS.
2377static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2378 APFloat &LHS, BinaryOperatorKind Opcode,
2379 const APFloat &RHS) {
2380 switch (Opcode) {
2381 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002382 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002383 return false;
2384 case BO_Mul:
2385 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2386 break;
2387 case BO_Add:
2388 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2389 break;
2390 case BO_Sub:
2391 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2392 break;
2393 case BO_Div:
2394 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2395 break;
2396 }
2397
Richard Smith0c6124b2015-12-03 01:36:22 +00002398 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002399 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002400 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002401 }
Richard Smith861b5b52013-05-07 23:34:45 +00002402 return true;
2403}
2404
Richard Smitha8105bc2012-01-06 16:39:00 +00002405/// Cast an lvalue referring to a base subobject to a derived class, by
2406/// truncating the lvalue's path to the given length.
2407static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2408 const RecordDecl *TruncatedType,
2409 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002410 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002411
2412 // Check we actually point to a derived class object.
2413 if (TruncatedElements == D.Entries.size())
2414 return true;
2415 assert(TruncatedElements >= D.MostDerivedPathLength &&
2416 "not casting to a derived class");
2417 if (!Result.checkSubobject(Info, E, CSK_Derived))
2418 return false;
2419
2420 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002421 const RecordDecl *RD = TruncatedType;
2422 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002423 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002424 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2425 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002426 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002427 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002428 else
Richard Smithd62306a2011-11-10 06:34:14 +00002429 Result.Offset -= Layout.getBaseClassOffset(Base);
2430 RD = Base;
2431 }
Richard Smith027bf112011-11-17 22:56:20 +00002432 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002433 return true;
2434}
2435
John McCalld7bca762012-05-01 00:38:49 +00002436static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002437 const CXXRecordDecl *Derived,
2438 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002439 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002440 if (!RL) {
2441 if (Derived->isInvalidDecl()) return false;
2442 RL = &Info.Ctx.getASTRecordLayout(Derived);
2443 }
2444
Richard Smithd62306a2011-11-10 06:34:14 +00002445 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002446 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002447 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002448}
2449
Richard Smitha8105bc2012-01-06 16:39:00 +00002450static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002451 const CXXRecordDecl *DerivedDecl,
2452 const CXXBaseSpecifier *Base) {
2453 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2454
John McCalld7bca762012-05-01 00:38:49 +00002455 if (!Base->isVirtual())
2456 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002457
Richard Smitha8105bc2012-01-06 16:39:00 +00002458 SubobjectDesignator &D = Obj.Designator;
2459 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002460 return false;
2461
Richard Smitha8105bc2012-01-06 16:39:00 +00002462 // Extract most-derived object and corresponding type.
2463 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2464 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2465 return false;
2466
2467 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002468 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002469 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2470 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002471 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002472 return true;
2473}
2474
Richard Smith84401042013-06-03 05:03:02 +00002475static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2476 QualType Type, LValue &Result) {
2477 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2478 PathE = E->path_end();
2479 PathI != PathE; ++PathI) {
2480 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2481 *PathI))
2482 return false;
2483 Type = (*PathI)->getType();
2484 }
2485 return true;
2486}
2487
Richard Smithd62306a2011-11-10 06:34:14 +00002488/// Update LVal to refer to the given field, which must be a member of the type
2489/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002490static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002491 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002492 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002493 if (!RL) {
2494 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002495 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002496 }
Richard Smithd62306a2011-11-10 06:34:14 +00002497
2498 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002499 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002500 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002501 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002502}
2503
Richard Smith1b78b3d2012-01-25 22:15:11 +00002504/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002505static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002506 LValue &LVal,
2507 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002508 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002509 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002510 return false;
2511 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002512}
2513
Richard Smithd62306a2011-11-10 06:34:14 +00002514/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002515static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2516 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002517 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2518 // extension.
2519 if (Type->isVoidType() || Type->isFunctionType()) {
2520 Size = CharUnits::One();
2521 return true;
2522 }
2523
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002524 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002525 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002526 return false;
2527 }
2528
Richard Smithd62306a2011-11-10 06:34:14 +00002529 if (!Type->isConstantSizeType()) {
2530 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002531 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002532 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002533 return false;
2534 }
2535
2536 Size = Info.Ctx.getTypeSizeInChars(Type);
2537 return true;
2538}
2539
2540/// Update a pointer value to model pointer arithmetic.
2541/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002542/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002543/// \param LVal - The pointer value to be updated.
2544/// \param EltTy - The pointee type represented by LVal.
2545/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002546static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2547 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002548 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002549 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002550 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002551 return false;
2552
Yaxun Liu402804b2016-12-15 08:09:08 +00002553 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002554 return true;
2555}
2556
Richard Smithd6cc1982017-01-31 02:23:02 +00002557static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2558 LValue &LVal, QualType EltTy,
2559 int64_t Adjustment) {
2560 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2561 APSInt::get(Adjustment));
2562}
2563
Richard Smith66c96992012-02-18 22:04:06 +00002564/// Update an lvalue to refer to a component of a complex number.
2565/// \param Info - Information about the ongoing evaluation.
2566/// \param LVal - The lvalue to be updated.
2567/// \param EltTy - The complex number's component type.
2568/// \param Imag - False for the real component, true for the imaginary.
2569static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2570 LValue &LVal, QualType EltTy,
2571 bool Imag) {
2572 if (Imag) {
2573 CharUnits SizeOfComponent;
2574 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2575 return false;
2576 LVal.Offset += SizeOfComponent;
2577 }
2578 LVal.addComplex(Info, E, EltTy, Imag);
2579 return true;
2580}
2581
Faisal Vali051e3a22017-02-16 04:12:21 +00002582static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2583 QualType Type, const LValue &LVal,
2584 APValue &RVal);
2585
Richard Smith27908702011-10-24 17:54:18 +00002586/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002587///
2588/// \param Info Information about the ongoing evaluation.
2589/// \param E An expression to be used when printing diagnostics.
2590/// \param VD The variable whose initializer should be obtained.
2591/// \param Frame The frame in which the variable was created. Must be null
2592/// if this variable is not local to the evaluation.
2593/// \param Result Filled in with a pointer to the value of the variable.
2594static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2595 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002596 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002597
Richard Smith254a73d2011-10-28 22:34:42 +00002598 // If this is a parameter to an active constexpr function call, perform
2599 // argument substitution.
2600 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002601 // Assume arguments of a potential constant expression are unknown
2602 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002603 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002604 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002605 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002606 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002607 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002608 }
Richard Smith3229b742013-05-05 21:17:10 +00002609 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002610 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002611 }
Richard Smith27908702011-10-24 17:54:18 +00002612
Richard Smithd9f663b2013-04-22 15:31:51 +00002613 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002614 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002615 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2616 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002617 if (!Result) {
2618 // Assume variables referenced within a lambda's call operator that were
2619 // not declared within the call operator are captures and during checking
2620 // of a potential constant expression, assume they are unknown constant
2621 // expressions.
2622 assert(isLambdaCallOperator(Frame->Callee) &&
2623 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2624 "missing value for local variable");
2625 if (Info.checkingPotentialConstantExpression())
2626 return false;
2627 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002628 Info.FFDiag(E->getBeginLoc(),
2629 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002630 << "captures not currently allowed";
2631 return false;
2632 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002633 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002634 }
2635
Richard Smithd0b4dd62011-12-19 06:19:21 +00002636 // Dig out the initializer, and use the declaration which it's attached to.
2637 const Expr *Init = VD->getAnyInitializer(VD);
2638 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002639 // If we're checking a potential constant expression, the variable could be
2640 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002641 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002642 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002643 return false;
2644 }
2645
Richard Smithd62306a2011-11-10 06:34:14 +00002646 // If we're currently evaluating the initializer of this declaration, use that
2647 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002648 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002649 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002650 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002651 }
2652
Richard Smithcecf1842011-11-01 21:06:14 +00002653 // Never evaluate the initializer of a weak variable. We can't be sure that
2654 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002655 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002656 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002657 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002658 }
Richard Smithcecf1842011-11-01 21:06:14 +00002659
Richard Smithd0b4dd62011-12-19 06:19:21 +00002660 // Check that we can fold the initializer. In C++, we will have already done
2661 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002662 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002663 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002664 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002665 Notes.size() + 1) << VD;
2666 Info.Note(VD->getLocation(), diag::note_declared_at);
2667 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002668 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002669 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002670 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002671 Notes.size() + 1) << VD;
2672 Info.Note(VD->getLocation(), diag::note_declared_at);
2673 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002674 }
Richard Smith27908702011-10-24 17:54:18 +00002675
Richard Smith3229b742013-05-05 21:17:10 +00002676 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002677 return true;
Richard Smith27908702011-10-24 17:54:18 +00002678}
2679
Richard Smith11562c52011-10-28 17:51:58 +00002680static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002681 Qualifiers Quals = T.getQualifiers();
2682 return Quals.hasConst() && !Quals.hasVolatile();
2683}
2684
Richard Smithe97cbd72011-11-11 04:05:33 +00002685/// Get the base index of the given base class within an APValue representing
2686/// the given derived class.
2687static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2688 const CXXRecordDecl *Base) {
2689 Base = Base->getCanonicalDecl();
2690 unsigned Index = 0;
2691 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2692 E = Derived->bases_end(); I != E; ++I, ++Index) {
2693 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2694 return Index;
2695 }
2696
2697 llvm_unreachable("base class missing from derived class's bases list");
2698}
2699
Richard Smith3da88fa2013-04-26 14:36:30 +00002700/// Extract the value of a character from a string literal.
2701static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2702 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002703 // FIXME: Support MakeStringConstant
2704 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2705 std::string Str;
2706 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2707 assert(Index <= Str.size() && "Index too large");
2708 return APSInt::getUnsigned(Str.c_str()[Index]);
2709 }
2710
Alexey Bataevec474782014-10-09 08:45:04 +00002711 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2712 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002713 const StringLiteral *S = cast<StringLiteral>(Lit);
2714 const ConstantArrayType *CAT =
2715 Info.Ctx.getAsConstantArrayType(S->getType());
2716 assert(CAT && "string literal isn't an array");
2717 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002718 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002719
2720 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002721 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002722 if (Index < S->getLength())
2723 Value = S->getCodeUnit(Index);
2724 return Value;
2725}
2726
Richard Smith3da88fa2013-04-26 14:36:30 +00002727// Expand a string literal into an array of characters.
Eli Friedman3bf72d72019-02-08 21:18:46 +00002728//
2729// FIXME: This is inefficient; we should probably introduce something similar
2730// to the LLVM ConstantDataArray to make this cheaper.
2731static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
Richard Smith3da88fa2013-04-26 14:36:30 +00002732 APValue &Result) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002733 const ConstantArrayType *CAT =
2734 Info.Ctx.getAsConstantArrayType(S->getType());
2735 assert(CAT && "string literal isn't an array");
2736 QualType CharType = CAT->getElementType();
2737 assert(CharType->isIntegerType() && "unexpected character type");
2738
2739 unsigned Elts = CAT->getSize().getZExtValue();
2740 Result = APValue(APValue::UninitArray(),
2741 std::min(S->getLength(), Elts), Elts);
2742 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2743 CharType->isUnsignedIntegerType());
2744 if (Result.hasArrayFiller())
2745 Result.getArrayFiller() = APValue(Value);
2746 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2747 Value = S->getCodeUnit(I);
2748 Result.getArrayInitializedElt(I) = APValue(Value);
2749 }
2750}
2751
2752// Expand an array so that it has more than Index filled elements.
2753static void expandArray(APValue &Array, unsigned Index) {
2754 unsigned Size = Array.getArraySize();
2755 assert(Index < Size);
2756
2757 // Always at least double the number of elements for which we store a value.
2758 unsigned OldElts = Array.getArrayInitializedElts();
2759 unsigned NewElts = std::max(Index+1, OldElts * 2);
2760 NewElts = std::min(Size, std::max(NewElts, 8u));
2761
2762 // Copy the data across.
2763 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2764 for (unsigned I = 0; I != OldElts; ++I)
2765 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2766 for (unsigned I = OldElts; I != NewElts; ++I)
2767 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2768 if (NewValue.hasArrayFiller())
2769 NewValue.getArrayFiller() = Array.getArrayFiller();
2770 Array.swap(NewValue);
2771}
2772
Richard Smithb01fe402014-09-16 01:24:02 +00002773/// Determine whether a type would actually be read by an lvalue-to-rvalue
2774/// conversion. If it's of class type, we may assume that the copy operation
2775/// is trivial. Note that this is never true for a union type with fields
2776/// (because the copy always "reads" the active member) and always true for
2777/// a non-class type.
2778static bool isReadByLvalueToRvalueConversion(QualType T) {
2779 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2780 if (!RD || (RD->isUnion() && !RD->field_empty()))
2781 return true;
2782 if (RD->isEmpty())
2783 return false;
2784
2785 for (auto *Field : RD->fields())
2786 if (isReadByLvalueToRvalueConversion(Field->getType()))
2787 return true;
2788
2789 for (auto &BaseSpec : RD->bases())
2790 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2791 return true;
2792
2793 return false;
2794}
2795
2796/// Diagnose an attempt to read from any unreadable field within the specified
2797/// type, which might be a class type.
2798static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2799 QualType T) {
2800 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2801 if (!RD)
2802 return false;
2803
2804 if (!RD->hasMutableFields())
2805 return false;
2806
2807 for (auto *Field : RD->fields()) {
2808 // If we're actually going to read this field in some way, then it can't
2809 // be mutable. If we're in a union, then assigning to a mutable field
2810 // (even an empty one) can change the active member, so that's not OK.
2811 // FIXME: Add core issue number for the union case.
2812 if (Field->isMutable() &&
2813 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002814 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002815 Info.Note(Field->getLocation(), diag::note_declared_at);
2816 return true;
2817 }
2818
2819 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2820 return true;
2821 }
2822
2823 for (auto &BaseSpec : RD->bases())
2824 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2825 return true;
2826
2827 // All mutable fields were empty, and thus not actually read.
2828 return false;
2829}
2830
Richard Smithdebad642019-05-12 09:39:08 +00002831static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2832 APValue::LValueBase Base) {
2833 // A temporary we created.
2834 if (Base.getCallIndex())
2835 return true;
2836
2837 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2838 if (!Evaluating)
2839 return false;
2840
2841 // The variable whose initializer we're evaluating.
2842 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2843 if (declaresSameEntity(Evaluating, BaseD))
2844 return true;
2845
2846 // A temporary lifetime-extended by the variable whose initializer we're
2847 // evaluating.
2848 if (auto *BaseE = Base.dyn_cast<const Expr *>())
2849 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2850 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2851 return true;
2852
2853 return false;
2854}
2855
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002856namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002857/// A handle to a complete object (an object that is not a subobject of
2858/// another object).
2859struct CompleteObject {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002860 /// The identity of the object.
2861 APValue::LValueBase Base;
Richard Smith3229b742013-05-05 21:17:10 +00002862 /// The value of the complete object.
2863 APValue *Value;
2864 /// The type of the complete object.
2865 QualType Type;
2866
Craig Topper36250ad2014-05-12 05:36:57 +00002867 CompleteObject() : Value(nullptr) {}
Richard Smithdebad642019-05-12 09:39:08 +00002868 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2869 : Base(Base), Value(Value), Type(Type) {}
2870
2871 bool mayReadMutableMembers(EvalInfo &Info) const {
2872 // In C++14 onwards, it is permitted to read a mutable member whose
2873 // lifetime began within the evaluation.
2874 // FIXME: Should we also allow this in C++11?
2875 if (!Info.getLangOpts().CPlusPlus14)
2876 return false;
2877 return lifetimeStartedInEvaluation(Info, Base);
Richard Smith3229b742013-05-05 21:17:10 +00002878 }
2879
Richard Smithdebad642019-05-12 09:39:08 +00002880 explicit operator bool() const { return !Type.isNull(); }
Richard Smith3229b742013-05-05 21:17:10 +00002881};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002882} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002883
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002884static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2885 bool IsMutable = false) {
2886 // C++ [basic.type.qualifier]p1:
2887 // - A const object is an object of type const T or a non-mutable subobject
2888 // of a const object.
2889 if (ObjType.isConstQualified() && !IsMutable)
2890 SubobjType.addConst();
2891 // - A volatile object is an object of type const T or a subobject of a
2892 // volatile object.
2893 if (ObjType.isVolatileQualified())
2894 SubobjType.addVolatile();
2895 return SubobjType;
2896}
2897
Richard Smith3da88fa2013-04-26 14:36:30 +00002898/// Find the designated sub-object of an rvalue.
2899template<typename SubobjectHandler>
2900typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002901findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002902 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002903 if (Sub.Invalid)
2904 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002905 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002906 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002907 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002908 Info.FFDiag(E, Sub.isOnePastTheEnd()
2909 ? diag::note_constexpr_access_past_end
2910 : diag::note_constexpr_access_unsized_array)
2911 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002912 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002913 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002914 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002915 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002916
Richard Smith3229b742013-05-05 21:17:10 +00002917 APValue *O = Obj.Value;
2918 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002919 const FieldDecl *LastField = nullptr;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002920 const FieldDecl *VolatileField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002921
Richard Smithd62306a2011-11-10 06:34:14 +00002922 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002923 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2924 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002925 if (!Info.checkingPotentialConstantExpression())
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002926 Info.FFDiag(E, diag::note_constexpr_access_uninit)
2927 << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002928 return handler.failed();
2929 }
2930
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002931 // C++ [class.ctor]p5:
2932 // const and volatile semantics are not applied on an object under
2933 // construction.
2934 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
2935 ObjType->isRecordType() &&
2936 Info.isEvaluatingConstructor(
2937 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
2938 Sub.Entries.begin() + I)) !=
2939 ConstructionPhase::None) {
2940 ObjType = Info.Ctx.getCanonicalType(ObjType);
2941 ObjType.removeLocalConst();
2942 ObjType.removeLocalVolatile();
2943 }
2944
2945 // If this is our last pass, check that the final object type is OK.
2946 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
2947 // Accesses to volatile objects are prohibited.
Richard Smithdebad642019-05-12 09:39:08 +00002948 if (ObjType.isVolatileQualified() &&
2949 handler.AccessKind != AK_MemberCall) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002950 if (Info.getLangOpts().CPlusPlus) {
2951 int DiagKind;
2952 SourceLocation Loc;
2953 const NamedDecl *Decl = nullptr;
2954 if (VolatileField) {
2955 DiagKind = 2;
2956 Loc = VolatileField->getLocation();
2957 Decl = VolatileField;
2958 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
2959 DiagKind = 1;
2960 Loc = VD->getLocation();
2961 Decl = VD;
2962 } else {
2963 DiagKind = 0;
2964 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
2965 Loc = E->getExprLoc();
2966 }
2967 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2968 << handler.AccessKind << DiagKind << Decl;
2969 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
2970 } else {
2971 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2972 }
2973 return handler.failed();
2974 }
2975
Richard Smithb01fe402014-09-16 01:24:02 +00002976 // If we are reading an object of class type, there may still be more
2977 // things we need to check: if there are any mutable subobjects, we
2978 // cannot perform this read. (This only happens when performing a trivial
2979 // copy or assignment.)
2980 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smithdebad642019-05-12 09:39:08 +00002981 !Obj.mayReadMutableMembers(Info) &&
2982 diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002983 return handler.failed();
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002984 }
Richard Smithb01fe402014-09-16 01:24:02 +00002985
Richard Smithd3d6f4f2019-05-12 08:57:59 +00002986 if (I == N) {
Richard Smith49ca8aa2013-08-06 07:09:20 +00002987 if (!handler.found(*O, ObjType))
2988 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002989
Richard Smith49ca8aa2013-08-06 07:09:20 +00002990 // If we modified a bit-field, truncate it to the right width.
Richard Smithdebad642019-05-12 09:39:08 +00002991 if (isModification(handler.AccessKind) &&
Richard Smith49ca8aa2013-08-06 07:09:20 +00002992 LastField && LastField->isBitField() &&
2993 !truncateBitfieldValue(Info, E, *O, LastField))
2994 return false;
2995
2996 return true;
2997 }
2998
Craig Topper36250ad2014-05-12 05:36:57 +00002999 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00003000 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00003001 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00003002 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003003 assert(CAT && "vla in literal type?");
Richard Smith5b5e27a2019-05-10 20:05:31 +00003004 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003005 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00003006 // Note, it should not be possible to form a pointer with a valid
3007 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00003008 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003009 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003010 << handler.AccessKind;
3011 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003012 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003013 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003014 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003015
3016 ObjType = CAT->getElementType();
3017
Richard Smith3da88fa2013-04-26 14:36:30 +00003018 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00003019 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00003020 else if (handler.AccessKind != AK_Read) {
3021 expandArray(*O, Index);
3022 O = &O->getArrayInitializedElt(Index);
3023 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00003024 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00003025 } else if (ObjType->isAnyComplexType()) {
3026 // Next subobject is a complex number.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003027 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
Richard Smith66c96992012-02-18 22:04:06 +00003028 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003029 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00003030 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00003031 << handler.AccessKind;
3032 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003033 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003034 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00003035 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003036
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003037 ObjType = getSubobjectType(
3038 ObjType, ObjType->castAs<ComplexType>()->getElementType());
Richard Smith3da88fa2013-04-26 14:36:30 +00003039
Richard Smith66c96992012-02-18 22:04:06 +00003040 assert(I == N - 1 && "extracting subobject of scalar?");
3041 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003042 return handler.found(Index ? O->getComplexIntImag()
3043 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003044 } else {
3045 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00003046 return handler.found(Index ? O->getComplexFloatImag()
3047 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00003048 }
Richard Smithd62306a2011-11-10 06:34:14 +00003049 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00003050 if (Field->isMutable() && handler.AccessKind == AK_Read &&
Richard Smithdebad642019-05-12 09:39:08 +00003051 !Obj.mayReadMutableMembers(Info)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003052 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00003053 << Field;
3054 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00003055 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00003056 }
3057
Richard Smithd62306a2011-11-10 06:34:14 +00003058 // Next subobject is a class, struct or union field.
3059 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3060 if (RD->isUnion()) {
3061 const FieldDecl *UnionField = O->getUnionField();
3062 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00003063 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003064 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00003065 << handler.AccessKind << Field << !UnionField << UnionField;
3066 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003067 }
Richard Smithd62306a2011-11-10 06:34:14 +00003068 O = &O->getUnionValue();
3069 } else
3070 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00003071
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003072 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
Richard Smith49ca8aa2013-08-06 07:09:20 +00003073 LastField = Field;
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003074 if (Field->getType().isVolatileQualified())
3075 VolatileField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00003076 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00003077 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00003078 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3079 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3080 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00003081
Richard Smithd3d6f4f2019-05-12 08:57:59 +00003082 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
Richard Smithf3e9e432011-11-07 09:22:26 +00003083 }
3084 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003085}
3086
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003087namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003088struct ExtractSubobjectHandler {
3089 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00003090 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00003091
3092 static const AccessKinds AccessKind = AK_Read;
3093
3094 typedef bool result_type;
3095 bool failed() { return false; }
3096 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003097 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00003098 return true;
3099 }
3100 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003101 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003102 return true;
3103 }
3104 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003105 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003106 return true;
3107 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003108};
Richard Smith3229b742013-05-05 21:17:10 +00003109} // end anonymous namespace
3110
Richard Smith3da88fa2013-04-26 14:36:30 +00003111const AccessKinds ExtractSubobjectHandler::AccessKind;
3112
3113/// Extract the designated sub-object of an rvalue.
3114static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003115 const CompleteObject &Obj,
3116 const SubobjectDesignator &Sub,
3117 APValue &Result) {
3118 ExtractSubobjectHandler Handler = { Info, Result };
3119 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003120}
3121
Richard Smith3229b742013-05-05 21:17:10 +00003122namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003123struct ModifySubobjectHandler {
3124 EvalInfo &Info;
3125 APValue &NewVal;
3126 const Expr *E;
3127
3128 typedef bool result_type;
3129 static const AccessKinds AccessKind = AK_Assign;
3130
3131 bool checkConst(QualType QT) {
3132 // Assigning to a const object has undefined behavior.
3133 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003134 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003135 return false;
3136 }
3137 return true;
3138 }
3139
3140 bool failed() { return false; }
3141 bool found(APValue &Subobj, QualType SubobjType) {
3142 if (!checkConst(SubobjType))
3143 return false;
3144 // We've been given ownership of NewVal, so just swap it in.
3145 Subobj.swap(NewVal);
3146 return true;
3147 }
3148 bool found(APSInt &Value, QualType SubobjType) {
3149 if (!checkConst(SubobjType))
3150 return false;
3151 if (!NewVal.isInt()) {
3152 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003153 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003154 return false;
3155 }
3156 Value = NewVal.getInt();
3157 return true;
3158 }
3159 bool found(APFloat &Value, QualType SubobjType) {
3160 if (!checkConst(SubobjType))
3161 return false;
3162 Value = NewVal.getFloat();
3163 return true;
3164 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003165};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003166} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003167
Richard Smith3229b742013-05-05 21:17:10 +00003168const AccessKinds ModifySubobjectHandler::AccessKind;
3169
Richard Smith3da88fa2013-04-26 14:36:30 +00003170/// Update the designated sub-object of an rvalue to the given value.
3171static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003172 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003173 const SubobjectDesignator &Sub,
3174 APValue &NewVal) {
3175 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003176 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003177}
3178
Richard Smith84f6dcf2012-02-02 01:16:57 +00003179/// Find the position where two subobject designators diverge, or equivalently
3180/// the length of the common initial subsequence.
3181static unsigned FindDesignatorMismatch(QualType ObjType,
3182 const SubobjectDesignator &A,
3183 const SubobjectDesignator &B,
3184 bool &WasArrayIndex) {
3185 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3186 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003187 if (!ObjType.isNull() &&
3188 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003189 // Next subobject is an array element.
Richard Smith5b5e27a2019-05-10 20:05:31 +00003190 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003191 WasArrayIndex = true;
3192 return I;
3193 }
Richard Smith66c96992012-02-18 22:04:06 +00003194 if (ObjType->isAnyComplexType())
3195 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3196 else
3197 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003198 } else {
Richard Smith5b5e27a2019-05-10 20:05:31 +00003199 if (A.Entries[I].getAsBaseOrMember() !=
3200 B.Entries[I].getAsBaseOrMember()) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003201 WasArrayIndex = false;
3202 return I;
3203 }
3204 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3205 // Next subobject is a field.
3206 ObjType = FD->getType();
3207 else
3208 // Next subobject is a base class.
3209 ObjType = QualType();
3210 }
3211 }
3212 WasArrayIndex = false;
3213 return I;
3214}
3215
3216/// Determine whether the given subobject designators refer to elements of the
3217/// same array object.
3218static bool AreElementsOfSameArray(QualType ObjType,
3219 const SubobjectDesignator &A,
3220 const SubobjectDesignator &B) {
3221 if (A.Entries.size() != B.Entries.size())
3222 return false;
3223
George Burgess IVa51c4072015-10-16 01:49:01 +00003224 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003225 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3226 // A is a subobject of the array element.
3227 return false;
3228
3229 // If A (and B) designates an array element, the last entry will be the array
3230 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3231 // of length 1' case, and the entire path must match.
3232 bool WasArrayIndex;
3233 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3234 return CommonLength >= A.Entries.size() - IsArray;
3235}
3236
Richard Smith3229b742013-05-05 21:17:10 +00003237/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003238static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3239 AccessKinds AK, const LValue &LVal,
3240 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003241 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003242 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003243 return CompleteObject();
3244 }
3245
Craig Topper36250ad2014-05-12 05:36:57 +00003246 CallStackFrame *Frame = nullptr;
Richard Smith37be3362019-05-04 04:00:45 +00003247 unsigned Depth = 0;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003248 if (LVal.getLValueCallIndex()) {
Richard Smith37be3362019-05-04 04:00:45 +00003249 std::tie(Frame, Depth) =
3250 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003251 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003252 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003253 << AK << LVal.Base.is<const ValueDecl*>();
3254 NoteLValueLocation(Info, LVal.Base);
3255 return CompleteObject();
3256 }
Richard Smith3229b742013-05-05 21:17:10 +00003257 }
3258
3259 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3260 // is not a constant expression (even if the object is non-volatile). We also
3261 // apply this rule to C++98, in order to conform to the expected 'volatile'
3262 // semantics.
Richard Smithdebad642019-05-12 09:39:08 +00003263 if (AK != AK_MemberCall && LValType.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003264 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003265 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003266 << AK << LValType;
3267 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003268 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003269 return CompleteObject();
3270 }
3271
Richard Smithdebad642019-05-12 09:39:08 +00003272 // The wording is unclear on this, but for the purpose of determining the
3273 // validity of a member function call, we assume that all objects whose
3274 // lifetimes did not start within the constant evaluation are in fact within
3275 // their lifetimes, so member calls on them are valid. (This simultaneously
3276 // includes all members of a union!)
3277 bool NeedValue = AK != AK_MemberCall;
3278
Richard Smith3229b742013-05-05 21:17:10 +00003279 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003280 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003281 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00003282
3283 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3284 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3285 // In C++11, constexpr, non-volatile variables initialized with constant
3286 // expressions are constant expressions too. Inside constexpr functions,
3287 // parameters are constant expressions even if they're non-const.
3288 // In C++1y, objects local to a constant expression (those with a Frame) are
3289 // both readable and writable inside constant expressions.
3290 // In C, such things can also be folded, although they are not ICEs.
3291 const VarDecl *VD = dyn_cast<VarDecl>(D);
3292 if (VD) {
3293 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3294 VD = VDef;
3295 }
3296 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003297 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003298 return CompleteObject();
3299 }
3300
Richard Smith3229b742013-05-05 21:17:10 +00003301 // Unless we're looking at a local variable or argument in a constexpr call,
3302 // the variable we're reading must be const.
3303 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003304 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smithdebad642019-05-12 09:39:08 +00003305 declaresSameEntity(
3306 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003307 // OK, we can read and modify an object if we're in the process of
3308 // evaluating its initializer, because its lifetime began in this
3309 // evaluation.
Richard Smithdebad642019-05-12 09:39:08 +00003310 } else if (isModification(AK)) {
3311 // All the remaining cases do not permit modification of the object.
Faisal Valie690b7a2016-07-02 22:34:24 +00003312 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003313 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003314 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003315 // OK, we can read this variable.
3316 } else if (BaseType->isIntegralOrEnumerationType()) {
Richard Smithdebad642019-05-12 09:39:08 +00003317 // In OpenCL if a variable is in constant address space it is a const
3318 // value.
Xiuli Pan244e3f62016-06-07 04:34:00 +00003319 if (!(BaseType.isConstQualified() ||
3320 (Info.getLangOpts().OpenCL &&
3321 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smithdebad642019-05-12 09:39:08 +00003322 if (!NeedValue)
3323 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003324 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003325 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003326 Info.Note(VD->getLocation(), diag::note_declared_at);
3327 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003328 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003329 }
3330 return CompleteObject();
3331 }
Richard Smithdebad642019-05-12 09:39:08 +00003332 } else if (!NeedValue) {
3333 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003334 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3335 // We support folding of const floating-point types, in order to make
3336 // static const data members of such types (supported as an extension)
3337 // more useful.
3338 if (Info.getLangOpts().CPlusPlus11) {
3339 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3340 Info.Note(VD->getLocation(), diag::note_declared_at);
3341 } else {
3342 Info.CCEDiag(E);
3343 }
George Burgess IVb5316982016-12-27 05:33:20 +00003344 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3345 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3346 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003347 } else {
3348 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003349 if (Info.checkingPotentialConstantExpression() &&
3350 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3351 // The definition of this variable could be constexpr. We can't
3352 // access it right now, but may be able to in future.
3353 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003354 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003355 Info.Note(VD->getLocation(), diag::note_declared_at);
3356 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003357 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003358 }
3359 return CompleteObject();
3360 }
3361 }
3362
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003363 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003364 return CompleteObject();
3365 } else {
3366 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3367
3368 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003369 if (const MaterializeTemporaryExpr *MTE =
3370 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3371 assert(MTE->getStorageDuration() == SD_Static &&
3372 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003373
Richard Smithe6c01442013-06-05 00:46:14 +00003374 // Per C++1y [expr.const]p2:
3375 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3376 // - a [...] glvalue of integral or enumeration type that refers to
3377 // a non-volatile const object [...]
3378 // [...]
3379 // - a [...] glvalue of literal type that refers to a non-volatile
3380 // object whose lifetime began within the evaluation of e.
3381 //
3382 // C++11 misses the 'began within the evaluation of e' check and
3383 // instead allows all temporaries, including things like:
3384 // int &&r = 1;
3385 // int x = ++r;
3386 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003387 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003388 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3389 const ValueDecl *ED = MTE->getExtendingDecl();
3390 if (!(BaseType.isConstQualified() &&
3391 BaseType->isIntegralOrEnumerationType()) &&
3392 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Richard Smithdebad642019-05-12 09:39:08 +00003393 if (!NeedValue)
3394 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Faisal Valie690b7a2016-07-02 22:34:24 +00003395 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003396 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3397 return CompleteObject();
3398 }
3399
3400 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3401 assert(BaseVal && "got reference to unevaluated temporary");
3402 } else {
Richard Smithdebad642019-05-12 09:39:08 +00003403 if (!NeedValue)
3404 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
Faisal Valie690b7a2016-07-02 22:34:24 +00003405 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003406 return CompleteObject();
3407 }
3408 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003409 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003410 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003411 }
Richard Smith7525ff62013-05-09 07:14:00 +00003412 }
3413
Richard Smith9defb7d2018-02-21 03:38:30 +00003414 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003415 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003416 //
3417 // FIXME: Not all local state is mutable. Allow local constant subobjects
3418 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003419 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3420 Info.EvalStatus.HasSideEffects) ||
Richard Smithdebad642019-05-12 09:39:08 +00003421 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
Richard Smith3229b742013-05-05 21:17:10 +00003422 return CompleteObject();
3423
Richard Smithdebad642019-05-12 09:39:08 +00003424 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
Richard Smith3229b742013-05-05 21:17:10 +00003425}
3426
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003427/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003428/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3429/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003430///
3431/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003432/// \param Conv - The expression for which we are performing the conversion.
3433/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003434/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3435/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003436/// \param LVal - The glvalue on which we are attempting to perform this action.
3437/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003438static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003439 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003440 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003441 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003442 return false;
3443
Richard Smith3229b742013-05-05 21:17:10 +00003444 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003445 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003446 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003447 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3448 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3449 // initializer until now for such expressions. Such an expression can't be
3450 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003451 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003452 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003453 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003454 }
Richard Smith3229b742013-05-05 21:17:10 +00003455 APValue Lit;
3456 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3457 return false;
Richard Smithdebad642019-05-12 09:39:08 +00003458 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
Richard Smith3229b742013-05-05 21:17:10 +00003459 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003460 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00003461 // Special-case character extraction so we don't have to construct an
3462 // APValue for the whole string.
Eli Friedman041adb02019-02-09 02:22:17 +00003463 assert(LVal.Designator.Entries.size() <= 1 &&
Eli Friedman3bf72d72019-02-08 21:18:46 +00003464 "Can only read characters from string literals");
Eli Friedman041adb02019-02-09 02:22:17 +00003465 if (LVal.Designator.Entries.empty()) {
3466 // Fail for now for LValue to RValue conversion of an array.
3467 // (This shouldn't show up in C/C++, but it could be triggered by a
3468 // weird EvaluateAsRValue call from a tool.)
3469 Info.FFDiag(Conv);
3470 return false;
3471 }
Eli Friedman3bf72d72019-02-08 21:18:46 +00003472 if (LVal.Designator.isOnePastTheEnd()) {
3473 if (Info.getLangOpts().CPlusPlus11)
3474 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3475 else
3476 Info.FFDiag(Conv);
3477 return false;
3478 }
Richard Smith5b5e27a2019-05-10 20:05:31 +00003479 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
Eli Friedman3bf72d72019-02-08 21:18:46 +00003480 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3481 return true;
Richard Smith96e0c102011-11-04 02:25:55 +00003482 }
Richard Smith11562c52011-10-28 17:51:58 +00003483 }
3484
Richard Smith3229b742013-05-05 21:17:10 +00003485 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3486 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003487}
3488
3489/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003490static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003491 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003492 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003493 return false;
3494
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003495 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003496 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003497 return false;
3498 }
3499
Richard Smith3229b742013-05-05 21:17:10 +00003500 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003501 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3502}
3503
3504namespace {
3505struct CompoundAssignSubobjectHandler {
3506 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003507 const Expr *E;
3508 QualType PromotedLHSType;
3509 BinaryOperatorKind Opcode;
3510 const APValue &RHS;
3511
3512 static const AccessKinds AccessKind = AK_Assign;
3513
3514 typedef bool result_type;
3515
3516 bool checkConst(QualType QT) {
3517 // Assigning to a const object has undefined behavior.
3518 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003519 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003520 return false;
3521 }
3522 return true;
3523 }
3524
3525 bool failed() { return false; }
3526 bool found(APValue &Subobj, QualType SubobjType) {
3527 switch (Subobj.getKind()) {
3528 case APValue::Int:
3529 return found(Subobj.getInt(), SubobjType);
3530 case APValue::Float:
3531 return found(Subobj.getFloat(), SubobjType);
3532 case APValue::ComplexInt:
3533 case APValue::ComplexFloat:
3534 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003535 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003536 return false;
3537 case APValue::LValue:
3538 return foundPointer(Subobj, SubobjType);
3539 default:
3540 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003541 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003542 return false;
3543 }
3544 }
3545 bool found(APSInt &Value, QualType SubobjType) {
3546 if (!checkConst(SubobjType))
3547 return false;
3548
Tan S. B.9f935e82018-12-18 07:38:06 +00003549 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003550 // We don't support compound assignment on integer-cast-to-pointer
3551 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003552 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003553 return false;
3554 }
3555
Tan S. B.9f935e82018-12-18 07:38:06 +00003556 if (RHS.isInt()) {
3557 APSInt LHS =
3558 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3559 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3560 return false;
3561 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3562 return true;
3563 } else if (RHS.isFloat()) {
3564 APFloat FValue(0.0);
3565 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3566 FValue) &&
3567 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3568 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3569 Value);
3570 }
3571
3572 Info.FFDiag(E);
3573 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003574 }
3575 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003576 return checkConst(SubobjType) &&
3577 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3578 Value) &&
3579 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3580 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003581 }
3582 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3583 if (!checkConst(SubobjType))
3584 return false;
3585
3586 QualType PointeeType;
3587 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3588 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003589
3590 if (PointeeType.isNull() || !RHS.isInt() ||
3591 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003592 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003593 return false;
3594 }
3595
Richard Smithd6cc1982017-01-31 02:23:02 +00003596 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003597 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003598 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003599
3600 LValue LVal;
3601 LVal.setFrom(Info.Ctx, Subobj);
3602 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3603 return false;
3604 LVal.moveInto(Subobj);
3605 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003606 }
Richard Smith43e77732013-05-07 04:50:00 +00003607};
3608} // end anonymous namespace
3609
3610const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3611
3612/// Perform a compound assignment of LVal <op>= RVal.
3613static bool handleCompoundAssignment(
3614 EvalInfo &Info, const Expr *E,
3615 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3616 BinaryOperatorKind Opcode, const APValue &RVal) {
3617 if (LVal.Designator.Invalid)
3618 return false;
3619
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003620 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003621 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003622 return false;
3623 }
3624
3625 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3626 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3627 RVal };
3628 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3629}
3630
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003631namespace {
3632struct IncDecSubobjectHandler {
3633 EvalInfo &Info;
3634 const UnaryOperator *E;
3635 AccessKinds AccessKind;
3636 APValue *Old;
3637
Richard Smith243ef902013-05-05 23:31:59 +00003638 typedef bool result_type;
3639
3640 bool checkConst(QualType QT) {
3641 // Assigning to a const object has undefined behavior.
3642 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003643 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003644 return false;
3645 }
3646 return true;
3647 }
3648
3649 bool failed() { return false; }
3650 bool found(APValue &Subobj, QualType SubobjType) {
3651 // Stash the old value. Also clear Old, so we don't clobber it later
3652 // if we're post-incrementing a complex.
3653 if (Old) {
3654 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003655 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003656 }
3657
3658 switch (Subobj.getKind()) {
3659 case APValue::Int:
3660 return found(Subobj.getInt(), SubobjType);
3661 case APValue::Float:
3662 return found(Subobj.getFloat(), SubobjType);
3663 case APValue::ComplexInt:
3664 return found(Subobj.getComplexIntReal(),
3665 SubobjType->castAs<ComplexType>()->getElementType()
3666 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3667 case APValue::ComplexFloat:
3668 return found(Subobj.getComplexFloatReal(),
3669 SubobjType->castAs<ComplexType>()->getElementType()
3670 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3671 case APValue::LValue:
3672 return foundPointer(Subobj, SubobjType);
3673 default:
3674 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003675 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003676 return false;
3677 }
3678 }
3679 bool found(APSInt &Value, QualType SubobjType) {
3680 if (!checkConst(SubobjType))
3681 return false;
3682
3683 if (!SubobjType->isIntegerType()) {
3684 // We don't support increment / decrement on integer-cast-to-pointer
3685 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003686 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003687 return false;
3688 }
3689
3690 if (Old) *Old = APValue(Value);
3691
3692 // bool arithmetic promotes to int, and the conversion back to bool
3693 // doesn't reduce mod 2^n, so special-case it.
3694 if (SubobjType->isBooleanType()) {
3695 if (AccessKind == AK_Increment)
3696 Value = 1;
3697 else
3698 Value = !Value;
3699 return true;
3700 }
3701
3702 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003703 if (AccessKind == AK_Increment) {
3704 ++Value;
3705
3706 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3707 APSInt ActualValue(Value, /*IsUnsigned*/true);
3708 return HandleOverflow(Info, E, ActualValue, SubobjType);
3709 }
3710 } else {
3711 --Value;
3712
3713 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3714 unsigned BitWidth = Value.getBitWidth();
3715 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3716 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003717 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003718 }
3719 }
3720 return true;
3721 }
3722 bool found(APFloat &Value, QualType SubobjType) {
3723 if (!checkConst(SubobjType))
3724 return false;
3725
3726 if (Old) *Old = APValue(Value);
3727
3728 APFloat One(Value.getSemantics(), 1);
3729 if (AccessKind == AK_Increment)
3730 Value.add(One, APFloat::rmNearestTiesToEven);
3731 else
3732 Value.subtract(One, APFloat::rmNearestTiesToEven);
3733 return true;
3734 }
3735 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3736 if (!checkConst(SubobjType))
3737 return false;
3738
3739 QualType PointeeType;
3740 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3741 PointeeType = PT->getPointeeType();
3742 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003743 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003744 return false;
3745 }
3746
3747 LValue LVal;
3748 LVal.setFrom(Info.Ctx, Subobj);
3749 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3750 AccessKind == AK_Increment ? 1 : -1))
3751 return false;
3752 LVal.moveInto(Subobj);
3753 return true;
3754 }
Richard Smith243ef902013-05-05 23:31:59 +00003755};
3756} // end anonymous namespace
3757
3758/// Perform an increment or decrement on LVal.
3759static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3760 QualType LValType, bool IsIncrement, APValue *Old) {
3761 if (LVal.Designator.Invalid)
3762 return false;
3763
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003764 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003765 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003766 return false;
3767 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003768
3769 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3770 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3771 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3772 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3773}
3774
Richard Smithe97cbd72011-11-11 04:05:33 +00003775/// Build an lvalue for the object argument of a member function call.
3776static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3777 LValue &This) {
3778 if (Object->getType()->isPointerType())
3779 return EvaluatePointer(Object, This, Info);
3780
3781 if (Object->isGLValue())
3782 return EvaluateLValue(Object, This, Info);
3783
Richard Smithd9f663b2013-04-22 15:31:51 +00003784 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003785 return EvaluateTemporary(Object, This, Info);
3786
Faisal Valie690b7a2016-07-02 22:34:24 +00003787 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003788 return false;
3789}
3790
3791/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3792/// lvalue referring to the result.
3793///
3794/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003795/// \param LV - An lvalue referring to the base of the member pointer.
3796/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003797/// \param IncludeMember - Specifies whether the member itself is included in
3798/// the resulting LValue subobject designator. This is not possible when
3799/// creating a bound member function.
3800/// \return The field or method declaration to which the member pointer refers,
3801/// or 0 if evaluation fails.
3802static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003803 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003804 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003805 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003806 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003807 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003808 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003809 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003810
3811 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3812 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003813 if (!MemPtr.getDecl()) {
3814 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003815 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003816 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003817 }
Richard Smith253c2a32012-01-27 01:14:48 +00003818
Richard Smith027bf112011-11-17 22:56:20 +00003819 if (MemPtr.isDerivedMember()) {
3820 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003821 // The end of the derived-to-base path for the base object must match the
3822 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003823 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003824 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003825 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003826 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003827 }
Richard Smith027bf112011-11-17 22:56:20 +00003828 unsigned PathLengthToMember =
3829 LV.Designator.Entries.size() - MemPtr.Path.size();
3830 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3831 const CXXRecordDecl *LVDecl = getAsBaseClass(
3832 LV.Designator.Entries[PathLengthToMember + I]);
3833 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003834 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003835 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003836 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003837 }
Richard Smith027bf112011-11-17 22:56:20 +00003838 }
3839
3840 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003841 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003842 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003843 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003844 } else if (!MemPtr.Path.empty()) {
3845 // Extend the LValue path with the member pointer's path.
3846 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3847 MemPtr.Path.size() + IncludeMember);
3848
3849 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003850 if (const PointerType *PT = LVType->getAs<PointerType>())
3851 LVType = PT->getPointeeType();
3852 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3853 assert(RD && "member pointer access on non-class-type expression");
3854 // The first class in the path is that of the lvalue.
3855 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3856 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003857 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003858 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003859 RD = Base;
3860 }
3861 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003862 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3863 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003864 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003865 }
3866
3867 // Add the member. Note that we cannot build bound member functions here.
3868 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003869 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003870 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003871 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003872 } else if (const IndirectFieldDecl *IFD =
3873 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003874 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003875 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003876 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003877 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003878 }
Richard Smith027bf112011-11-17 22:56:20 +00003879 }
3880
3881 return MemPtr.getDecl();
3882}
3883
Richard Smith84401042013-06-03 05:03:02 +00003884static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3885 const BinaryOperator *BO,
3886 LValue &LV,
3887 bool IncludeMember = true) {
3888 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3889
3890 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003891 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003892 MemberPtr MemPtr;
3893 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3894 }
Craig Topper36250ad2014-05-12 05:36:57 +00003895 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003896 }
3897
3898 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3899 BO->getRHS(), IncludeMember);
3900}
3901
Richard Smith027bf112011-11-17 22:56:20 +00003902/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3903/// the provided lvalue, which currently refers to the base object.
3904static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3905 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003906 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003907 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003908 return false;
3909
Richard Smitha8105bc2012-01-06 16:39:00 +00003910 QualType TargetQT = E->getType();
3911 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3912 TargetQT = PT->getPointeeType();
3913
3914 // Check this cast lands within the final derived-to-base subobject path.
3915 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003916 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003917 << D.MostDerivedType << TargetQT;
3918 return false;
3919 }
3920
Richard Smith027bf112011-11-17 22:56:20 +00003921 // Check the type of the final cast. We don't need to check the path,
3922 // since a cast can only be formed if the path is unique.
3923 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003924 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3925 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003926 if (NewEntriesSize == D.MostDerivedPathLength)
3927 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3928 else
Richard Smith027bf112011-11-17 22:56:20 +00003929 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003930 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003931 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003932 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003933 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003934 }
Richard Smith027bf112011-11-17 22:56:20 +00003935
3936 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003937 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003938}
3939
Mike Stump876387b2009-10-27 22:09:17 +00003940namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003941enum EvalStmtResult {
3942 /// Evaluation failed.
3943 ESR_Failed,
3944 /// Hit a 'return' statement.
3945 ESR_Returned,
3946 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003947 ESR_Succeeded,
3948 /// Hit a 'continue' statement.
3949 ESR_Continue,
3950 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003951 ESR_Break,
3952 /// Still scanning for 'case' or 'default' statement.
3953 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003954};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003955}
Richard Smith254a73d2011-10-28 22:34:42 +00003956
Richard Smith97fcf4b2016-08-14 23:15:52 +00003957static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3958 // We don't need to evaluate the initializer for a static local.
3959 if (!VD->hasLocalStorage())
3960 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003961
Richard Smith97fcf4b2016-08-14 23:15:52 +00003962 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003963 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00003964
Richard Smith97fcf4b2016-08-14 23:15:52 +00003965 const Expr *InitE = VD->getInit();
3966 if (!InitE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003967 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
3968 << false << VD->getType();
Richard Smith97fcf4b2016-08-14 23:15:52 +00003969 Val = APValue();
3970 return false;
3971 }
Richard Smith51f03172013-06-20 03:00:05 +00003972
Richard Smith97fcf4b2016-08-14 23:15:52 +00003973 if (InitE->isValueDependent())
3974 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003975
Richard Smith97fcf4b2016-08-14 23:15:52 +00003976 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3977 // Wipe out any partially-computed value, to allow tracking that this
3978 // evaluation failed.
3979 Val = APValue();
3980 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003981 }
3982
3983 return true;
3984}
3985
Richard Smith97fcf4b2016-08-14 23:15:52 +00003986static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3987 bool OK = true;
3988
3989 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3990 OK &= EvaluateVarDecl(Info, VD);
3991
3992 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3993 for (auto *BD : DD->bindings())
3994 if (auto *VD = BD->getHoldingVar())
3995 OK &= EvaluateDecl(Info, VD);
3996
3997 return OK;
3998}
3999
4000
Richard Smith4e18ca52013-05-06 05:56:11 +00004001/// Evaluate a condition (either a variable declaration or an expression).
4002static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4003 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004004 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004005 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4006 return false;
4007 return EvaluateAsBooleanCondition(Cond, Result, Info);
4008}
4009
Richard Smith89210072016-04-04 23:29:43 +00004010namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004011/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00004012/// statement should be stored.
4013struct StmtResult {
4014 /// The APValue that should be filled in with the returned value.
4015 APValue &Value;
4016 /// The location containing the result, if any (used to support RVO).
4017 const LValue *Slot;
4018};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004019
4020struct TempVersionRAII {
4021 CallStackFrame &Frame;
4022
4023 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4024 Frame.pushTempVersion();
4025 }
4026
4027 ~TempVersionRAII() {
4028 Frame.popTempVersion();
4029 }
4030};
4031
Richard Smith89210072016-04-04 23:29:43 +00004032}
Richard Smith52a980a2015-08-28 02:43:42 +00004033
4034static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00004035 const Stmt *S,
4036 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00004037
4038/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00004039static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004040 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00004041 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004042 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00004043 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00004044 case ESR_Break:
4045 return ESR_Succeeded;
4046 case ESR_Succeeded:
4047 case ESR_Continue:
4048 return ESR_Continue;
4049 case ESR_Failed:
4050 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00004051 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00004052 return ESR;
4053 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00004054 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00004055}
4056
Richard Smith496ddcf2013-05-12 17:32:42 +00004057/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004058static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004059 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004060 BlockScopeRAII Scope(Info);
4061
Richard Smith496ddcf2013-05-12 17:32:42 +00004062 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00004063 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004064 {
4065 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004066 if (const Stmt *Init = SS->getInit()) {
4067 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4068 if (ESR != ESR_Succeeded)
4069 return ESR;
4070 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004071 if (SS->getConditionVariable() &&
4072 !EvaluateDecl(Info, SS->getConditionVariable()))
4073 return ESR_Failed;
4074 if (!EvaluateInteger(SS->getCond(), Value, Info))
4075 return ESR_Failed;
4076 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004077
4078 // Find the switch case corresponding to the value of the condition.
4079 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00004080 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004081 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4082 SC = SC->getNextSwitchCase()) {
4083 if (isa<DefaultStmt>(SC)) {
4084 Found = SC;
4085 continue;
4086 }
4087
4088 const CaseStmt *CS = cast<CaseStmt>(SC);
4089 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4090 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4091 : LHS;
4092 if (LHS <= Value && Value <= RHS) {
4093 Found = SC;
4094 break;
4095 }
4096 }
4097
4098 if (!Found)
4099 return ESR_Succeeded;
4100
4101 // Search the switch body for the switch case and evaluate it from there.
4102 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4103 case ESR_Break:
4104 return ESR_Succeeded;
4105 case ESR_Succeeded:
4106 case ESR_Continue:
4107 case ESR_Failed:
4108 case ESR_Returned:
4109 return ESR;
4110 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004111 // This can only happen if the switch case is nested within a statement
4112 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004113 Info.FFDiag(Found->getBeginLoc(),
4114 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004115 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004116 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004117 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004118}
4119
Richard Smith254a73d2011-10-28 22:34:42 +00004120// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004121static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004122 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004123 if (!Info.nextStep(S))
4124 return ESR_Failed;
4125
Richard Smith496ddcf2013-05-12 17:32:42 +00004126 // If we're hunting down a 'case' or 'default' label, recurse through
4127 // substatements until we hit the label.
4128 if (Case) {
4129 // FIXME: We don't start the lifetime of objects whose initialization we
4130 // jump over. However, such objects must be of class type with a trivial
4131 // default constructor that initialize all subobjects, so must be empty,
4132 // so this almost never matters.
4133 switch (S->getStmtClass()) {
4134 case Stmt::CompoundStmtClass:
4135 // FIXME: Precompute which substatement of a compound statement we
4136 // would jump to, and go straight there rather than performing a
4137 // linear scan each time.
4138 case Stmt::LabelStmtClass:
4139 case Stmt::AttributedStmtClass:
4140 case Stmt::DoStmtClass:
4141 break;
4142
4143 case Stmt::CaseStmtClass:
4144 case Stmt::DefaultStmtClass:
4145 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004146 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004147 break;
4148
4149 case Stmt::IfStmtClass: {
4150 // FIXME: Precompute which side of an 'if' we would jump to, and go
4151 // straight there rather than scanning both sides.
4152 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004153
4154 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4155 // preceded by our switch label.
4156 BlockScopeRAII Scope(Info);
4157
Richard Smith496ddcf2013-05-12 17:32:42 +00004158 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4159 if (ESR != ESR_CaseNotFound || !IS->getElse())
4160 return ESR;
4161 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4162 }
4163
4164 case Stmt::WhileStmtClass: {
4165 EvalStmtResult ESR =
4166 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4167 if (ESR != ESR_Continue)
4168 return ESR;
4169 break;
4170 }
4171
4172 case Stmt::ForStmtClass: {
4173 const ForStmt *FS = cast<ForStmt>(S);
4174 EvalStmtResult ESR =
4175 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4176 if (ESR != ESR_Continue)
4177 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004178 if (FS->getInc()) {
4179 FullExpressionRAII IncScope(Info);
4180 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4181 return ESR_Failed;
4182 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004183 break;
4184 }
4185
4186 case Stmt::DeclStmtClass:
4187 // FIXME: If the variable has initialization that can't be jumped over,
4188 // bail out of any immediately-surrounding compound-statement too.
4189 default:
4190 return ESR_CaseNotFound;
4191 }
4192 }
4193
Richard Smith254a73d2011-10-28 22:34:42 +00004194 switch (S->getStmtClass()) {
4195 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004196 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004197 // Don't bother evaluating beyond an expression-statement which couldn't
4198 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004199 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004200 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004201 return ESR_Failed;
4202 return ESR_Succeeded;
4203 }
4204
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004205 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004206 return ESR_Failed;
4207
4208 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004209 return ESR_Succeeded;
4210
Richard Smithd9f663b2013-04-22 15:31:51 +00004211 case Stmt::DeclStmtClass: {
4212 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004213 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004214 // Each declaration initialization is its own full-expression.
4215 // FIXME: This isn't quite right; if we're performing aggregate
4216 // initialization, each braced subexpression is its own full-expression.
4217 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004218 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004219 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004220 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004221 return ESR_Succeeded;
4222 }
4223
Richard Smith357362d2011-12-13 06:39:58 +00004224 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004225 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004226 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004227 if (RetExpr &&
4228 !(Result.Slot
4229 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4230 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004231 return ESR_Failed;
4232 return ESR_Returned;
4233 }
Richard Smith254a73d2011-10-28 22:34:42 +00004234
4235 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004236 BlockScopeRAII Scope(Info);
4237
Richard Smith254a73d2011-10-28 22:34:42 +00004238 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004239 for (const auto *BI : CS->body()) {
4240 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004241 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004242 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004243 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004244 return ESR;
4245 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004246 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004247 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004248
4249 case Stmt::IfStmtClass: {
4250 const IfStmt *IS = cast<IfStmt>(S);
4251
4252 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004253 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004254 if (const Stmt *Init = IS->getInit()) {
4255 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4256 if (ESR != ESR_Succeeded)
4257 return ESR;
4258 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004259 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004260 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004261 return ESR_Failed;
4262
4263 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4264 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4265 if (ESR != ESR_Succeeded)
4266 return ESR;
4267 }
4268 return ESR_Succeeded;
4269 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004270
4271 case Stmt::WhileStmtClass: {
4272 const WhileStmt *WS = cast<WhileStmt>(S);
4273 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004274 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004275 bool Continue;
4276 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4277 Continue))
4278 return ESR_Failed;
4279 if (!Continue)
4280 break;
4281
4282 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4283 if (ESR != ESR_Continue)
4284 return ESR;
4285 }
4286 return ESR_Succeeded;
4287 }
4288
4289 case Stmt::DoStmtClass: {
4290 const DoStmt *DS = cast<DoStmt>(S);
4291 bool Continue;
4292 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004293 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004294 if (ESR != ESR_Continue)
4295 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004296 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004297
Richard Smith08d6a2c2013-07-24 07:11:57 +00004298 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004299 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4300 return ESR_Failed;
4301 } while (Continue);
4302 return ESR_Succeeded;
4303 }
4304
4305 case Stmt::ForStmtClass: {
4306 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004307 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004308 if (FS->getInit()) {
4309 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4310 if (ESR != ESR_Succeeded)
4311 return ESR;
4312 }
4313 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004314 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004315 bool Continue = true;
4316 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4317 FS->getCond(), Continue))
4318 return ESR_Failed;
4319 if (!Continue)
4320 break;
4321
4322 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4323 if (ESR != ESR_Continue)
4324 return ESR;
4325
Richard Smith08d6a2c2013-07-24 07:11:57 +00004326 if (FS->getInc()) {
4327 FullExpressionRAII IncScope(Info);
4328 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4329 return ESR_Failed;
4330 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004331 }
4332 return ESR_Succeeded;
4333 }
4334
Richard Smith896e0d72013-05-06 06:51:17 +00004335 case Stmt::CXXForRangeStmtClass: {
4336 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004337 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004338
Richard Smith8baa5002018-09-28 18:44:09 +00004339 // Evaluate the init-statement if present.
4340 if (FS->getInit()) {
4341 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4342 if (ESR != ESR_Succeeded)
4343 return ESR;
4344 }
4345
Richard Smith896e0d72013-05-06 06:51:17 +00004346 // Initialize the __range variable.
4347 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4348 if (ESR != ESR_Succeeded)
4349 return ESR;
4350
4351 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004352 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4353 if (ESR != ESR_Succeeded)
4354 return ESR;
4355 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004356 if (ESR != ESR_Succeeded)
4357 return ESR;
4358
4359 while (true) {
4360 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004361 {
4362 bool Continue = true;
4363 FullExpressionRAII CondExpr(Info);
4364 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4365 return ESR_Failed;
4366 if (!Continue)
4367 break;
4368 }
Richard Smith896e0d72013-05-06 06:51:17 +00004369
4370 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004371 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004372 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4373 if (ESR != ESR_Succeeded)
4374 return ESR;
4375
4376 // Loop body.
4377 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4378 if (ESR != ESR_Continue)
4379 return ESR;
4380
4381 // Increment: ++__begin
4382 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4383 return ESR_Failed;
4384 }
4385
4386 return ESR_Succeeded;
4387 }
4388
Richard Smith496ddcf2013-05-12 17:32:42 +00004389 case Stmt::SwitchStmtClass:
4390 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4391
Richard Smith4e18ca52013-05-06 05:56:11 +00004392 case Stmt::ContinueStmtClass:
4393 return ESR_Continue;
4394
4395 case Stmt::BreakStmtClass:
4396 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004397
4398 case Stmt::LabelStmtClass:
4399 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4400
4401 case Stmt::AttributedStmtClass:
4402 // As a general principle, C++11 attributes can be ignored without
4403 // any semantic impact.
4404 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4405 Case);
4406
4407 case Stmt::CaseStmtClass:
4408 case Stmt::DefaultStmtClass:
4409 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004410 case Stmt::CXXTryStmtClass:
4411 // Evaluate try blocks by evaluating all sub statements.
4412 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004413 }
4414}
4415
Richard Smithcc36f692011-12-22 02:22:31 +00004416/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4417/// default constructor. If so, we'll fold it whether or not it's marked as
4418/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4419/// so we need special handling.
4420static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004421 const CXXConstructorDecl *CD,
4422 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004423 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4424 return false;
4425
Richard Smith66e05fe2012-01-18 05:21:49 +00004426 // Value-initialization does not call a trivial default constructor, so such a
4427 // call is a core constant expression whether or not the constructor is
4428 // constexpr.
4429 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004430 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004431 // FIXME: If DiagDecl is an implicitly-declared special member function,
4432 // we should be much more explicit about why it's not constexpr.
4433 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4434 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4435 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004436 } else {
4437 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4438 }
4439 }
4440 return true;
4441}
4442
Richard Smith357362d2011-12-13 06:39:58 +00004443/// CheckConstexprFunction - Check that a function can be called in a constant
4444/// expression.
4445static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4446 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004447 const FunctionDecl *Definition,
4448 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004449 // Potential constant expressions can contain calls to declared, but not yet
4450 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004451 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004452 Declaration->isConstexpr())
4453 return false;
4454
James Y Knightc7d3e602018-10-05 17:49:48 +00004455 // Bail out if the function declaration itself is invalid. We will
4456 // have produced a relevant diagnostic while parsing it, so just
4457 // note the problematic sub-expression.
4458 if (Declaration->isInvalidDecl()) {
4459 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004460 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004461 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004462
Richard Smithd9c6b032019-05-09 19:45:49 +00004463 // DR1872: An instantiated virtual constexpr function can't be called in a
Hans Wennborgd5fb16252019-05-13 13:19:09 +00004464 // constant expression.
4465 if (isa<CXXMethodDecl>(Declaration) &&
4466 cast<CXXMethodDecl>(Declaration)->isVirtual()) {
4467 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_call);
Richard Smithd9c6b032019-05-09 19:45:49 +00004468 return false;
4469 }
4470
Richard Smith357362d2011-12-13 06:39:58 +00004471 // Can we evaluate this function call?
Hans Wennborgd5fb16252019-05-13 13:19:09 +00004472 if (Definition && Definition->isConstexpr() &&
4473 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004474 return true;
4475
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004476 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004477 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004478
Richard Smith5179eb72016-06-28 19:03:57 +00004479 // If this function is not constexpr because it is an inherited
4480 // non-constexpr constructor, diagnose that directly.
4481 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4482 if (CD && CD->isInheritingConstructor()) {
4483 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004484 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004485 DiagDecl = CD = Inherited;
4486 }
4487
4488 // FIXME: If DiagDecl is an implicitly-declared special member function
4489 // or an inheriting constructor, we should be much more explicit about why
4490 // it's not constexpr.
4491 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004492 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004493 << CD->getInheritedConstructor().getConstructor()->getParent();
4494 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004495 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004496 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004497 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4498 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004499 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004500 }
4501 return false;
4502}
4503
Richard Smithdebad642019-05-12 09:39:08 +00004504namespace {
4505struct CheckMemberCallThisPointerHandler {
4506 static const AccessKinds AccessKind = AK_MemberCall;
4507 typedef bool result_type;
4508 bool failed() { return false; }
4509 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4510 bool found(APSInt &Value, QualType SubobjType) { return true; }
4511 bool found(APFloat &Value, QualType SubobjType) { return true; }
4512};
4513} // end anonymous namespace
4514
4515const AccessKinds CheckMemberCallThisPointerHandler::AccessKind;
4516
4517/// Check that the pointee of the 'this' pointer in a member function call is
4518/// either within its lifetime or in its period of construction or destruction.
4519static bool checkMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4520 const LValue &This) {
Richard Smithdab287b2019-05-13 07:51:29 +00004521 if (This.Designator.Invalid)
4522 return false;
4523
Richard Smithdebad642019-05-12 09:39:08 +00004524 CompleteObject Obj =
4525 findCompleteObject(Info, E, AK_MemberCall, This, QualType());
4526
4527 if (!Obj)
4528 return false;
4529
4530 if (!Obj.Value) {
4531 // The object is not usable in constant expressions, so we can't inspect
4532 // its value to see if it's in-lifetime or what the active union members
4533 // are. We can still check for a one-past-the-end lvalue.
4534 if (This.Designator.isOnePastTheEnd() ||
4535 This.Designator.isMostDerivedAnUnsizedArray()) {
4536 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4537 ? diag::note_constexpr_access_past_end
4538 : diag::note_constexpr_access_unsized_array)
4539 << AK_MemberCall;
4540 return false;
4541 }
4542 return true;
4543 }
4544
4545 CheckMemberCallThisPointerHandler Handler;
4546 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4547}
4548
Richard Smithbe6dd812014-11-19 21:27:17 +00004549/// Determine if a class has any fields that might need to be copied by a
4550/// trivial copy or move operation.
4551static bool hasFields(const CXXRecordDecl *RD) {
4552 if (!RD || RD->isEmpty())
4553 return false;
4554 for (auto *FD : RD->fields()) {
4555 if (FD->isUnnamedBitfield())
4556 continue;
4557 return true;
4558 }
4559 for (auto &Base : RD->bases())
4560 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4561 return true;
4562 return false;
4563}
4564
Richard Smithd62306a2011-11-10 06:34:14 +00004565namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004566typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004567}
4568
4569/// EvaluateArgs - Evaluate the arguments to a function call.
4570static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4571 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004572 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004573 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004574 I != E; ++I) {
4575 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4576 // If we're checking for a potential constant expression, evaluate all
4577 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004578 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004579 return false;
4580 Success = false;
4581 }
4582 }
4583 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004584}
4585
Richard Smith254a73d2011-10-28 22:34:42 +00004586/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004587static bool HandleFunctionCall(SourceLocation CallLoc,
4588 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004589 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004590 EvalInfo &Info, APValue &Result,
4591 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004592 ArgVector ArgValues(Args.size());
4593 if (!EvaluateArgs(Args, ArgValues, Info))
4594 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004595
Richard Smith253c2a32012-01-27 01:14:48 +00004596 if (!Info.CheckCallLimit(CallLoc))
4597 return false;
4598
4599 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004600
4601 // For a trivial copy or move assignment, perform an APValue copy. This is
4602 // essential for unions, where the operations performed by the assignment
4603 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004604 //
4605 // Skip this for non-union classes with no fields; in that case, the defaulted
4606 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004607 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004608 if (MD && MD->isDefaulted() &&
4609 (MD->getParent()->isUnion() ||
4610 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004611 assert(This &&
4612 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4613 LValue RHS;
4614 RHS.setFrom(Info.Ctx, ArgValues[0]);
4615 APValue RHSValue;
4616 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4617 RHS, RHSValue))
4618 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00004619 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00004620 RHSValue))
4621 return false;
4622 This->moveInto(Result);
4623 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004624 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00004625 // We're in a lambda; determine the lambda capture field maps unless we're
4626 // just constexpr checking a lambda's call operator. constexpr checking is
4627 // done before the captures have been added to the closure object (unless
4628 // we're inferring constexpr-ness), so we don't have access to them in this
4629 // case. But since we don't need the captures to constexpr check, we can
4630 // just ignore them.
4631 if (!Info.checkingPotentialConstantExpression())
4632 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4633 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004634 }
4635
Richard Smith52a980a2015-08-28 02:43:42 +00004636 StmtResult Ret = {Result, ResultSlot};
4637 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004638 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004639 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004640 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004641 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004642 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004643 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004644}
4645
Richard Smithd62306a2011-11-10 06:34:14 +00004646/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004647static bool HandleConstructorCall(const Expr *E, const LValue &This,
4648 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004649 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004650 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004651 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004652 if (!Info.CheckCallLimit(CallLoc))
4653 return false;
4654
Richard Smith3607ffe2012-02-13 03:54:03 +00004655 const CXXRecordDecl *RD = Definition->getParent();
4656 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004657 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004658 return false;
4659 }
4660
Erik Pilkington42925492017-10-04 00:18:55 +00004661 EvalInfo::EvaluatingConstructorRAII EvalObj(
Richard Smithd3d6f4f2019-05-12 08:57:59 +00004662 Info,
4663 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
4664 RD->getNumBases());
Richard Smith5179eb72016-06-28 19:03:57 +00004665 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004666
Richard Smith52a980a2015-08-28 02:43:42 +00004667 // FIXME: Creating an APValue just to hold a nonexistent return value is
4668 // wasteful.
4669 APValue RetVal;
4670 StmtResult Ret = {RetVal, nullptr};
4671
Richard Smith5179eb72016-06-28 19:03:57 +00004672 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004673 if (Definition->isDelegatingConstructor()) {
4674 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004675 {
4676 FullExpressionRAII InitScope(Info);
4677 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4678 return false;
4679 }
Richard Smith52a980a2015-08-28 02:43:42 +00004680 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004681 }
4682
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004683 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004684 // essential for unions (or classes with anonymous union members), where the
4685 // operations performed by the constructor cannot be represented by
4686 // ctor-initializers.
4687 //
4688 // Skip this for empty non-union classes; we should not perform an
4689 // lvalue-to-rvalue conversion on them because their copy constructor does not
4690 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004691 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004692 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004693 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004694 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004695 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004696 return handleLValueToRValueConversion(
4697 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4698 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004699 }
4700
4701 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004702 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004703 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004704 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004705
John McCalld7bca762012-05-01 00:38:49 +00004706 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004707 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4708
Richard Smith08d6a2c2013-07-24 07:11:57 +00004709 // A scope for temporaries lifetime-extended by reference members.
4710 BlockScopeRAII LifetimeExtendedScope(Info);
4711
Richard Smith253c2a32012-01-27 01:14:48 +00004712 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004713 unsigned BasesSeen = 0;
4714#ifndef NDEBUG
4715 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4716#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004717 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004718 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004719 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004720 APValue *Value = &Result;
4721
4722 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004723 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004724 if (I->isBaseInitializer()) {
4725 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004726#ifndef NDEBUG
4727 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004728 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004729 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4730 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4731 "base class initializers not in expected order");
4732 ++BaseIt;
4733#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004734 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004735 BaseType->getAsCXXRecordDecl(), &Layout))
4736 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004737 Value = &Result.getStructBase(BasesSeen++);
Hans Wennborgd5fb16252019-05-13 13:19:09 +00004738
4739 // This is the point at which the dynamic type of the object becomes this
4740 // class type.
4741 if (BasesSeen == RD->getNumBases())
4742 EvalObj.finishedConstructingBases();
Aaron Ballman0ad78302014-03-13 17:34:31 +00004743 } else if ((FD = I->getMember())) {
4744 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004745 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004746 if (RD->isUnion()) {
4747 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004748 Value = &Result.getUnionValue();
4749 } else {
4750 Value = &Result.getStructField(FD->getFieldIndex());
4751 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004752 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004753 // Walk the indirect field decl's chain to find the object to initialize,
4754 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004755 auto IndirectFieldChain = IFD->chain();
4756 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004757 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004758 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4759 // Switch the union field if it differs. This happens if we had
4760 // preceding zero-initialization, and we're now initializing a union
4761 // subobject other than the first.
4762 // FIXME: In this case, the values of the other subobjects are
4763 // specified, since zero-initialization sets all padding bits to zero.
4764 if (Value->isUninit() ||
4765 (Value->isUnion() && Value->getUnionField() != FD)) {
4766 if (CD->isUnion())
4767 *Value = APValue(FD);
4768 else
4769 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004770 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004771 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004772 // Store Subobject as its parent before updating it for the last element
4773 // in the chain.
4774 if (C == IndirectFieldChain.back())
4775 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004776 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004777 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004778 if (CD->isUnion())
4779 Value = &Value->getUnionValue();
4780 else
4781 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004782 }
Richard Smithd62306a2011-11-10 06:34:14 +00004783 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004784 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004785 }
Richard Smith253c2a32012-01-27 01:14:48 +00004786
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004787 // Need to override This for implicit field initializers as in this case
4788 // This refers to innermost anonymous struct/union containing initializer,
4789 // not to currently constructed class.
4790 const Expr *Init = I->getInit();
4791 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4792 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004793 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004794 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4795 (FD && FD->isBitField() &&
4796 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004797 // If we're checking for a potential constant expression, evaluate all
4798 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004799 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004800 return false;
4801 Success = false;
4802 }
Richard Smithd62306a2011-11-10 06:34:14 +00004803 }
4804
Richard Smithd9f663b2013-04-22 15:31:51 +00004805 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004806 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004807}
4808
Richard Smith5179eb72016-06-28 19:03:57 +00004809static bool HandleConstructorCall(const Expr *E, const LValue &This,
4810 ArrayRef<const Expr*> Args,
4811 const CXXConstructorDecl *Definition,
4812 EvalInfo &Info, APValue &Result) {
4813 ArgVector ArgValues(Args.size());
4814 if (!EvaluateArgs(Args, ArgValues, Info))
4815 return false;
4816
4817 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4818 Info, Result);
4819}
4820
Eli Friedman9a156e52008-11-12 09:44:48 +00004821//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004822// Generic Evaluation
4823//===----------------------------------------------------------------------===//
4824namespace {
4825
Aaron Ballman68af21c2014-01-03 19:26:43 +00004826template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004827class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004828 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004829private:
Richard Smith52a980a2015-08-28 02:43:42 +00004830 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004831 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004832 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004833 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004834 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004835 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004836 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004837
Richard Smith17100ba2012-02-16 02:46:34 +00004838 // Check whether a conditional operator with a non-constant condition is a
4839 // potential constant expression. If neither arm is a potential constant
4840 // expression, then the conditional operator is not either.
4841 template<typename ConditionalOperator>
4842 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004843 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004844
4845 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004846 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004847 {
Richard Smith17100ba2012-02-16 02:46:34 +00004848 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004849 StmtVisitorTy::Visit(E->getFalseExpr());
4850 if (Diag.empty())
4851 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004852 }
Richard Smith17100ba2012-02-16 02:46:34 +00004853
George Burgess IV8c892b52016-05-25 22:31:54 +00004854 {
4855 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004856 Diag.clear();
4857 StmtVisitorTy::Visit(E->getTrueExpr());
4858 if (Diag.empty())
4859 return;
4860 }
4861
4862 Error(E, diag::note_constexpr_conditional_never_const);
4863 }
4864
4865
4866 template<typename ConditionalOperator>
4867 bool HandleConditionalOperator(const ConditionalOperator *E) {
4868 bool BoolResult;
4869 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004870 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004871 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004872 return false;
4873 }
4874 if (Info.noteFailure()) {
4875 StmtVisitorTy::Visit(E->getTrueExpr());
4876 StmtVisitorTy::Visit(E->getFalseExpr());
4877 }
Richard Smith17100ba2012-02-16 02:46:34 +00004878 return false;
4879 }
4880
4881 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4882 return StmtVisitorTy::Visit(EvalExpr);
4883 }
4884
Peter Collingbournee9200682011-05-13 03:29:01 +00004885protected:
4886 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004887 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004888 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4889
Richard Smith92b1ce02011-12-12 09:28:41 +00004890 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004891 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004892 }
4893
Aaron Ballman68af21c2014-01-03 19:26:43 +00004894 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004895
4896public:
4897 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4898
4899 EvalInfo &getEvalInfo() { return Info; }
4900
Richard Smithf57d8cb2011-12-09 22:58:01 +00004901 /// Report an evaluation error. This should only be called when an error is
4902 /// first discovered. When propagating an error, just return false.
4903 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004904 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004905 return false;
4906 }
4907 bool Error(const Expr *E) {
4908 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4909 }
4910
Aaron Ballman68af21c2014-01-03 19:26:43 +00004911 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004912 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004913 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004914 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004915 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004916 }
4917
Bill Wendling8003edc2018-11-09 00:41:36 +00004918 bool VisitConstantExpr(const ConstantExpr *E)
4919 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004920 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004921 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004922 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004923 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004924 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004925 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004926 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004927 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004928 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004929 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004930 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004931 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004932 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4933 TempVersionRAII RAII(*Info.CurrentCall);
4934 return StmtVisitorTy::Visit(E->getExpr());
4935 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004936 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004937 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00004938 // The initializer may not have been parsed yet, or might be erroneous.
4939 if (!E->getExpr())
4940 return Error(E);
4941 return StmtVisitorTy::Visit(E->getExpr());
4942 }
Richard Smith5894a912011-12-19 22:12:41 +00004943 // We cannot create any objects for which cleanups are required, so there is
4944 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004945 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004946 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004947
Aaron Ballman68af21c2014-01-03 19:26:43 +00004948 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004949 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4950 return static_cast<Derived*>(this)->VisitCastExpr(E);
4951 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004952 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004953 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4954 return static_cast<Derived*>(this)->VisitCastExpr(E);
4955 }
4956
Aaron Ballman68af21c2014-01-03 19:26:43 +00004957 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004958 switch (E->getOpcode()) {
4959 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004960 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004961
4962 case BO_Comma:
4963 VisitIgnoredValue(E->getLHS());
4964 return StmtVisitorTy::Visit(E->getRHS());
4965
4966 case BO_PtrMemD:
4967 case BO_PtrMemI: {
4968 LValue Obj;
4969 if (!HandleMemberPointerAccess(Info, E, Obj))
4970 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004971 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004972 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004973 return false;
4974 return DerivedSuccess(Result, E);
4975 }
4976 }
4977 }
4978
Aaron Ballman68af21c2014-01-03 19:26:43 +00004979 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004980 // Evaluate and cache the common expression. We treat it as a temporary,
4981 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004982 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004983 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004984 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004985
Richard Smith17100ba2012-02-16 02:46:34 +00004986 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004987 }
4988
Aaron Ballman68af21c2014-01-03 19:26:43 +00004989 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004990 bool IsBcpCall = false;
4991 // If the condition (ignoring parens) is a __builtin_constant_p call,
4992 // the result is a constant expression if it can be folded without
4993 // side-effects. This is an important GNU extension. See GCC PR38377
4994 // for discussion.
4995 if (const CallExpr *CallCE =
4996 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004997 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004998 IsBcpCall = true;
4999
5000 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
5001 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00005002 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00005003 return false;
5004
Richard Smith6d4c6582013-11-05 22:18:15 +00005005 FoldConstant Fold(Info, IsBcpCall);
5006 if (!HandleConditionalOperator(E)) {
5007 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00005008 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00005009 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00005010
5011 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00005012 }
5013
Aaron Ballman68af21c2014-01-03 19:26:43 +00005014 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005015 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00005016 return DerivedSuccess(*Value, E);
5017
5018 const Expr *Source = E->getSourceExpr();
5019 if (!Source)
5020 return Error(E);
5021 if (Source == E) { // sanity checking.
5022 assert(0 && "OpaqueValueExpr recursively refers to itself");
5023 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00005024 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00005025 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00005026 }
Richard Smith4ce706a2011-10-11 21:43:33 +00005027
Aaron Ballman68af21c2014-01-03 19:26:43 +00005028 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00005029 APValue Result;
5030 if (!handleCallExpr(E, Result, nullptr))
5031 return false;
5032 return DerivedSuccess(Result, E);
5033 }
5034
5035 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00005036 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00005037 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00005038 QualType CalleeType = Callee->getType();
5039
Craig Topper36250ad2014-05-12 05:36:57 +00005040 const FunctionDecl *FD = nullptr;
5041 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00005042 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00005043
Richard Smithe97cbd72011-11-11 04:05:33 +00005044 // Extract function decl and 'this' pointer from the callee.
5045 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Hans Wennborgd5fb16252019-05-13 13:19:09 +00005046 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005047 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
5048 // Explicit bound member calls, such as x.f() or p->g();
5049 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005050 return false;
Hans Wennborgd5fb16252019-05-13 13:19:09 +00005051 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00005052 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00005053 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
5054 // Indirect bound member calls ('.*' or '->*').
Hans Wennborgd5fb16252019-05-13 13:19:09 +00005055 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
5056 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00005057 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00005058 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00005059 return Error(Callee);
Hans Wennborgd5fb16252019-05-13 13:19:09 +00005060
5061 FD = dyn_cast<FunctionDecl>(Member);
5062 if (!FD)
5063 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00005064 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00005065 LValue Call;
5066 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005067 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00005068
Richard Smitha8105bc2012-01-06 16:39:00 +00005069 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005070 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00005071 FD = dyn_cast_or_null<FunctionDecl>(
5072 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00005073 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005074 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00005075 // Don't call function pointers which have been cast to some other type.
5076 // Per DR (no number yet), the caller and callee can differ in noexcept.
5077 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
5078 CalleeType->getPointeeType(), FD->getType())) {
5079 return Error(E);
5080 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005081
5082 // Overloaded operator calls to member functions are represented as normal
5083 // calls with '*this' as the first argument.
5084 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
5085 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005086 // FIXME: When selecting an implicit conversion for an overloaded
5087 // operator delete, we sometimes try to evaluate calls to conversion
5088 // operators without a 'this' parameter!
5089 if (Args.empty())
5090 return Error(E);
5091
Nick Lewycky13073a62017-06-12 21:15:44 +00005092 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00005093 return false;
5094 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00005095 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00005096 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00005097 // Map the static invoker for the lambda back to the call operator.
5098 // Conveniently, we don't have to slice out the 'this' argument (as is
5099 // being done for the non-static case), since a static member function
5100 // doesn't have an implicit argument passed in.
5101 const CXXRecordDecl *ClosureClass = MD->getParent();
5102 assert(
5103 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
5104 "Number of captures must be zero for conversion to function-ptr");
5105
5106 const CXXMethodDecl *LambdaCallOp =
5107 ClosureClass->getLambdaCallOperator();
5108
5109 // Set 'FD', the function that will be called below, to the call
5110 // operator. If the closure object represents a generic lambda, find
5111 // the corresponding specialization of the call operator.
5112
5113 if (ClosureClass->isGenericLambda()) {
5114 assert(MD->isFunctionTemplateSpecialization() &&
5115 "A generic lambda's static-invoker function must be a "
5116 "template specialization");
5117 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
5118 FunctionTemplateDecl *CallOpTemplate =
5119 LambdaCallOp->getDescribedFunctionTemplate();
5120 void *InsertPos = nullptr;
5121 FunctionDecl *CorrespondingCallOpSpecialization =
5122 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
5123 assert(CorrespondingCallOpSpecialization &&
5124 "We must always have a function call operator specialization "
5125 "that corresponds to our static invoker specialization");
5126 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
5127 } else
5128 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00005129 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005130 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00005131 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00005132
Hans Wennborgd5fb16252019-05-13 13:19:09 +00005133 if (This && !checkMemberCallThisPointer(Info, E, *This))
5134 return false;
Richard Smith47b34932012-02-01 02:39:43 +00005135
Craig Topper36250ad2014-05-12 05:36:57 +00005136 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00005137 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00005138
Nick Lewycky13073a62017-06-12 21:15:44 +00005139 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
5140 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00005141 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005142 return false;
5143
Richard Smith52a980a2015-08-28 02:43:42 +00005144 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00005145 }
5146
Aaron Ballman68af21c2014-01-03 19:26:43 +00005147 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005148 return StmtVisitorTy::Visit(E->getInitializer());
5149 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005150 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00005151 if (E->getNumInits() == 0)
5152 return DerivedZeroInitialization(E);
5153 if (E->getNumInits() == 1)
5154 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00005155 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005156 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005157 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005158 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005159 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005160 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005161 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005162 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005163 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005164 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005165 }
Richard Smith4ce706a2011-10-11 21:43:33 +00005166
Richard Smithd62306a2011-11-10 06:34:14 +00005167 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00005168 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005169 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
5170 "missing temporary materialization conversion");
Richard Smithd62306a2011-11-10 06:34:14 +00005171 assert(!E->isArrow() && "missing call to bound member function?");
5172
Richard Smith2e312c82012-03-03 22:46:17 +00005173 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00005174 if (!Evaluate(Val, Info, E->getBase()))
5175 return false;
5176
5177 QualType BaseTy = E->getBase()->getType();
5178
5179 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00005180 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005181 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00005182 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00005183 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5184
Richard Smithd3d6f4f2019-05-12 08:57:59 +00005185 // Note: there is no lvalue base here. But this case should only ever
5186 // happen in C or in C++98, where we cannot be evaluating a constexpr
5187 // constructor, which is the only case the base matters.
Richard Smithdebad642019-05-12 09:39:08 +00005188 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00005189 SubobjectDesignator Designator(BaseTy);
5190 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00005191
Richard Smith3229b742013-05-05 21:17:10 +00005192 APValue Result;
5193 return extractSubobject(Info, E, Obj, Designator, Result) &&
5194 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00005195 }
5196
Aaron Ballman68af21c2014-01-03 19:26:43 +00005197 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005198 switch (E->getCastKind()) {
5199 default:
5200 break;
5201
Richard Smitha23ab512013-05-23 00:30:41 +00005202 case CK_AtomicToNonAtomic: {
5203 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00005204 // This does not need to be done in place even for class/array types:
5205 // atomic-to-non-atomic conversion implies copying the object
5206 // representation.
5207 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00005208 return false;
5209 return DerivedSuccess(AtomicVal, E);
5210 }
5211
Richard Smith11562c52011-10-28 17:51:58 +00005212 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00005213 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00005214 return StmtVisitorTy::Visit(E->getSubExpr());
5215
5216 case CK_LValueToRValue: {
5217 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005218 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5219 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005220 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00005221 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00005222 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00005223 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005224 return false;
5225 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00005226 }
5227 }
5228
Richard Smithf57d8cb2011-12-09 22:58:01 +00005229 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005230 }
5231
Aaron Ballman68af21c2014-01-03 19:26:43 +00005232 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005233 return VisitUnaryPostIncDec(UO);
5234 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005235 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005236 return VisitUnaryPostIncDec(UO);
5237 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005238 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005239 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005240 return Error(UO);
5241
5242 LValue LVal;
5243 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5244 return false;
5245 APValue RVal;
5246 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5247 UO->isIncrementOp(), &RVal))
5248 return false;
5249 return DerivedSuccess(RVal, UO);
5250 }
5251
Aaron Ballman68af21c2014-01-03 19:26:43 +00005252 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00005253 // We will have checked the full-expressions inside the statement expression
5254 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00005255 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00005256 return Error(E);
5257
Richard Smith08d6a2c2013-07-24 07:11:57 +00005258 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00005259 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005260 if (CS->body_empty())
5261 return true;
5262
Richard Smith51f03172013-06-20 03:00:05 +00005263 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5264 BE = CS->body_end();
5265 /**/; ++BI) {
5266 if (BI + 1 == BE) {
5267 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5268 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005269 Info.FFDiag((*BI)->getBeginLoc(),
5270 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005271 return false;
5272 }
5273 return this->Visit(FinalExpr);
5274 }
5275
5276 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00005277 StmtResult Result = { ReturnValue, nullptr };
5278 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00005279 if (ESR != ESR_Succeeded) {
5280 // FIXME: If the statement-expression terminated due to 'return',
5281 // 'break', or 'continue', it would be nice to propagate that to
5282 // the outer statement evaluation rather than bailing out.
5283 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005284 Info.FFDiag((*BI)->getBeginLoc(),
5285 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005286 return false;
5287 }
5288 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005289
5290 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00005291 }
5292
Richard Smith4a678122011-10-24 18:44:57 +00005293 /// Visit a value which is evaluated, but whose value is ignored.
5294 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00005295 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00005296 }
David Majnemere9807b22016-02-26 04:23:19 +00005297
5298 /// Potentially visit a MemberExpr's base expression.
5299 void VisitIgnoredBaseExpression(const Expr *E) {
5300 // While MSVC doesn't evaluate the base expression, it does diagnose the
5301 // presence of side-effecting behavior.
5302 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5303 return;
5304 VisitIgnoredValue(E);
5305 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005306};
5307
Eric Fiselier0683c0e2018-05-07 21:07:10 +00005308} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00005309
5310//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005311// Common base class for lvalue and temporary evaluation.
5312//===----------------------------------------------------------------------===//
5313namespace {
5314template<class Derived>
5315class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005316 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00005317protected:
5318 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005319 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005320 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005321 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005322
5323 bool Success(APValue::LValueBase B) {
5324 Result.set(B);
5325 return true;
5326 }
5327
George Burgess IVf9013bf2017-02-10 22:52:29 +00005328 bool evaluatePointer(const Expr *E, LValue &Result) {
5329 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5330 }
5331
Richard Smith027bf112011-11-17 22:56:20 +00005332public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005333 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5334 : ExprEvaluatorBaseTy(Info), Result(Result),
5335 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005336
Richard Smith2e312c82012-03-03 22:46:17 +00005337 bool Success(const APValue &V, const Expr *E) {
5338 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005339 return true;
5340 }
Richard Smith027bf112011-11-17 22:56:20 +00005341
Richard Smith027bf112011-11-17 22:56:20 +00005342 bool VisitMemberExpr(const MemberExpr *E) {
5343 // Handle non-static data members.
5344 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005345 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005346 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005347 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005348 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005349 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005350 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005351 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005352 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005353 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005354 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005355 BaseTy = E->getBase()->getType();
5356 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005357 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005358 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005359 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005360 Result.setInvalid(E);
5361 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005362 }
Richard Smith027bf112011-11-17 22:56:20 +00005363
Richard Smith1b78b3d2012-01-25 22:15:11 +00005364 const ValueDecl *MD = E->getMemberDecl();
5365 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5366 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5367 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5368 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005369 if (!HandleLValueMember(this->Info, E, Result, FD))
5370 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005371 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005372 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5373 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005374 } else
5375 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005376
Richard Smith1b78b3d2012-01-25 22:15:11 +00005377 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005378 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005379 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005380 RefValue))
5381 return false;
5382 return Success(RefValue, E);
5383 }
5384 return true;
5385 }
5386
5387 bool VisitBinaryOperator(const BinaryOperator *E) {
5388 switch (E->getOpcode()) {
5389 default:
5390 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5391
5392 case BO_PtrMemD:
5393 case BO_PtrMemI:
5394 return HandleMemberPointerAccess(this->Info, E, Result);
5395 }
5396 }
5397
5398 bool VisitCastExpr(const CastExpr *E) {
5399 switch (E->getCastKind()) {
5400 default:
5401 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5402
5403 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005404 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005405 if (!this->Visit(E->getSubExpr()))
5406 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005407
5408 // Now figure out the necessary offset to add to the base LV to get from
5409 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005410 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5411 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005412 }
5413 }
5414};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005415}
Richard Smith027bf112011-11-17 22:56:20 +00005416
5417//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005418// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005419//
5420// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5421// function designators (in C), decl references to void objects (in C), and
5422// temporaries (if building with -Wno-address-of-temporary).
5423//
5424// LValue evaluation produces values comprising a base expression of one of the
5425// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005426// - Declarations
5427// * VarDecl
5428// * FunctionDecl
5429// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005430// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005431// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005432// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005433// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005434// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005435// * ObjCEncodeExpr
5436// * AddrLabelExpr
5437// * BlockExpr
5438// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005439// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005440// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005441// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005442// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5443// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005444// * A MaterializeTemporaryExpr that has static storage duration, with no
5445// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005446// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005447//===----------------------------------------------------------------------===//
5448namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005449class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005450 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005451public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005452 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5453 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005454
Richard Smith11562c52011-10-28 17:51:58 +00005455 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005456 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005457
Peter Collingbournee9200682011-05-13 03:29:01 +00005458 bool VisitDeclRefExpr(const DeclRefExpr *E);
5459 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005460 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005461 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5462 bool VisitMemberExpr(const MemberExpr *E);
5463 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5464 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005465 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005466 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005467 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5468 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005469 bool VisitUnaryReal(const UnaryOperator *E);
5470 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005471 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5472 return VisitUnaryPreIncDec(UO);
5473 }
5474 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5475 return VisitUnaryPreIncDec(UO);
5476 }
Richard Smith3229b742013-05-05 21:17:10 +00005477 bool VisitBinAssign(const BinaryOperator *BO);
5478 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005479
Peter Collingbournee9200682011-05-13 03:29:01 +00005480 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005481 switch (E->getCastKind()) {
5482 default:
Richard Smith027bf112011-11-17 22:56:20 +00005483 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005484
Eli Friedmance3e02a2011-10-11 00:13:24 +00005485 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005486 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005487 if (!Visit(E->getSubExpr()))
5488 return false;
5489 Result.Designator.setInvalid();
5490 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005491
Richard Smith027bf112011-11-17 22:56:20 +00005492 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005493 if (!Visit(E->getSubExpr()))
5494 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005495 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005496 }
5497 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005498};
5499} // end anonymous namespace
5500
Richard Smith11562c52011-10-28 17:51:58 +00005501/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005502/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005503/// * function designators in C, and
5504/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005505/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005506static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5507 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005508 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005509 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005510 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005511}
5512
Peter Collingbournee9200682011-05-13 03:29:01 +00005513bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005514 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005515 return Success(FD);
5516 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005517 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005518 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005519 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005520 return Error(E);
5521}
Richard Smith733237d2011-10-24 23:14:33 +00005522
Faisal Vali0528a312016-11-13 06:09:16 +00005523
Richard Smith11562c52011-10-28 17:51:58 +00005524bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005525
5526 // If we are within a lambda's call operator, check whether the 'VD' referred
5527 // to within 'E' actually represents a lambda-capture that maps to a
5528 // data-member/field within the closure object, and if so, evaluate to the
5529 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00005530 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5531 isa<DeclRefExpr>(E) &&
5532 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5533 // We don't always have a complete capture-map when checking or inferring if
5534 // the function call operator meets the requirements of a constexpr function
5535 // - but we don't need to evaluate the captures to determine constexprness
5536 // (dcl.constexpr C++17).
5537 if (Info.checkingPotentialConstantExpression())
5538 return false;
5539
Faisal Vali051e3a22017-02-16 04:12:21 +00005540 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005541 // Start with 'Result' referring to the complete closure object...
5542 Result = *Info.CurrentCall->This;
5543 // ... then update it to refer to the field of the closure object
5544 // that represents the capture.
5545 if (!HandleLValueMember(Info, E, Result, FD))
5546 return false;
5547 // And if the field is of reference type, update 'Result' to refer to what
5548 // the field refers to.
5549 if (FD->getType()->isReferenceType()) {
5550 APValue RVal;
5551 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5552 RVal))
5553 return false;
5554 Result.setFrom(Info.Ctx, RVal);
5555 }
5556 return true;
5557 }
5558 }
Craig Topper36250ad2014-05-12 05:36:57 +00005559 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005560 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5561 // Only if a local variable was declared in the function currently being
5562 // evaluated, do we expect to be able to find its value in the current
5563 // frame. (Otherwise it was likely declared in an enclosing context and
5564 // could either have a valid evaluatable value (for e.g. a constexpr
5565 // variable) or be ill-formed (and trigger an appropriate evaluation
5566 // diagnostic)).
5567 if (Info.CurrentCall->Callee &&
5568 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5569 Frame = Info.CurrentCall;
5570 }
5571 }
Richard Smith3229b742013-05-05 21:17:10 +00005572
Richard Smithfec09922011-11-01 16:57:24 +00005573 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005574 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005575 Result.set({VD, Frame->Index,
5576 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00005577 return true;
5578 }
Richard Smithce40ad62011-11-12 22:28:03 +00005579 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005580 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005581
Richard Smith3229b742013-05-05 21:17:10 +00005582 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005583 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005584 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005585 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005586 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005587 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005588 return false;
5589 }
Richard Smith3229b742013-05-05 21:17:10 +00005590 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005591}
5592
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005593bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5594 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005595 // Walk through the expression to find the materialized temporary itself.
5596 SmallVector<const Expr *, 2> CommaLHSs;
5597 SmallVector<SubobjectAdjustment, 2> Adjustments;
5598 const Expr *Inner = E->GetTemporaryExpr()->
5599 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005600
Richard Smith84401042013-06-03 05:03:02 +00005601 // If we passed any comma operators, evaluate their LHSs.
5602 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5603 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5604 return false;
5605
Richard Smithe6c01442013-06-05 00:46:14 +00005606 // A materialized temporary with static storage duration can appear within the
5607 // result of a constant expression evaluation, so we need to preserve its
5608 // value for use outside this evaluation.
5609 APValue *Value;
5610 if (E->getStorageDuration() == SD_Static) {
5611 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005612 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005613 Result.set(E);
5614 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005615 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5616 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00005617 }
5618
Richard Smithea4ad5d2013-06-06 08:19:16 +00005619 QualType Type = Inner->getType();
5620
Richard Smith84401042013-06-03 05:03:02 +00005621 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005622 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5623 (E->getStorageDuration() == SD_Static &&
5624 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5625 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005626 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005627 }
Richard Smith84401042013-06-03 05:03:02 +00005628
5629 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005630 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5631 --I;
5632 switch (Adjustments[I].Kind) {
5633 case SubobjectAdjustment::DerivedToBaseAdjustment:
5634 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5635 Type, Result))
5636 return false;
5637 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5638 break;
5639
5640 case SubobjectAdjustment::FieldAdjustment:
5641 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5642 return false;
5643 Type = Adjustments[I].Field->getType();
5644 break;
5645
5646 case SubobjectAdjustment::MemberPointerAdjustment:
5647 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5648 Adjustments[I].Ptr.RHS))
5649 return false;
5650 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5651 break;
5652 }
5653 }
5654
5655 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005656}
5657
Peter Collingbournee9200682011-05-13 03:29:01 +00005658bool
5659LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005660 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5661 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005662 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5663 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005664 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005665}
5666
Richard Smith6e525142011-12-27 12:18:28 +00005667bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005668 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005669 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005670
Faisal Valie690b7a2016-07-02 22:34:24 +00005671 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005672 << E->getExprOperand()->getType()
5673 << E->getExprOperand()->getSourceRange();
5674 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005675}
5676
Francois Pichet0066db92012-04-16 04:08:35 +00005677bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5678 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005679}
Francois Pichet0066db92012-04-16 04:08:35 +00005680
Peter Collingbournee9200682011-05-13 03:29:01 +00005681bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005682 // Handle static data members.
5683 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005684 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005685 return VisitVarDecl(E, VD);
5686 }
5687
Richard Smith254a73d2011-10-28 22:34:42 +00005688 // Handle static member functions.
5689 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5690 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005691 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005692 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005693 }
5694 }
5695
Richard Smithd62306a2011-11-10 06:34:14 +00005696 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005697 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005698}
5699
Peter Collingbournee9200682011-05-13 03:29:01 +00005700bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005701 // FIXME: Deal with vectors as array subscript bases.
5702 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005703 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005704
Nick Lewyckyad888682017-04-27 07:27:36 +00005705 bool Success = true;
5706 if (!evaluatePointer(E->getBase(), Result)) {
5707 if (!Info.noteFailure())
5708 return false;
5709 Success = false;
5710 }
Mike Stump11289f42009-09-09 15:08:12 +00005711
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005712 APSInt Index;
5713 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005714 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005715
Nick Lewyckyad888682017-04-27 07:27:36 +00005716 return Success &&
5717 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005718}
Eli Friedman9a156e52008-11-12 09:44:48 +00005719
Peter Collingbournee9200682011-05-13 03:29:01 +00005720bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005721 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005722}
5723
Richard Smith66c96992012-02-18 22:04:06 +00005724bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5725 if (!Visit(E->getSubExpr()))
5726 return false;
5727 // __real is a no-op on scalar lvalues.
5728 if (E->getSubExpr()->getType()->isAnyComplexType())
5729 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5730 return true;
5731}
5732
5733bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5734 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5735 "lvalue __imag__ on scalar?");
5736 if (!Visit(E->getSubExpr()))
5737 return false;
5738 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5739 return true;
5740}
5741
Richard Smith243ef902013-05-05 23:31:59 +00005742bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005743 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005744 return Error(UO);
5745
5746 if (!this->Visit(UO->getSubExpr()))
5747 return false;
5748
Richard Smith243ef902013-05-05 23:31:59 +00005749 return handleIncDec(
5750 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005751 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005752}
5753
5754bool LValueExprEvaluator::VisitCompoundAssignOperator(
5755 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005756 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005757 return Error(CAO);
5758
Richard Smith3229b742013-05-05 21:17:10 +00005759 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005760
5761 // The overall lvalue result is the result of evaluating the LHS.
5762 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005763 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005764 Evaluate(RHS, this->Info, CAO->getRHS());
5765 return false;
5766 }
5767
Richard Smith3229b742013-05-05 21:17:10 +00005768 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5769 return false;
5770
Richard Smith43e77732013-05-07 04:50:00 +00005771 return handleCompoundAssignment(
5772 this->Info, CAO,
5773 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5774 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005775}
5776
5777bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005778 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005779 return Error(E);
5780
Richard Smith3229b742013-05-05 21:17:10 +00005781 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005782
5783 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005784 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005785 Evaluate(NewVal, this->Info, E->getRHS());
5786 return false;
5787 }
5788
Richard Smith3229b742013-05-05 21:17:10 +00005789 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5790 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005791
5792 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005793 NewVal);
5794}
5795
Eli Friedman9a156e52008-11-12 09:44:48 +00005796//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005797// Pointer Evaluation
5798//===----------------------------------------------------------------------===//
5799
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005800/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00005801/// returned by a function with the alloc_size attribute. Returns true if we
5802/// were successful. Places an unsigned number into `Result`.
5803///
5804/// This expects the given CallExpr to be a call to a function with an
5805/// alloc_size attribute.
5806static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5807 const CallExpr *Call,
5808 llvm::APInt &Result) {
5809 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5810
Joel E. Denny81508102018-03-13 14:51:22 +00005811 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5812 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005813 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5814 if (Call->getNumArgs() <= SizeArgNo)
5815 return false;
5816
5817 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00005818 Expr::EvalResult ExprResult;
5819 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00005820 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00005821 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00005822 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5823 return false;
5824 Into = Into.zextOrSelf(BitsInSizeT);
5825 return true;
5826 };
5827
5828 APSInt SizeOfElem;
5829 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5830 return false;
5831
Joel E. Denny81508102018-03-13 14:51:22 +00005832 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005833 Result = std::move(SizeOfElem);
5834 return true;
5835 }
5836
5837 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00005838 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005839 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5840 return false;
5841
5842 bool Overflow;
5843 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5844 if (Overflow)
5845 return false;
5846
5847 Result = std::move(BytesAvailable);
5848 return true;
5849}
5850
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005851/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00005852/// function.
5853static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5854 const LValue &LVal,
5855 llvm::APInt &Result) {
5856 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5857 "Can't get the size of a non alloc_size function");
5858 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5859 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5860 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5861}
5862
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005863/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00005864/// a function with the alloc_size attribute. If it was possible to do so, this
5865/// function will return true, make Result's Base point to said function call,
5866/// and mark Result's Base as invalid.
5867static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5868 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005869 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005870 return false;
5871
5872 // Because we do no form of static analysis, we only support const variables.
5873 //
5874 // Additionally, we can't support parameters, nor can we support static
5875 // variables (in the latter case, use-before-assign isn't UB; in the former,
5876 // we have no clue what they'll be assigned to).
5877 const auto *VD =
5878 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5879 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5880 return false;
5881
5882 const Expr *Init = VD->getAnyInitializer();
5883 if (!Init)
5884 return false;
5885
5886 const Expr *E = Init->IgnoreParens();
5887 if (!tryUnwrapAllocSizeCall(E))
5888 return false;
5889
5890 // Store E instead of E unwrapped so that the type of the LValue's base is
5891 // what the user wanted.
5892 Result.setInvalid(E);
5893
5894 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005895 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005896 return true;
5897}
5898
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005899namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005900class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005901 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005902 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005903 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005904
Peter Collingbournee9200682011-05-13 03:29:01 +00005905 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005906 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005907 return true;
5908 }
George Burgess IVe3763372016-12-22 02:50:20 +00005909
George Burgess IVf9013bf2017-02-10 22:52:29 +00005910 bool evaluateLValue(const Expr *E, LValue &Result) {
5911 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5912 }
5913
5914 bool evaluatePointer(const Expr *E, LValue &Result) {
5915 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5916 }
5917
George Burgess IVe3763372016-12-22 02:50:20 +00005918 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005919public:
Mike Stump11289f42009-09-09 15:08:12 +00005920
George Burgess IVf9013bf2017-02-10 22:52:29 +00005921 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5922 : ExprEvaluatorBaseTy(info), Result(Result),
5923 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005924
Richard Smith2e312c82012-03-03 22:46:17 +00005925 bool Success(const APValue &V, const Expr *E) {
5926 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005927 return true;
5928 }
Richard Smithfddd3842011-12-30 21:15:51 +00005929 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005930 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5931 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005932 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005933 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005934
John McCall45d55e42010-05-07 21:00:08 +00005935 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005936 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005937 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005938 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005939 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005940 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00005941 if (E->isExpressibleAsConstantInitializer())
5942 return Success(E);
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005943 if (Info.noteFailure())
5944 EvaluateIgnoredValue(Info, E->getSubExpr());
5945 return Error(E);
5946 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005947 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005948 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005949 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005950 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005951 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005952 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005953 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005954 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005955 }
Richard Smithd62306a2011-11-10 06:34:14 +00005956 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005957 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005958 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005959 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005960 if (!Info.CurrentCall->This) {
5961 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005962 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005963 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005964 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005965 return false;
5966 }
Richard Smithd62306a2011-11-10 06:34:14 +00005967 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005968 // If we are inside a lambda's call operator, the 'this' expression refers
5969 // to the enclosing '*this' object (either by value or reference) which is
5970 // either copied into the closure object's field that represents the '*this'
5971 // or refers to '*this'.
5972 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5973 // Update 'Result' to refer to the data member/field of the closure object
5974 // that represents the '*this' capture.
5975 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00005976 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005977 return false;
5978 // If we captured '*this' by reference, replace the field with its referent.
5979 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5980 ->isPointerType()) {
5981 APValue RVal;
5982 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5983 RVal))
5984 return false;
5985
5986 Result.setFrom(Info.Ctx, RVal);
5987 }
5988 }
Richard Smithd62306a2011-11-10 06:34:14 +00005989 return true;
5990 }
John McCallc07a0c72011-02-17 10:25:35 +00005991
Eli Friedman449fe542009-03-23 04:56:01 +00005992 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005993};
Chris Lattner05706e882008-07-11 18:11:29 +00005994} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005995
George Burgess IVf9013bf2017-02-10 22:52:29 +00005996static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5997 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005998 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005999 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00006000}
6001
John McCall45d55e42010-05-07 21:00:08 +00006002bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00006003 if (E->getOpcode() != BO_Add &&
6004 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00006005 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00006006
Chris Lattner05706e882008-07-11 18:11:29 +00006007 const Expr *PExp = E->getLHS();
6008 const Expr *IExp = E->getRHS();
6009 if (IExp->getType()->isPointerType())
6010 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00006011
George Burgess IVf9013bf2017-02-10 22:52:29 +00006012 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00006013 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00006014 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006015
John McCall45d55e42010-05-07 21:00:08 +00006016 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00006017 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00006018 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00006019
Richard Smith96e0c102011-11-04 02:25:55 +00006020 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00006021 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00006022
Ted Kremenek28831752012-08-23 20:46:57 +00006023 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00006024 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00006025}
Eli Friedman9a156e52008-11-12 09:44:48 +00006026
John McCall45d55e42010-05-07 21:00:08 +00006027bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006028 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00006029}
Mike Stump11289f42009-09-09 15:08:12 +00006030
Richard Smith81dfef92018-07-11 00:29:05 +00006031bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6032 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00006033
Eli Friedman847a2bc2009-12-27 05:43:15 +00006034 switch (E->getCastKind()) {
6035 default:
6036 break;
6037
John McCalle3027922010-08-25 11:45:40 +00006038 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00006039 case CK_CPointerToObjCPointerCast:
6040 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00006041 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00006042 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00006043 if (!Visit(SubExpr))
6044 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00006045 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
6046 // permitted in constant expressions in C++11. Bitcasts from cv void* are
6047 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00006048 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00006049 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00006050 if (SubExpr->getType()->isVoidPointerType())
6051 CCEDiag(E, diag::note_constexpr_invalid_cast)
6052 << 3 << SubExpr->getType();
6053 else
6054 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6055 }
Yaxun Liu402804b2016-12-15 08:09:08 +00006056 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
6057 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00006058 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00006059
Anders Carlsson18275092010-10-31 20:41:46 +00006060 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00006061 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006062 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00006063 return false;
Richard Smith027bf112011-11-17 22:56:20 +00006064 if (!Result.Base && Result.Offset.isZero())
6065 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00006066
Richard Smithd62306a2011-11-10 06:34:14 +00006067 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00006068 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00006069 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
6070 castAs<PointerType>()->getPointeeType(),
6071 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00006072
Richard Smith027bf112011-11-17 22:56:20 +00006073 case CK_BaseToDerived:
6074 if (!Visit(E->getSubExpr()))
6075 return false;
6076 if (!Result.Base && Result.Offset.isZero())
6077 return true;
6078 return HandleBaseToDerivedCast(Info, E, Result);
6079
Richard Smith0b0a0b62011-10-29 20:57:55 +00006080 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006081 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006082 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00006083
John McCalle3027922010-08-25 11:45:40 +00006084 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00006085 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6086
Richard Smith2e312c82012-03-03 22:46:17 +00006087 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00006088 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00006089 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00006090
John McCall45d55e42010-05-07 21:00:08 +00006091 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00006092 unsigned Size = Info.Ctx.getTypeSize(E->getType());
6093 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006094 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006095 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00006096 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00006097 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00006098 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00006099 return true;
6100 } else {
6101 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00006102 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00006103 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00006104 }
6105 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00006106
6107 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00006108 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00006109 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00006110 return false;
6111 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006112 APValue &Value = createTemporary(SubExpr, false, Result,
6113 *Info.CurrentCall);
6114 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00006115 return false;
6116 }
Richard Smith96e0c102011-11-04 02:25:55 +00006117 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00006118 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
6119 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00006120 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00006121 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00006122 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00006123 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00006124 }
Richard Smithdd785442011-10-31 20:57:44 +00006125
John McCalle3027922010-08-25 11:45:40 +00006126 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006127 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00006128
6129 case CK_LValueToRValue: {
6130 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006131 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00006132 return false;
6133
6134 APValue RVal;
6135 // Note, we use the subexpression's type in order to retain cv-qualifiers.
6136 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6137 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00006138 return InvalidBaseOK &&
6139 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00006140 return Success(RVal, E);
6141 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006142 }
6143
Richard Smith11562c52011-10-28 17:51:58 +00006144 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00006145}
Chris Lattner05706e882008-07-11 18:11:29 +00006146
Richard Smith6822bd72018-10-26 19:26:45 +00006147static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
6148 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006149 // C++ [expr.alignof]p3:
6150 // When alignof is applied to a reference type, the result is the
6151 // alignment of the referenced type.
6152 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6153 T = Ref->getPointeeType();
6154
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00006155 if (T.getQualifiers().hasUnaligned())
6156 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00006157
6158 const bool AlignOfReturnsPreferred =
6159 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
6160
6161 // __alignof is defined to return the preferred alignment.
6162 // Before 8, clang returned the preferred alignment for alignof and _Alignof
6163 // as well.
6164 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
6165 return Info.Ctx.toCharUnitsFromBits(
6166 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6167 // alignof and _Alignof are defined to return the ABI alignment.
6168 else if (ExprKind == UETT_AlignOf)
6169 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
6170 else
6171 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00006172}
6173
Richard Smith6822bd72018-10-26 19:26:45 +00006174static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
6175 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006176 E = E->IgnoreParens();
6177
6178 // The kinds of expressions that we have special-case logic here for
6179 // should be kept up to date with the special checks for those
6180 // expressions in Sema.
6181
6182 // alignof decl is always accepted, even if it doesn't make sense: we default
6183 // to 1 in those cases.
6184 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6185 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6186 /*RefAsPointee*/true);
6187
6188 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6189 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6190 /*RefAsPointee*/true);
6191
Richard Smith6822bd72018-10-26 19:26:45 +00006192 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006193}
6194
George Burgess IVe3763372016-12-22 02:50:20 +00006195// To be clear: this happily visits unsupported builtins. Better name welcomed.
6196bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6197 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6198 return true;
6199
George Burgess IVf9013bf2017-02-10 22:52:29 +00006200 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00006201 return false;
6202
6203 Result.setInvalid(E);
6204 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006205 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00006206 return true;
6207}
6208
Peter Collingbournee9200682011-05-13 03:29:01 +00006209bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006210 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00006211 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00006212
Richard Smith6328cbd2016-11-16 00:57:23 +00006213 if (unsigned BuiltinOp = E->getBuiltinCallee())
6214 return VisitBuiltinCallExpr(E, BuiltinOp);
6215
George Burgess IVe3763372016-12-22 02:50:20 +00006216 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006217}
6218
6219bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6220 unsigned BuiltinOp) {
6221 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00006222 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006223 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006224 case Builtin::BI__builtin_assume_aligned: {
6225 // We need to be very careful here because: if the pointer does not have the
6226 // asserted alignment, then the behavior is undefined, and undefined
6227 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00006228 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00006229 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00006230
Hal Finkel0dd05d42014-10-03 17:18:37 +00006231 LValue OffsetResult(Result);
6232 APSInt Alignment;
6233 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6234 return false;
Richard Smith642a2362017-01-30 23:30:26 +00006235 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00006236
6237 if (E->getNumArgs() > 2) {
6238 APSInt Offset;
6239 if (!EvaluateInteger(E->getArg(2), Offset, Info))
6240 return false;
6241
Richard Smith642a2362017-01-30 23:30:26 +00006242 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006243 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6244 }
6245
6246 // If there is a base object, then it must have the correct alignment.
6247 if (OffsetResult.Base) {
6248 CharUnits BaseAlignment;
6249 if (const ValueDecl *VD =
6250 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6251 BaseAlignment = Info.Ctx.getDeclAlign(VD);
6252 } else {
Richard Smith6822bd72018-10-26 19:26:45 +00006253 BaseAlignment = GetAlignOfExpr(
6254 Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006255 }
6256
6257 if (BaseAlignment < Align) {
6258 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00006259 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00006260 CCEDiag(E->getArg(0),
6261 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00006262 << (unsigned)BaseAlignment.getQuantity()
6263 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006264 return false;
6265 }
6266 }
6267
6268 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006269 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006270 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006271
Richard Smith642a2362017-01-30 23:30:26 +00006272 (OffsetResult.Base
6273 ? CCEDiag(E->getArg(0),
6274 diag::note_constexpr_baa_insufficient_alignment) << 1
6275 : CCEDiag(E->getArg(0),
6276 diag::note_constexpr_baa_value_insufficient_alignment))
6277 << (int)OffsetResult.Offset.getQuantity()
6278 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006279 return false;
6280 }
6281
6282 return true;
6283 }
Eric Fiselier26187502018-12-14 21:11:28 +00006284 case Builtin::BI__builtin_launder:
6285 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00006286 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006287 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00006288 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006289 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00006290 if (Info.getLangOpts().CPlusPlus11)
6291 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6292 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00006293 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00006294 else
6295 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006296 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00006297 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006298 case Builtin::BI__builtin_wcschr:
6299 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006300 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006301 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00006302 if (!Visit(E->getArg(0)))
6303 return false;
6304 APSInt Desired;
6305 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6306 return false;
6307 uint64_t MaxLength = uint64_t(-1);
6308 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00006309 BuiltinOp != Builtin::BIwcschr &&
6310 BuiltinOp != Builtin::BI__builtin_strchr &&
6311 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00006312 APSInt N;
6313 if (!EvaluateInteger(E->getArg(2), N, Info))
6314 return false;
6315 MaxLength = N.getExtValue();
6316 }
Hubert Tong147b7432018-12-12 16:53:43 +00006317 // We cannot find the value if there are no candidates to match against.
6318 if (MaxLength == 0u)
6319 return ZeroInitialization(E);
6320 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
6321 Result.Designator.Invalid)
6322 return false;
6323 QualType CharTy = Result.Designator.getType(Info.Ctx);
6324 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
6325 BuiltinOp == Builtin::BI__builtin_memchr;
6326 assert(IsRawByte ||
6327 Info.Ctx.hasSameUnqualifiedType(
6328 CharTy, E->getArg(0)->getType()->getPointeeType()));
6329 // Pointers to const void may point to objects of incomplete type.
6330 if (IsRawByte && CharTy->isIncompleteType()) {
6331 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
6332 return false;
6333 }
6334 // Give up on byte-oriented matching against multibyte elements.
6335 // FIXME: We can compare the bytes in the correct order.
6336 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
6337 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00006338 // Figure out what value we're actually looking for (after converting to
6339 // the corresponding unsigned type if necessary).
6340 uint64_t DesiredVal;
6341 bool StopAtNull = false;
6342 switch (BuiltinOp) {
6343 case Builtin::BIstrchr:
6344 case Builtin::BI__builtin_strchr:
6345 // strchr compares directly to the passed integer, and therefore
6346 // always fails if given an int that is not a char.
6347 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6348 E->getArg(1)->getType(),
6349 Desired),
6350 Desired))
6351 return ZeroInitialization(E);
6352 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006353 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006354 case Builtin::BImemchr:
6355 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006356 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006357 // memchr compares by converting both sides to unsigned char. That's also
6358 // correct for strchr if we get this far (to cope with plain char being
6359 // unsigned in the strchr case).
6360 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6361 break;
Richard Smithe9507952016-11-12 01:39:56 +00006362
Richard Smith8110c9d2016-11-29 19:45:17 +00006363 case Builtin::BIwcschr:
6364 case Builtin::BI__builtin_wcschr:
6365 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006366 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006367 case Builtin::BIwmemchr:
6368 case Builtin::BI__builtin_wmemchr:
6369 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6370 DesiredVal = Desired.getZExtValue();
6371 break;
6372 }
Richard Smithe9507952016-11-12 01:39:56 +00006373
6374 for (; MaxLength; --MaxLength) {
6375 APValue Char;
6376 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6377 !Char.isInt())
6378 return false;
6379 if (Char.getInt().getZExtValue() == DesiredVal)
6380 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006381 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006382 break;
6383 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6384 return false;
6385 }
6386 // Not found: return nullptr.
6387 return ZeroInitialization(E);
6388 }
6389
Richard Smith06f71b52018-08-04 00:57:17 +00006390 case Builtin::BImemcpy:
6391 case Builtin::BImemmove:
6392 case Builtin::BIwmemcpy:
6393 case Builtin::BIwmemmove:
6394 if (Info.getLangOpts().CPlusPlus11)
6395 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6396 << /*isConstexpr*/0 << /*isConstructor*/0
6397 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6398 else
6399 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6400 LLVM_FALLTHROUGH;
6401 case Builtin::BI__builtin_memcpy:
6402 case Builtin::BI__builtin_memmove:
6403 case Builtin::BI__builtin_wmemcpy:
6404 case Builtin::BI__builtin_wmemmove: {
6405 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6406 BuiltinOp == Builtin::BIwmemmove ||
6407 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6408 BuiltinOp == Builtin::BI__builtin_wmemmove;
6409 bool Move = BuiltinOp == Builtin::BImemmove ||
6410 BuiltinOp == Builtin::BIwmemmove ||
6411 BuiltinOp == Builtin::BI__builtin_memmove ||
6412 BuiltinOp == Builtin::BI__builtin_wmemmove;
6413
6414 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00006415 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00006416 return false;
6417 LValue Dest = Result;
6418
6419 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00006420 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00006421 return false;
6422
6423 APSInt N;
6424 if (!EvaluateInteger(E->getArg(2), N, Info))
6425 return false;
6426 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6427
6428 // If the size is zero, we treat this as always being a valid no-op.
6429 // (Even if one of the src and dest pointers is null.)
6430 if (!N)
6431 return true;
6432
Richard Smith128719c2018-09-13 22:47:33 +00006433 // Otherwise, if either of the operands is null, we can't proceed. Don't
6434 // try to determine the type of the copied objects, because there aren't
6435 // any.
6436 if (!Src.Base || !Dest.Base) {
6437 APValue Val;
6438 (!Src.Base ? Src : Dest).moveInto(Val);
6439 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6440 << Move << WChar << !!Src.Base
6441 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6442 return false;
6443 }
6444 if (Src.Designator.Invalid || Dest.Designator.Invalid)
6445 return false;
6446
Richard Smith06f71b52018-08-04 00:57:17 +00006447 // We require that Src and Dest are both pointers to arrays of
6448 // trivially-copyable type. (For the wide version, the designator will be
6449 // invalid if the designated object is not a wchar_t.)
6450 QualType T = Dest.Designator.getType(Info.Ctx);
6451 QualType SrcT = Src.Designator.getType(Info.Ctx);
6452 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6453 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6454 return false;
6455 }
Petr Pavlued083f22018-10-04 09:25:44 +00006456 if (T->isIncompleteType()) {
6457 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6458 return false;
6459 }
Richard Smith06f71b52018-08-04 00:57:17 +00006460 if (!T.isTriviallyCopyableType(Info.Ctx)) {
6461 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6462 return false;
6463 }
6464
6465 // Figure out how many T's we're copying.
6466 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6467 if (!WChar) {
6468 uint64_t Remainder;
6469 llvm::APInt OrigN = N;
6470 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6471 if (Remainder) {
6472 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6473 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6474 << (unsigned)TSize;
6475 return false;
6476 }
6477 }
6478
6479 // Check that the copying will remain within the arrays, just so that we
6480 // can give a more meaningful diagnostic. This implicitly also checks that
6481 // N fits into 64 bits.
6482 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6483 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6484 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6485 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6486 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6487 << N.toString(10, /*Signed*/false);
6488 return false;
6489 }
6490 uint64_t NElems = N.getZExtValue();
6491 uint64_t NBytes = NElems * TSize;
6492
6493 // Check for overlap.
6494 int Direction = 1;
6495 if (HasSameBase(Src, Dest)) {
6496 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6497 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6498 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6499 // Dest is inside the source region.
6500 if (!Move) {
6501 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6502 return false;
6503 }
6504 // For memmove and friends, copy backwards.
6505 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6506 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6507 return false;
6508 Direction = -1;
6509 } else if (!Move && SrcOffset >= DestOffset &&
6510 SrcOffset - DestOffset < NBytes) {
6511 // Src is inside the destination region for memcpy: invalid.
6512 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6513 return false;
6514 }
6515 }
6516
6517 while (true) {
6518 APValue Val;
6519 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6520 !handleAssignment(Info, E, Dest, T, Val))
6521 return false;
6522 // Do not iterate past the last element; if we're copying backwards, that
6523 // might take us off the start of the array.
6524 if (--NElems == 0)
6525 return true;
6526 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6527 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6528 return false;
6529 }
6530 }
6531
Richard Smith6cbd65d2013-07-11 02:27:57 +00006532 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006533 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006534 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006535}
Chris Lattner05706e882008-07-11 18:11:29 +00006536
6537//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006538// Member Pointer Evaluation
6539//===----------------------------------------------------------------------===//
6540
6541namespace {
6542class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006543 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006544 MemberPtr &Result;
6545
6546 bool Success(const ValueDecl *D) {
6547 Result = MemberPtr(D);
6548 return true;
6549 }
6550public:
6551
6552 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6553 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6554
Richard Smith2e312c82012-03-03 22:46:17 +00006555 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006556 Result.setFrom(V);
6557 return true;
6558 }
Richard Smithfddd3842011-12-30 21:15:51 +00006559 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006560 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006561 }
6562
6563 bool VisitCastExpr(const CastExpr *E);
6564 bool VisitUnaryAddrOf(const UnaryOperator *E);
6565};
6566} // end anonymous namespace
6567
6568static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6569 EvalInfo &Info) {
6570 assert(E->isRValue() && E->getType()->isMemberPointerType());
6571 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6572}
6573
6574bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6575 switch (E->getCastKind()) {
6576 default:
6577 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6578
6579 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006580 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006581 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006582
6583 case CK_BaseToDerivedMemberPointer: {
6584 if (!Visit(E->getSubExpr()))
6585 return false;
6586 if (E->path_empty())
6587 return true;
6588 // Base-to-derived member pointer casts store the path in derived-to-base
6589 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6590 // the wrong end of the derived->base arc, so stagger the path by one class.
6591 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6592 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6593 PathI != PathE; ++PathI) {
6594 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6595 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6596 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006597 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006598 }
6599 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6600 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006601 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006602 return true;
6603 }
6604
6605 case CK_DerivedToBaseMemberPointer:
6606 if (!Visit(E->getSubExpr()))
6607 return false;
6608 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6609 PathE = E->path_end(); PathI != PathE; ++PathI) {
6610 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6611 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6612 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006613 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006614 }
6615 return true;
6616 }
6617}
6618
6619bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6620 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6621 // member can be formed.
6622 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6623}
6624
6625//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006626// Record Evaluation
6627//===----------------------------------------------------------------------===//
6628
6629namespace {
6630 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006631 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006632 const LValue &This;
6633 APValue &Result;
6634 public:
6635
6636 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6637 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6638
Richard Smith2e312c82012-03-03 22:46:17 +00006639 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006640 Result = V;
6641 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006642 }
Richard Smithb8348f52016-05-12 22:16:28 +00006643 bool ZeroInitialization(const Expr *E) {
6644 return ZeroInitialization(E, E->getType());
6645 }
6646 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006647
Richard Smith52a980a2015-08-28 02:43:42 +00006648 bool VisitCallExpr(const CallExpr *E) {
6649 return handleCallExpr(E, Result, &This);
6650 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006651 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006652 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006653 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6654 return VisitCXXConstructExpr(E, E->getType());
6655 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006656 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006657 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006658 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006659 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006660
6661 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006662 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006663}
Richard Smithd62306a2011-11-10 06:34:14 +00006664
Richard Smithfddd3842011-12-30 21:15:51 +00006665/// Perform zero-initialization on an object of non-union class type.
6666/// C++11 [dcl.init]p5:
6667/// To zero-initialize an object or reference of type T means:
6668/// [...]
6669/// -- if T is a (possibly cv-qualified) non-union class type,
6670/// each non-static data member and each base-class subobject is
6671/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006672static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6673 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006674 const LValue &This, APValue &Result) {
6675 assert(!RD->isUnion() && "Expected non-union class type");
6676 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6677 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006678 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006679
John McCalld7bca762012-05-01 00:38:49 +00006680 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006681 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6682
6683 if (CD) {
6684 unsigned Index = 0;
6685 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006686 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006687 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6688 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006689 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6690 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006691 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006692 Result.getStructBase(Index)))
6693 return false;
6694 }
6695 }
6696
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006697 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006698 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006699 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006700 continue;
6701
6702 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006703 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006704 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006705
David Blaikie2d7c57e2012-04-30 02:36:29 +00006706 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006707 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006708 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006709 return false;
6710 }
6711
6712 return true;
6713}
6714
Richard Smithb8348f52016-05-12 22:16:28 +00006715bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6716 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006717 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006718 if (RD->isUnion()) {
6719 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6720 // object's first non-static named data member is zero-initialized
6721 RecordDecl::field_iterator I = RD->field_begin();
6722 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006723 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006724 return true;
6725 }
6726
6727 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006728 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006729 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006730 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006731 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006732 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006733 }
6734
Richard Smith5d108602012-02-17 00:44:16 +00006735 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006736 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006737 return false;
6738 }
6739
Richard Smitha8105bc2012-01-06 16:39:00 +00006740 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006741}
6742
Richard Smithe97cbd72011-11-11 04:05:33 +00006743bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6744 switch (E->getCastKind()) {
6745 default:
6746 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6747
6748 case CK_ConstructorConversion:
6749 return Visit(E->getSubExpr());
6750
6751 case CK_DerivedToBase:
6752 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006753 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006754 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006755 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006756 if (!DerivedObject.isStruct())
6757 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006758
6759 // Derived-to-base rvalue conversion: just slice off the derived part.
6760 APValue *Value = &DerivedObject;
6761 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6762 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6763 PathE = E->path_end(); PathI != PathE; ++PathI) {
6764 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6765 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6766 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6767 RD = Base;
6768 }
6769 Result = *Value;
6770 return true;
6771 }
6772 }
6773}
6774
Richard Smithd62306a2011-11-10 06:34:14 +00006775bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006776 if (E->isTransparent())
6777 return Visit(E->getInit(0));
6778
Richard Smithd62306a2011-11-10 06:34:14 +00006779 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006780 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006781 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006782 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6783
6784 EvalInfo::EvaluatingConstructorRAII EvalObj(
6785 Info,
6786 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6787 CXXRD && CXXRD->getNumBases());
Richard Smithd62306a2011-11-10 06:34:14 +00006788
6789 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006790 const FieldDecl *Field = E->getInitializedFieldInUnion();
6791 Result = APValue(Field);
6792 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006793 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006794
6795 // If the initializer list for a union does not contain any elements, the
6796 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006797 // FIXME: The element should be initialized from an initializer list.
6798 // Is this difference ever observable for initializer lists which
6799 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006800 ImplicitValueInitExpr VIE(Field->getType());
6801 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6802
Richard Smithd62306a2011-11-10 06:34:14 +00006803 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006804 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6805 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006806
6807 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6808 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6809 isa<CXXDefaultInitExpr>(InitExpr));
6810
Richard Smithb228a862012-02-15 02:18:13 +00006811 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006812 }
6813
Richard Smithc0d04a22016-05-25 22:06:25 +00006814 if (Result.isUninit())
6815 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6816 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006817 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006818 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006819
6820 // Initialize base classes.
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006821 if (CXXRD && CXXRD->getNumBases()) {
Richard Smith872307e2016-03-08 22:17:41 +00006822 for (const auto &Base : CXXRD->bases()) {
6823 assert(ElementNo < E->getNumInits() && "missing init for base class");
6824 const Expr *Init = E->getInit(ElementNo);
6825
6826 LValue Subobject = This;
6827 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6828 return false;
6829
6830 APValue &FieldVal = Result.getStructBase(ElementNo);
6831 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006832 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006833 return false;
6834 Success = false;
6835 }
6836 ++ElementNo;
6837 }
Richard Smithd3d6f4f2019-05-12 08:57:59 +00006838
6839 EvalObj.finishedConstructingBases();
Richard Smith872307e2016-03-08 22:17:41 +00006840 }
6841
6842 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006843 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006844 // Anonymous bit-fields are not considered members of the class for
6845 // purposes of aggregate initialization.
6846 if (Field->isUnnamedBitfield())
6847 continue;
6848
6849 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006850
Richard Smith253c2a32012-01-27 01:14:48 +00006851 bool HaveInit = ElementNo < E->getNumInits();
6852
6853 // FIXME: Diagnostics here should point to the end of the initializer
6854 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006855 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006856 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006857 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006858
6859 // Perform an implicit value-initialization for members beyond the end of
6860 // the initializer list.
6861 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006862 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006863
Richard Smith852c9db2013-04-20 22:23:05 +00006864 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6865 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6866 isa<CXXDefaultInitExpr>(Init));
6867
Richard Smith49ca8aa2013-08-06 07:09:20 +00006868 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6869 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6870 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006871 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006872 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006873 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006874 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006875 }
6876 }
6877
Richard Smith253c2a32012-01-27 01:14:48 +00006878 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006879}
6880
Richard Smithb8348f52016-05-12 22:16:28 +00006881bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6882 QualType T) {
6883 // Note that E's type is not necessarily the type of our class here; we might
6884 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006885 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006886 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6887
Richard Smithfddd3842011-12-30 21:15:51 +00006888 bool ZeroInit = E->requiresZeroInitialization();
6889 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006890 // If we've already performed zero-initialization, we're already done.
6891 if (!Result.isUninit())
6892 return true;
6893
Richard Smithda3f4fd2014-03-05 23:32:50 +00006894 // We can get here in two different ways:
6895 // 1) We're performing value-initialization, and should zero-initialize
6896 // the object, or
6897 // 2) We're performing default-initialization of an object with a trivial
6898 // constexpr default constructor, in which case we should start the
6899 // lifetimes of all the base subobjects (there can be no data member
6900 // subobjects in this case) per [basic.life]p1.
6901 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006902 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006903 }
6904
Craig Topper36250ad2014-05-12 05:36:57 +00006905 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006906 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006907
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006908 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006909 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006910
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006911 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006912 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006913 if (const MaterializeTemporaryExpr *ME
6914 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6915 return Visit(ME->GetTemporaryExpr());
6916
Richard Smithb8348f52016-05-12 22:16:28 +00006917 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006918 return false;
6919
Craig Topper5fc8fc22014-08-27 06:28:36 +00006920 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006921 return HandleConstructorCall(E, This, Args,
6922 cast<CXXConstructorDecl>(Definition), Info,
6923 Result);
6924}
6925
6926bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6927 const CXXInheritedCtorInitExpr *E) {
6928 if (!Info.CurrentCall) {
6929 assert(Info.checkingPotentialConstantExpression());
6930 return false;
6931 }
6932
6933 const CXXConstructorDecl *FD = E->getConstructor();
6934 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6935 return false;
6936
6937 const FunctionDecl *Definition = nullptr;
6938 auto Body = FD->getBody(Definition);
6939
6940 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6941 return false;
6942
6943 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006944 cast<CXXConstructorDecl>(Definition), Info,
6945 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006946}
6947
Richard Smithcc1b96d2013-06-12 22:31:48 +00006948bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6949 const CXXStdInitializerListExpr *E) {
6950 const ConstantArrayType *ArrayType =
6951 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6952
6953 LValue Array;
6954 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6955 return false;
6956
6957 // Get a pointer to the first element of the array.
6958 Array.addArray(Info, E, ArrayType);
6959
6960 // FIXME: Perform the checks on the field types in SemaInit.
6961 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6962 RecordDecl::field_iterator Field = Record->field_begin();
6963 if (Field == Record->field_end())
6964 return Error(E);
6965
6966 // Start pointer.
6967 if (!Field->getType()->isPointerType() ||
6968 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6969 ArrayType->getElementType()))
6970 return Error(E);
6971
6972 // FIXME: What if the initializer_list type has base classes, etc?
6973 Result = APValue(APValue::UninitStruct(), 0, 2);
6974 Array.moveInto(Result.getStructField(0));
6975
6976 if (++Field == Record->field_end())
6977 return Error(E);
6978
6979 if (Field->getType()->isPointerType() &&
6980 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6981 ArrayType->getElementType())) {
6982 // End pointer.
6983 if (!HandleLValueArrayAdjustment(Info, E, Array,
6984 ArrayType->getElementType(),
6985 ArrayType->getSize().getZExtValue()))
6986 return false;
6987 Array.moveInto(Result.getStructField(1));
6988 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6989 // Length.
6990 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6991 else
6992 return Error(E);
6993
6994 if (++Field != Record->field_end())
6995 return Error(E);
6996
6997 return true;
6998}
6999
Faisal Valic72a08c2017-01-09 03:02:53 +00007000bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
7001 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
7002 if (ClosureClass->isInvalidDecl()) return false;
7003
7004 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00007005
Faisal Vali051e3a22017-02-16 04:12:21 +00007006 const size_t NumFields =
7007 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00007008
7009 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
7010 E->capture_init_end()) &&
7011 "The number of lambda capture initializers should equal the number of "
7012 "fields within the closure type");
7013
Faisal Vali051e3a22017-02-16 04:12:21 +00007014 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
7015 // Iterate through all the lambda's closure object's fields and initialize
7016 // them.
7017 auto *CaptureInitIt = E->capture_init_begin();
7018 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
7019 bool Success = true;
7020 for (const auto *Field : ClosureClass->fields()) {
7021 assert(CaptureInitIt != E->capture_init_end());
7022 // Get the initializer for this field
7023 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00007024
Faisal Vali051e3a22017-02-16 04:12:21 +00007025 // If there is no initializer, either this is a VLA or an error has
7026 // occurred.
7027 if (!CurFieldInit)
7028 return Error(E);
7029
7030 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7031 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
7032 if (!Info.keepEvaluatingAfterFailure())
7033 return false;
7034 Success = false;
7035 }
7036 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00007037 }
Faisal Vali051e3a22017-02-16 04:12:21 +00007038 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00007039}
7040
Richard Smithd62306a2011-11-10 06:34:14 +00007041static bool EvaluateRecord(const Expr *E, const LValue &This,
7042 APValue &Result, EvalInfo &Info) {
7043 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00007044 "can't evaluate expression as a record rvalue");
7045 return RecordExprEvaluator(Info, This, Result).Visit(E);
7046}
7047
7048//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00007049// Temporary Evaluation
7050//
7051// Temporaries are represented in the AST as rvalues, but generally behave like
7052// lvalues. The full-object of which the temporary is a subobject is implicitly
7053// materialized so that a reference can bind to it.
7054//===----------------------------------------------------------------------===//
7055namespace {
7056class TemporaryExprEvaluator
7057 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
7058public:
7059 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00007060 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00007061
7062 /// Visit an expression which constructs the value of this temporary.
7063 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00007064 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
7065 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00007066 }
7067
7068 bool VisitCastExpr(const CastExpr *E) {
7069 switch (E->getCastKind()) {
7070 default:
7071 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7072
7073 case CK_ConstructorConversion:
7074 return VisitConstructExpr(E->getSubExpr());
7075 }
7076 }
7077 bool VisitInitListExpr(const InitListExpr *E) {
7078 return VisitConstructExpr(E);
7079 }
7080 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7081 return VisitConstructExpr(E);
7082 }
7083 bool VisitCallExpr(const CallExpr *E) {
7084 return VisitConstructExpr(E);
7085 }
Richard Smith513955c2014-12-17 19:24:30 +00007086 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
7087 return VisitConstructExpr(E);
7088 }
Faisal Valic72a08c2017-01-09 03:02:53 +00007089 bool VisitLambdaExpr(const LambdaExpr *E) {
7090 return VisitConstructExpr(E);
7091 }
Richard Smith027bf112011-11-17 22:56:20 +00007092};
7093} // end anonymous namespace
7094
7095/// Evaluate an expression of record type as a temporary.
7096static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00007097 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00007098 return TemporaryExprEvaluator(Info, Result).Visit(E);
7099}
7100
7101//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007102// Vector Evaluation
7103//===----------------------------------------------------------------------===//
7104
7105namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007106 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007107 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00007108 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007109 public:
Mike Stump11289f42009-09-09 15:08:12 +00007110
Richard Smith2d406342011-10-22 21:10:00 +00007111 VectorExprEvaluator(EvalInfo &info, APValue &Result)
7112 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00007113
Craig Topper9798b932015-09-29 04:30:05 +00007114 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007115 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
7116 // FIXME: remove this APValue copy.
7117 Result = APValue(V.data(), V.size());
7118 return true;
7119 }
Richard Smith2e312c82012-03-03 22:46:17 +00007120 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00007121 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00007122 Result = V;
7123 return true;
7124 }
Richard Smithfddd3842011-12-30 21:15:51 +00007125 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00007126
Richard Smith2d406342011-10-22 21:10:00 +00007127 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00007128 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00007129 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00007130 bool VisitInitListExpr(const InitListExpr *E);
7131 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007132 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00007133 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00007134 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007135 };
7136} // end anonymous namespace
7137
7138static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007139 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00007140 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007141}
7142
George Burgess IV533ff002015-12-11 00:23:35 +00007143bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007144 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00007145 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007146
Richard Smith161f09a2011-12-06 22:44:34 +00007147 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00007148 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007149
Eli Friedmanc757de22011-03-25 00:43:55 +00007150 switch (E->getCastKind()) {
7151 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00007152 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00007153 if (SETy->isIntegerType()) {
7154 APSInt IntResult;
7155 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00007156 return false;
7157 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00007158 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00007159 APFloat FloatResult(0.0);
7160 if (!EvaluateFloat(SE, FloatResult, Info))
7161 return false;
7162 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00007163 } else {
Richard Smith2d406342011-10-22 21:10:00 +00007164 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007165 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00007166
7167 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00007168 SmallVector<APValue, 4> Elts(NElts, Val);
7169 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00007170 }
Eli Friedman803acb32011-12-22 03:51:45 +00007171 case CK_BitCast: {
7172 // Evaluate the operand into an APInt we can extract from.
7173 llvm::APInt SValInt;
7174 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
7175 return false;
7176 // Extract the elements
7177 QualType EltTy = VTy->getElementType();
7178 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
7179 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7180 SmallVector<APValue, 4> Elts;
7181 if (EltTy->isRealFloatingType()) {
7182 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00007183 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00007184 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00007185 FloatEltSize = 80;
7186 for (unsigned i = 0; i < NElts; i++) {
7187 llvm::APInt Elt;
7188 if (BigEndian)
7189 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
7190 else
7191 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00007192 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00007193 }
7194 } else if (EltTy->isIntegerType()) {
7195 for (unsigned i = 0; i < NElts; i++) {
7196 llvm::APInt Elt;
7197 if (BigEndian)
7198 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
7199 else
7200 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
7201 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
7202 }
7203 } else {
7204 return Error(E);
7205 }
7206 return Success(Elts, E);
7207 }
Eli Friedmanc757de22011-03-25 00:43:55 +00007208 default:
Richard Smith11562c52011-10-28 17:51:58 +00007209 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007210 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007211}
7212
Richard Smith2d406342011-10-22 21:10:00 +00007213bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007214VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007215 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007216 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00007217 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007218
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007219 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007220 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007221
Eli Friedmanb9c71292012-01-03 23:24:20 +00007222 // The number of initializers can be less than the number of
7223 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00007224 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00007225 // should be initialized with zeroes.
7226 unsigned CountInits = 0, CountElts = 0;
7227 while (CountElts < NumElements) {
7228 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00007229 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00007230 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00007231 APValue v;
7232 if (!EvaluateVector(E->getInit(CountInits), v, Info))
7233 return Error(E);
7234 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00007235 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00007236 Elements.push_back(v.getVectorElt(j));
7237 CountElts += vlen;
7238 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007239 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007240 if (CountInits < NumInits) {
7241 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007242 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007243 } else // trailing integer zero.
7244 sInt = Info.Ctx.MakeIntValue(0, EltTy);
7245 Elements.push_back(APValue(sInt));
7246 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007247 } else {
7248 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007249 if (CountInits < NumInits) {
7250 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007251 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007252 } else // trailing float zero.
7253 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7254 Elements.push_back(APValue(f));
7255 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00007256 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00007257 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007258 }
Richard Smith2d406342011-10-22 21:10:00 +00007259 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007260}
7261
Richard Smith2d406342011-10-22 21:10:00 +00007262bool
Richard Smithfddd3842011-12-30 21:15:51 +00007263VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007264 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00007265 QualType EltTy = VT->getElementType();
7266 APValue ZeroElement;
7267 if (EltTy->isIntegerType())
7268 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7269 else
7270 ZeroElement =
7271 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7272
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007273 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00007274 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007275}
7276
Richard Smith2d406342011-10-22 21:10:00 +00007277bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00007278 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007279 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007280}
7281
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007282//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00007283// Array Evaluation
7284//===----------------------------------------------------------------------===//
7285
7286namespace {
7287 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007288 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007289 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00007290 APValue &Result;
7291 public:
7292
Richard Smithd62306a2011-11-10 06:34:14 +00007293 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7294 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00007295
7296 bool Success(const APValue &V, const Expr *E) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00007297 assert(V.isArray() && "expected array");
Richard Smithf3e9e432011-11-07 09:22:26 +00007298 Result = V;
7299 return true;
7300 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007301
Richard Smithfddd3842011-12-30 21:15:51 +00007302 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007303 const ConstantArrayType *CAT =
7304 Info.Ctx.getAsConstantArrayType(E->getType());
7305 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007306 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007307
7308 Result = APValue(APValue::UninitArray(), 0,
7309 CAT->getSize().getZExtValue());
7310 if (!Result.hasArrayFiller()) return true;
7311
Richard Smithfddd3842011-12-30 21:15:51 +00007312 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00007313 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007314 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00007315 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00007316 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00007317 }
7318
Richard Smith52a980a2015-08-28 02:43:42 +00007319 bool VisitCallExpr(const CallExpr *E) {
7320 return handleCallExpr(E, Result, &This);
7321 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007322 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00007323 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00007324 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00007325 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7326 const LValue &Subobject,
7327 APValue *Value, QualType Type);
Eli Friedman3bf72d72019-02-08 21:18:46 +00007328 bool VisitStringLiteral(const StringLiteral *E) {
7329 expandStringLiteral(Info, E, Result);
7330 return true;
7331 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007332 };
7333} // end anonymous namespace
7334
Richard Smithd62306a2011-11-10 06:34:14 +00007335static bool EvaluateArray(const Expr *E, const LValue &This,
7336 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00007337 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00007338 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007339}
7340
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007341// Return true iff the given array filler may depend on the element index.
7342static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7343 // For now, just whitelist non-class value-initialization and initialization
7344 // lists comprised of them.
7345 if (isa<ImplicitValueInitExpr>(FillerExpr))
7346 return false;
7347 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7348 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7349 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7350 return true;
7351 }
7352 return false;
7353 }
7354 return true;
7355}
7356
Richard Smithf3e9e432011-11-07 09:22:26 +00007357bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7358 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7359 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007360 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007361
Richard Smithca2cfbf2011-12-22 01:07:19 +00007362 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7363 // an appropriately-typed string literal enclosed in braces.
Eli Friedman3bf72d72019-02-08 21:18:46 +00007364 if (E->isStringLiteralInit())
7365 return Visit(E->getInit(0));
Richard Smithca2cfbf2011-12-22 01:07:19 +00007366
Richard Smith253c2a32012-01-27 01:14:48 +00007367 bool Success = true;
7368
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007369 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7370 "zero-initialized array shouldn't have any initialized elts");
7371 APValue Filler;
7372 if (Result.isArray() && Result.hasArrayFiller())
7373 Filler = Result.getArrayFiller();
7374
Richard Smith9543c5e2013-04-22 14:44:29 +00007375 unsigned NumEltsToInit = E->getNumInits();
7376 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007377 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00007378
7379 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007380 // array element.
7381 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00007382 NumEltsToInit = NumElts;
7383
Nicola Zaghen3538b392018-05-15 13:30:56 +00007384 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7385 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007386
Richard Smith9543c5e2013-04-22 14:44:29 +00007387 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007388
7389 // If the array was previously zero-initialized, preserve the
7390 // zero-initialized values.
7391 if (!Filler.isUninit()) {
7392 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7393 Result.getArrayInitializedElt(I) = Filler;
7394 if (Result.hasArrayFiller())
7395 Result.getArrayFiller() = Filler;
7396 }
7397
Richard Smithd62306a2011-11-10 06:34:14 +00007398 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007399 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00007400 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7401 const Expr *Init =
7402 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00007403 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00007404 Info, Subobject, Init) ||
7405 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00007406 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007407 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00007408 return false;
7409 Success = false;
7410 }
Richard Smithd62306a2011-11-10 06:34:14 +00007411 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007412
Richard Smith9543c5e2013-04-22 14:44:29 +00007413 if (!Result.hasArrayFiller())
7414 return Success;
7415
7416 // If we get here, we have a trivial filler, which we can just evaluate
7417 // once and splat over the rest of the array elements.
7418 assert(FillerExpr && "no array filler for incomplete init list");
7419 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7420 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00007421}
7422
Richard Smith410306b2016-12-12 02:53:20 +00007423bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7424 if (E->getCommonExpr() &&
7425 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7426 Info, E->getCommonExpr()->getSourceExpr()))
7427 return false;
7428
7429 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7430
7431 uint64_t Elements = CAT->getSize().getZExtValue();
7432 Result = APValue(APValue::UninitArray(), Elements, Elements);
7433
7434 LValue Subobject = This;
7435 Subobject.addArray(Info, E, CAT);
7436
7437 bool Success = true;
7438 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7439 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7440 Info, Subobject, E->getSubExpr()) ||
7441 !HandleLValueArrayAdjustment(Info, E, Subobject,
7442 CAT->getElementType(), 1)) {
7443 if (!Info.noteFailure())
7444 return false;
7445 Success = false;
7446 }
7447 }
7448
7449 return Success;
7450}
7451
Richard Smith027bf112011-11-17 22:56:20 +00007452bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00007453 return VisitCXXConstructExpr(E, This, &Result, E->getType());
7454}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007455
Richard Smith9543c5e2013-04-22 14:44:29 +00007456bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7457 const LValue &Subobject,
7458 APValue *Value,
7459 QualType Type) {
7460 bool HadZeroInit = !Value->isUninit();
7461
7462 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7463 unsigned N = CAT->getSize().getZExtValue();
7464
7465 // Preserve the array filler if we had prior zero-initialization.
7466 APValue Filler =
7467 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7468 : APValue();
7469
7470 *Value = APValue(APValue::UninitArray(), N, N);
7471
7472 if (HadZeroInit)
7473 for (unsigned I = 0; I != N; ++I)
7474 Value->getArrayInitializedElt(I) = Filler;
7475
7476 // Initialize the elements.
7477 LValue ArrayElt = Subobject;
7478 ArrayElt.addArray(Info, E, CAT);
7479 for (unsigned I = 0; I != N; ++I)
7480 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7481 CAT->getElementType()) ||
7482 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7483 CAT->getElementType(), 1))
7484 return false;
7485
7486 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007487 }
Richard Smith027bf112011-11-17 22:56:20 +00007488
Richard Smith9543c5e2013-04-22 14:44:29 +00007489 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00007490 return Error(E);
7491
Richard Smithb8348f52016-05-12 22:16:28 +00007492 return RecordExprEvaluator(Info, Subobject, *Value)
7493 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00007494}
7495
Richard Smithf3e9e432011-11-07 09:22:26 +00007496//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007497// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007498//
7499// As a GNU extension, we support casting pointers to sufficiently-wide integer
7500// types and back in constant folding. Integer values are thus represented
7501// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00007502//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007503
7504namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007505class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007506 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00007507 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007508public:
Richard Smith2e312c82012-03-03 22:46:17 +00007509 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007510 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007511
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007512 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007513 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007514 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007515 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007516 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007517 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007518 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007519 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007520 return true;
7521 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007522 bool Success(const llvm::APSInt &SI, const Expr *E) {
7523 return Success(SI, E, Result);
7524 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007525
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007526 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007527 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007528 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007529 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007530 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007531 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007532 Result.getInt().setIsUnsigned(
7533 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007534 return true;
7535 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007536 bool Success(const llvm::APInt &I, const Expr *E) {
7537 return Success(I, E, Result);
7538 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007539
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007540 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007541 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007542 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007543 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007544 return true;
7545 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007546 bool Success(uint64_t Value, const Expr *E) {
7547 return Success(Value, E, Result);
7548 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007549
Ken Dyckdbc01912011-03-11 02:13:43 +00007550 bool Success(CharUnits Size, const Expr *E) {
7551 return Success(Size.getQuantity(), E);
7552 }
7553
Richard Smith2e312c82012-03-03 22:46:17 +00007554 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007555 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007556 Result = V;
7557 return true;
7558 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007559 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007560 }
Mike Stump11289f42009-09-09 15:08:12 +00007561
Richard Smithfddd3842011-12-30 21:15:51 +00007562 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007563
Peter Collingbournee9200682011-05-13 03:29:01 +00007564 //===--------------------------------------------------------------------===//
7565 // Visitor Methods
7566 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007567
Fangrui Song407659a2018-11-30 23:41:18 +00007568 bool VisitConstantExpr(const ConstantExpr *E);
7569
Chris Lattner7174bf32008-07-12 00:38:25 +00007570 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007571 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007572 }
7573 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007574 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007575 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007576
7577 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7578 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007579 if (CheckReferencedDecl(E, E->getDecl()))
7580 return true;
7581
7582 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007583 }
7584 bool VisitMemberExpr(const MemberExpr *E) {
7585 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007586 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007587 return true;
7588 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007589
7590 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007591 }
7592
Peter Collingbournee9200682011-05-13 03:29:01 +00007593 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007594 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007595 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007596 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007597 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007598
Peter Collingbournee9200682011-05-13 03:29:01 +00007599 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007600 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007601
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007602 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007603 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007604 }
Mike Stump11289f42009-09-09 15:08:12 +00007605
Ted Kremeneke65b0862012-03-06 20:05:56 +00007606 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7607 return Success(E->getValue(), E);
7608 }
Richard Smith410306b2016-12-12 02:53:20 +00007609
7610 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7611 if (Info.ArrayInitIndex == uint64_t(-1)) {
7612 // We were asked to evaluate this subexpression independent of the
7613 // enclosing ArrayInitLoopExpr. We can't do that.
7614 Info.FFDiag(E);
7615 return false;
7616 }
7617 return Success(Info.ArrayInitIndex, E);
7618 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007619
Richard Smith4ce706a2011-10-11 21:43:33 +00007620 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007621 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007622 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007623 }
7624
Douglas Gregor29c42f22012-02-24 07:38:34 +00007625 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7626 return Success(E->getValue(), E);
7627 }
7628
John Wiegley6242b6a2011-04-28 00:16:57 +00007629 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7630 return Success(E->getValue(), E);
7631 }
7632
John Wiegleyf9f65842011-04-25 06:54:41 +00007633 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7634 return Success(E->getValue(), E);
7635 }
7636
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007637 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007638 bool VisitUnaryImag(const UnaryOperator *E);
7639
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007640 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007641 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007642
Eli Friedman4e7a2412009-02-27 04:45:43 +00007643 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007644};
Leonard Chandb01c3a2018-06-20 17:19:40 +00007645
7646class FixedPointExprEvaluator
7647 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
7648 APValue &Result;
7649
7650 public:
7651 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
7652 : ExprEvaluatorBaseTy(info), Result(result) {}
7653
Leonard Chandb01c3a2018-06-20 17:19:40 +00007654 bool Success(const llvm::APInt &I, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00007655 return Success(
7656 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00007657 }
7658
Leonard Chandb01c3a2018-06-20 17:19:40 +00007659 bool Success(uint64_t Value, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00007660 return Success(
7661 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00007662 }
7663
7664 bool Success(const APValue &V, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00007665 return Success(V.getFixedPoint(), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00007666 }
7667
Leonard Chand3f3e162019-01-18 21:04:25 +00007668 bool Success(const APFixedPoint &V, const Expr *E) {
7669 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7670 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7671 "Invalid evaluation result.");
7672 Result = APValue(V);
7673 return true;
7674 }
Leonard Chandb01c3a2018-06-20 17:19:40 +00007675
7676 //===--------------------------------------------------------------------===//
7677 // Visitor Methods
7678 //===--------------------------------------------------------------------===//
7679
7680 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
7681 return Success(E->getValue(), E);
7682 }
7683
Leonard Chand3f3e162019-01-18 21:04:25 +00007684 bool VisitCastExpr(const CastExpr *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00007685 bool VisitUnaryOperator(const UnaryOperator *E);
Leonard Chand3f3e162019-01-18 21:04:25 +00007686 bool VisitBinaryOperator(const BinaryOperator *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00007687};
Chris Lattner05706e882008-07-11 18:11:29 +00007688} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007689
Richard Smith11562c52011-10-28 17:51:58 +00007690/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7691/// produce either the integer value or a pointer.
7692///
7693/// GCC has a heinous extension which folds casts between pointer types and
7694/// pointer-sized integral types. We support this by allowing the evaluation of
7695/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7696/// Some simple arithmetic on such values is supported (they are treated much
7697/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007698static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007699 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007700 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007701 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007702}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007703
Richard Smithf57d8cb2011-12-09 22:58:01 +00007704static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007705 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007706 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007707 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007708 if (!Val.isInt()) {
7709 // FIXME: It would be better to produce the diagnostic for casting
7710 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007711 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007712 return false;
7713 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007714 Result = Val.getInt();
7715 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007716}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007717
Leonard Chand3f3e162019-01-18 21:04:25 +00007718static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
7719 EvalInfo &Info) {
7720 if (E->getType()->isFixedPointType()) {
7721 APValue Val;
7722 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
7723 return false;
7724 if (!Val.isFixedPoint())
7725 return false;
7726
7727 Result = Val.getFixedPoint();
7728 return true;
7729 }
7730 return false;
7731}
7732
7733static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
7734 EvalInfo &Info) {
7735 if (E->getType()->isIntegerType()) {
7736 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
7737 APSInt Val;
7738 if (!EvaluateInteger(E, Val, Info))
7739 return false;
7740 Result = APFixedPoint(Val, FXSema);
7741 return true;
7742 } else if (E->getType()->isFixedPointType()) {
7743 return EvaluateFixedPoint(E, Result, Info);
7744 }
7745 return false;
7746}
7747
Richard Smithf57d8cb2011-12-09 22:58:01 +00007748/// Check whether the given declaration can be directly converted to an integral
7749/// rvalue. If not, no diagnostic is produced; there are other things we can
7750/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007751bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007752 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007753 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007754 // Check for signedness/width mismatches between E type and ECD value.
7755 bool SameSign = (ECD->getInitVal().isSigned()
7756 == E->getType()->isSignedIntegerOrEnumerationType());
7757 bool SameWidth = (ECD->getInitVal().getBitWidth()
7758 == Info.Ctx.getIntWidth(E->getType()));
7759 if (SameSign && SameWidth)
7760 return Success(ECD->getInitVal(), E);
7761 else {
7762 // Get rid of mismatch (otherwise Success assertions will fail)
7763 // by computing a new value matching the type of E.
7764 llvm::APSInt Val = ECD->getInitVal();
7765 if (!SameSign)
7766 Val.setIsSigned(!ECD->getInitVal().isSigned());
7767 if (!SameWidth)
7768 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7769 return Success(Val, E);
7770 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007771 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007772 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007773}
7774
Richard Smith08b682b2018-05-23 21:18:00 +00007775/// Values returned by __builtin_classify_type, chosen to match the values
7776/// produced by GCC's builtin.
7777enum class GCCTypeClass {
7778 None = -1,
7779 Void = 0,
7780 Integer = 1,
7781 // GCC reserves 2 for character types, but instead classifies them as
7782 // integers.
7783 Enum = 3,
7784 Bool = 4,
7785 Pointer = 5,
7786 // GCC reserves 6 for references, but appears to never use it (because
7787 // expressions never have reference type, presumably).
7788 PointerToDataMember = 7,
7789 RealFloat = 8,
7790 Complex = 9,
7791 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7792 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7793 // GCC claims to reserve 11 for pointers to member functions, but *actually*
7794 // uses 12 for that purpose, same as for a class or struct. Maybe it
7795 // internally implements a pointer to member as a struct? Who knows.
7796 PointerToMemberFunction = 12, // Not a bug, see above.
7797 ClassOrStruct = 12,
7798 Union = 13,
7799 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7800 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7801 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7802 // literals.
7803};
7804
Chris Lattner86ee2862008-10-06 06:40:35 +00007805/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7806/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00007807static GCCTypeClass
7808EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7809 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00007810
Richard Smith08b682b2018-05-23 21:18:00 +00007811 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007812 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7813
7814 switch (CanTy->getTypeClass()) {
7815#define TYPE(ID, BASE)
7816#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7817#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7818#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7819#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00007820 case Type::Auto:
7821 case Type::DeducedTemplateSpecialization:
7822 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007823
7824 case Type::Builtin:
7825 switch (BT->getKind()) {
7826#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00007827#define SIGNED_TYPE(ID, SINGLETON_ID) \
7828 case BuiltinType::ID: return GCCTypeClass::Integer;
7829#define FLOATING_TYPE(ID, SINGLETON_ID) \
7830 case BuiltinType::ID: return GCCTypeClass::RealFloat;
7831#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7832 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007833#include "clang/AST/BuiltinTypes.def"
7834 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00007835 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007836
7837 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00007838 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007839
Richard Smith08b682b2018-05-23 21:18:00 +00007840 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007841 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00007842 case BuiltinType::WChar_U:
7843 case BuiltinType::Char8:
7844 case BuiltinType::Char16:
7845 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007846 case BuiltinType::UShort:
7847 case BuiltinType::UInt:
7848 case BuiltinType::ULong:
7849 case BuiltinType::ULongLong:
7850 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00007851 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007852
Leonard Chanf921d852018-06-04 16:07:52 +00007853 case BuiltinType::UShortAccum:
7854 case BuiltinType::UAccum:
7855 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00007856 case BuiltinType::UShortFract:
7857 case BuiltinType::UFract:
7858 case BuiltinType::ULongFract:
7859 case BuiltinType::SatUShortAccum:
7860 case BuiltinType::SatUAccum:
7861 case BuiltinType::SatULongAccum:
7862 case BuiltinType::SatUShortFract:
7863 case BuiltinType::SatUFract:
7864 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00007865 return GCCTypeClass::None;
7866
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007867 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007868
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007869 case BuiltinType::ObjCId:
7870 case BuiltinType::ObjCClass:
7871 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007872#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7873 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007874#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00007875#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7876 case BuiltinType::Id:
7877#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007878 case BuiltinType::OCLSampler:
7879 case BuiltinType::OCLEvent:
7880 case BuiltinType::OCLClkEvent:
7881 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007882 case BuiltinType::OCLReserveID:
Richard Smith08b682b2018-05-23 21:18:00 +00007883 return GCCTypeClass::None;
7884
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007885 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00007886 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007887 };
Richard Smith08b682b2018-05-23 21:18:00 +00007888 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007889
7890 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00007891 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007892
7893 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007894 case Type::ConstantArray:
7895 case Type::VariableArray:
7896 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00007897 case Type::FunctionNoProto:
7898 case Type::FunctionProto:
7899 return GCCTypeClass::Pointer;
7900
7901 case Type::MemberPointer:
7902 return CanTy->isMemberDataPointerType()
7903 ? GCCTypeClass::PointerToDataMember
7904 : GCCTypeClass::PointerToMemberFunction;
7905
7906 case Type::Complex:
7907 return GCCTypeClass::Complex;
7908
7909 case Type::Record:
7910 return CanTy->isUnionType() ? GCCTypeClass::Union
7911 : GCCTypeClass::ClassOrStruct;
7912
7913 case Type::Atomic:
7914 // GCC classifies _Atomic T the same as T.
7915 return EvaluateBuiltinClassifyType(
7916 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007917
7918 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007919 case Type::Vector:
7920 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007921 case Type::ObjCObject:
7922 case Type::ObjCInterface:
7923 case Type::ObjCObjectPointer:
7924 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00007925 // GCC classifies vectors as None. We follow its lead and classify all
7926 // other types that don't fit into the regular classification the same way.
7927 return GCCTypeClass::None;
7928
7929 case Type::LValueReference:
7930 case Type::RValueReference:
7931 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007932 }
7933
Richard Smith08b682b2018-05-23 21:18:00 +00007934 llvm_unreachable("unexpected type class");
7935}
7936
7937/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7938/// as GCC.
7939static GCCTypeClass
7940EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7941 // If no argument was supplied, default to None. This isn't
7942 // ideal, however it is what gcc does.
7943 if (E->getNumArgs() == 0)
7944 return GCCTypeClass::None;
7945
7946 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7947 // being an ICE, but still folds it to a constant using the type of the first
7948 // argument.
7949 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00007950}
7951
Richard Smith5fab0c92011-12-28 19:48:30 +00007952/// EvaluateBuiltinConstantPForLValue - Determine the result of
Richard Smith31cfb312019-04-27 02:58:17 +00007953/// __builtin_constant_p when applied to the given pointer.
Richard Smith5fab0c92011-12-28 19:48:30 +00007954///
Richard Smith31cfb312019-04-27 02:58:17 +00007955/// A pointer is only "constant" if it is null (or a pointer cast to integer)
7956/// or it points to the first character of a string literal.
7957static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
7958 APValue::LValueBase Base = LV.getLValueBase();
7959 if (Base.isNull()) {
7960 // A null base is acceptable.
7961 return true;
7962 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
7963 if (!isa<StringLiteral>(E))
7964 return false;
7965 return LV.getLValueOffset().isZero();
7966 } else {
7967 // Any other base is not constant enough for GCC.
7968 return false;
7969 }
Richard Smith5fab0c92011-12-28 19:48:30 +00007970}
7971
7972/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7973/// GCC as we can manage.
Richard Smith31cfb312019-04-27 02:58:17 +00007974static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
Richard Smith37be3362019-05-04 04:00:45 +00007975 // This evaluation is not permitted to have side-effects, so evaluate it in
7976 // a speculative evaluation context.
7977 SpeculativeEvaluationRAII SpeculativeEval(Info);
7978
Richard Smith31cfb312019-04-27 02:58:17 +00007979 // Constant-folding is always enabled for the operand of __builtin_constant_p
7980 // (even when the enclosing evaluation context otherwise requires a strict
7981 // language-specific constant expression).
7982 FoldConstant Fold(Info, true);
7983
Richard Smith5fab0c92011-12-28 19:48:30 +00007984 QualType ArgType = Arg->getType();
7985
7986 // __builtin_constant_p always has one operand. The rules which gcc follows
7987 // are not precisely documented, but are as follows:
7988 //
7989 // - If the operand is of integral, floating, complex or enumeration type,
7990 // and can be folded to a known value of that type, it returns 1.
Richard Smith31cfb312019-04-27 02:58:17 +00007991 // - If the operand can be folded to a pointer to the first character
7992 // of a string literal (or such a pointer cast to an integral type)
7993 // or to a null pointer or an integer cast to a pointer, it returns 1.
Richard Smith5fab0c92011-12-28 19:48:30 +00007994 //
7995 // Otherwise, it returns 0.
7996 //
7997 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
Richard Smith31cfb312019-04-27 02:58:17 +00007998 // its support for this did not work prior to GCC 9 and is not yet well
7999 // understood.
8000 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
8001 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
8002 ArgType->isNullPtrType()) {
8003 APValue V;
8004 if (!::EvaluateAsRValue(Info, Arg, V)) {
8005 Fold.keepDiagnostics();
Richard Smith5fab0c92011-12-28 19:48:30 +00008006 return false;
Richard Smith31cfb312019-04-27 02:58:17 +00008007 }
Richard Smith5fab0c92011-12-28 19:48:30 +00008008
Richard Smith31cfb312019-04-27 02:58:17 +00008009 // For a pointer (possibly cast to integer), there are special rules.
Richard Smith0c6124b2015-12-03 01:36:22 +00008010 if (V.getKind() == APValue::LValue)
8011 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith31cfb312019-04-27 02:58:17 +00008012
8013 // Otherwise, any constant value is good enough.
8014 return V.getKind() != APValue::Uninitialized;
Richard Smith5fab0c92011-12-28 19:48:30 +00008015 }
8016
8017 // Anything else isn't considered to be sufficiently constant.
8018 return false;
8019}
8020
John McCall95007602010-05-10 23:27:23 +00008021/// Retrieves the "underlying object type" of the given expression,
8022/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00008023static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00008024 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
8025 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00008026 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00008027 } else if (const Expr *E = B.get<const Expr*>()) {
8028 if (isa<CompoundLiteralExpr>(E))
8029 return E->getType();
John McCall95007602010-05-10 23:27:23 +00008030 }
8031
8032 return QualType();
8033}
8034
George Burgess IV3a03fab2015-09-04 21:28:13 +00008035/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00008036/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00008037/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00008038/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
8039///
8040/// Always returns an RValue with a pointer representation.
8041static const Expr *ignorePointerCastsAndParens(const Expr *E) {
8042 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8043
8044 auto *NoParens = E->IgnoreParens();
8045 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00008046 if (Cast == nullptr)
8047 return NoParens;
8048
8049 // We only conservatively allow a few kinds of casts, because this code is
8050 // inherently a simple solution that seeks to support the common case.
8051 auto CastKind = Cast->getCastKind();
8052 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
8053 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00008054 return NoParens;
8055
8056 auto *SubExpr = Cast->getSubExpr();
8057 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
8058 return NoParens;
8059 return ignorePointerCastsAndParens(SubExpr);
8060}
8061
George Burgess IVa51c4072015-10-16 01:49:01 +00008062/// Checks to see if the given LValue's Designator is at the end of the LValue's
8063/// record layout. e.g.
8064/// struct { struct { int a, b; } fst, snd; } obj;
8065/// obj.fst // no
8066/// obj.snd // yes
8067/// obj.fst.a // no
8068/// obj.fst.b // no
8069/// obj.snd.a // no
8070/// obj.snd.b // yes
8071///
8072/// Please note: this function is specialized for how __builtin_object_size
8073/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00008074///
Richard Smith6f4f0f12017-10-20 22:56:25 +00008075/// If this encounters an invalid RecordDecl or otherwise cannot determine the
8076/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00008077static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
8078 assert(!LVal.Designator.Invalid);
8079
George Burgess IV4168d752016-06-27 19:40:41 +00008080 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
8081 const RecordDecl *Parent = FD->getParent();
8082 Invalid = Parent->isInvalidDecl();
8083 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00008084 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00008085 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00008086 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
8087 };
8088
8089 auto &Base = LVal.getLValueBase();
8090 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
8091 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00008092 bool Invalid;
8093 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
8094 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00008095 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00008096 for (auto *FD : IFD->chain()) {
8097 bool Invalid;
8098 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
8099 return Invalid;
8100 }
George Burgess IVa51c4072015-10-16 01:49:01 +00008101 }
8102 }
8103
George Burgess IVe3763372016-12-22 02:50:20 +00008104 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00008105 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00008106 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00008107 // If we don't know the array bound, conservatively assume we're looking at
8108 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00008109 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00008110 if (BaseType->isIncompleteArrayType())
8111 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
8112 else
8113 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00008114 }
8115
8116 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
8117 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00008118 if (BaseType->isArrayType()) {
8119 // Because __builtin_object_size treats arrays as objects, we can ignore
8120 // the index iff this is the last array in the Designator.
8121 if (I + 1 == E)
8122 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00008123 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
Richard Smith5b5e27a2019-05-10 20:05:31 +00008124 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00008125 if (Index + 1 != CAT->getSize())
8126 return false;
8127 BaseType = CAT->getElementType();
8128 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00008129 const auto *CT = BaseType->castAs<ComplexType>();
Richard Smith5b5e27a2019-05-10 20:05:31 +00008130 uint64_t Index = Entry.getAsArrayIndex();
George Burgess IVa51c4072015-10-16 01:49:01 +00008131 if (Index != 1)
8132 return false;
8133 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00008134 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00008135 bool Invalid;
8136 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
8137 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00008138 BaseType = FD->getType();
8139 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00008140 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00008141 return false;
8142 }
8143 }
8144 return true;
8145}
8146
George Burgess IVe3763372016-12-22 02:50:20 +00008147/// Tests to see if the LValue has a user-specified designator (that isn't
8148/// necessarily valid). Note that this always returns 'true' if the LValue has
8149/// an unsized array as its first designator entry, because there's currently no
8150/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00008151static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00008152 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00008153 return false;
8154
George Burgess IVe3763372016-12-22 02:50:20 +00008155 if (!LVal.Designator.Entries.empty())
8156 return LVal.Designator.isMostDerivedAnUnsizedArray();
8157
George Burgess IVa51c4072015-10-16 01:49:01 +00008158 if (!LVal.InvalidBase)
8159 return true;
8160
George Burgess IVe3763372016-12-22 02:50:20 +00008161 // If `E` is a MemberExpr, then the first part of the designator is hiding in
8162 // the LValueBase.
8163 const auto *E = LVal.Base.dyn_cast<const Expr *>();
8164 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00008165}
8166
George Burgess IVe3763372016-12-22 02:50:20 +00008167/// Attempts to detect a user writing into a piece of memory that's impossible
8168/// to figure out the size of by just using types.
8169static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
8170 const SubobjectDesignator &Designator = LVal.Designator;
8171 // Notes:
8172 // - Users can only write off of the end when we have an invalid base. Invalid
8173 // bases imply we don't know where the memory came from.
8174 // - We used to be a bit more aggressive here; we'd only be conservative if
8175 // the array at the end was flexible, or if it had 0 or 1 elements. This
8176 // broke some common standard library extensions (PR30346), but was
8177 // otherwise seemingly fine. It may be useful to reintroduce this behavior
8178 // with some sort of whitelist. OTOH, it seems that GCC is always
8179 // conservative with the last element in structs (if it's an array), so our
8180 // current behavior is more compatible than a whitelisting approach would
8181 // be.
8182 return LVal.InvalidBase &&
8183 Designator.Entries.size() == Designator.MostDerivedPathLength &&
8184 Designator.MostDerivedIsArrayElement &&
8185 isDesignatorAtObjectEnd(Ctx, LVal);
8186}
8187
8188/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
8189/// Fails if the conversion would cause loss of precision.
8190static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
8191 CharUnits &Result) {
8192 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
8193 if (Int.ugt(CharUnitsMax))
8194 return false;
8195 Result = CharUnits::fromQuantity(Int.getZExtValue());
8196 return true;
8197}
8198
8199/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
8200/// determine how many bytes exist from the beginning of the object to either
8201/// the end of the current subobject, or the end of the object itself, depending
8202/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00008203///
George Burgess IVe3763372016-12-22 02:50:20 +00008204/// If this returns false, the value of Result is undefined.
8205static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
8206 unsigned Type, const LValue &LVal,
8207 CharUnits &EndOffset) {
8208 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008209
George Burgess IV7fb7e362017-01-03 23:35:19 +00008210 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
8211 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
8212 return false;
8213 return HandleSizeof(Info, ExprLoc, Ty, Result);
8214 };
8215
George Burgess IVe3763372016-12-22 02:50:20 +00008216 // We want to evaluate the size of the entire object. This is a valid fallback
8217 // for when Type=1 and the designator is invalid, because we're asked for an
8218 // upper-bound.
8219 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
8220 // Type=3 wants a lower bound, so we can't fall back to this.
8221 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00008222 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00008223
8224 llvm::APInt APEndOffset;
8225 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8226 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8227 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8228
8229 if (LVal.InvalidBase)
8230 return false;
8231
8232 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00008233 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00008234 }
8235
George Burgess IVe3763372016-12-22 02:50:20 +00008236 // We want to evaluate the size of a subobject.
8237 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008238
8239 // The following is a moderately common idiom in C:
8240 //
8241 // struct Foo { int a; char c[1]; };
8242 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8243 // strcpy(&F->c[0], Bar);
8244 //
George Burgess IVe3763372016-12-22 02:50:20 +00008245 // In order to not break too much legacy code, we need to support it.
8246 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8247 // If we can resolve this to an alloc_size call, we can hand that back,
8248 // because we know for certain how many bytes there are to write to.
8249 llvm::APInt APEndOffset;
8250 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8251 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8252 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8253
8254 // If we cannot determine the size of the initial allocation, then we can't
8255 // given an accurate upper-bound. However, we are still able to give
8256 // conservative lower-bounds for Type=3.
8257 if (Type == 1)
8258 return false;
8259 }
8260
8261 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00008262 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008263 return false;
8264
George Burgess IVe3763372016-12-22 02:50:20 +00008265 // According to the GCC documentation, we want the size of the subobject
8266 // denoted by the pointer. But that's not quite right -- what we actually
8267 // want is the size of the immediately-enclosing array, if there is one.
8268 int64_t ElemsRemaining;
8269 if (Designator.MostDerivedIsArrayElement &&
8270 Designator.Entries.size() == Designator.MostDerivedPathLength) {
8271 uint64_t ArraySize = Designator.getMostDerivedArraySize();
Richard Smith5b5e27a2019-05-10 20:05:31 +00008272 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00008273 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8274 } else {
8275 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8276 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008277
George Burgess IVe3763372016-12-22 02:50:20 +00008278 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8279 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008280}
8281
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008282/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00008283/// returns true and stores the result in @p Size.
8284///
8285/// If @p WasError is non-null, this will report whether the failure to evaluate
8286/// is to be treated as an Error in IntExprEvaluator.
8287static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8288 EvalInfo &Info, uint64_t &Size) {
8289 // Determine the denoted object.
8290 LValue LVal;
8291 {
8292 // The operand of __builtin_object_size is never evaluated for side-effects.
8293 // If there are any, but we can determine the pointed-to object anyway, then
8294 // ignore the side-effects.
8295 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00008296 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00008297
8298 if (E->isGLValue()) {
8299 // It's possible for us to be given GLValues if we're called via
8300 // Expr::tryEvaluateObjectSize.
8301 APValue RVal;
8302 if (!EvaluateAsRValue(Info, E, RVal))
8303 return false;
8304 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00008305 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8306 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00008307 return false;
8308 }
8309
8310 // If we point to before the start of the object, there are no accessible
8311 // bytes.
8312 if (LVal.getLValueOffset().isNegative()) {
8313 Size = 0;
8314 return true;
8315 }
8316
8317 CharUnits EndOffset;
8318 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8319 return false;
8320
8321 // If we've fallen outside of the end offset, just pretend there's nothing to
8322 // write to/read from.
8323 if (EndOffset <= LVal.getLValueOffset())
8324 Size = 0;
8325 else
8326 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8327 return true;
John McCall95007602010-05-10 23:27:23 +00008328}
8329
Fangrui Song407659a2018-11-30 23:41:18 +00008330bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
8331 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
8332 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
8333}
8334
Peter Collingbournee9200682011-05-13 03:29:01 +00008335bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00008336 if (unsigned BuiltinOp = E->getBuiltinCallee())
8337 return VisitBuiltinCallExpr(E, BuiltinOp);
8338
8339 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8340}
8341
8342bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8343 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00008344 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008345 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00008346 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00008347
Erik Pilkington9c3b5882019-01-30 20:34:53 +00008348 case Builtin::BI__builtin_dynamic_object_size:
Mike Stump722cedf2009-10-26 18:35:08 +00008349 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00008350 // The type was checked when we built the expression.
8351 unsigned Type =
8352 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8353 assert(Type <= 3 && "unexpected type");
8354
George Burgess IVe3763372016-12-22 02:50:20 +00008355 uint64_t Size;
8356 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8357 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00008358
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008359 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00008360 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00008361
Richard Smith01ade172012-05-23 04:13:20 +00008362 // Expression had no side effects, but we couldn't statically determine the
8363 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008364 switch (Info.EvalMode) {
8365 case EvalInfo::EM_ConstantExpression:
8366 case EvalInfo::EM_PotentialConstantExpression:
8367 case EvalInfo::EM_ConstantFold:
8368 case EvalInfo::EM_EvaluateForOverflow:
8369 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008370 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008371 return Error(E);
8372 case EvalInfo::EM_ConstantExpressionUnevaluated:
8373 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008374 // Reduce it to a constant now.
8375 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008376 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00008377
8378 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00008379 }
8380
Tim Northover314fbfa2018-11-02 13:14:11 +00008381 case Builtin::BI__builtin_os_log_format_buffer_size: {
8382 analyze_os_log::OSLogBufferLayout Layout;
8383 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
8384 return Success(Layout.size().getQuantity(), E);
8385 }
8386
Benjamin Kramera801f4a2012-10-06 14:42:22 +00008387 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00008388 case Builtin::BI__builtin_bswap32:
8389 case Builtin::BI__builtin_bswap64: {
8390 APSInt Val;
8391 if (!EvaluateInteger(E->getArg(0), Val, Info))
8392 return false;
8393
8394 return Success(Val.byteSwap(), E);
8395 }
8396
Richard Smith8889a3d2013-06-13 06:26:32 +00008397 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00008398 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00008399
Craig Topperf95a6d92018-08-08 22:31:12 +00008400 case Builtin::BI__builtin_clrsb:
8401 case Builtin::BI__builtin_clrsbl:
8402 case Builtin::BI__builtin_clrsbll: {
8403 APSInt Val;
8404 if (!EvaluateInteger(E->getArg(0), Val, Info))
8405 return false;
8406
8407 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8408 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008409
Richard Smith80b3c8e2013-06-13 05:04:16 +00008410 case Builtin::BI__builtin_clz:
8411 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008412 case Builtin::BI__builtin_clzll:
8413 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008414 APSInt Val;
8415 if (!EvaluateInteger(E->getArg(0), Val, Info))
8416 return false;
8417 if (!Val)
8418 return Error(E);
8419
8420 return Success(Val.countLeadingZeros(), E);
8421 }
8422
Fangrui Song407659a2018-11-30 23:41:18 +00008423 case Builtin::BI__builtin_constant_p: {
Richard Smith31cfb312019-04-27 02:58:17 +00008424 const Expr *Arg = E->getArg(0);
David Blaikie639b3d12019-05-03 18:11:31 +00008425 if (EvaluateBuiltinConstantP(Info, Arg))
Fangrui Song407659a2018-11-30 23:41:18 +00008426 return Success(true, E);
David Blaikie639b3d12019-05-03 18:11:31 +00008427 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
Richard Smithf7d30482019-05-02 23:21:28 +00008428 // Outside a constant context, eagerly evaluate to false in the presence
8429 // of side-effects in order to avoid -Wunsequenced false-positives in
8430 // a branch on __builtin_constant_p(expr).
Richard Smith31cfb312019-04-27 02:58:17 +00008431 return Success(false, E);
Fangrui Song407659a2018-11-30 23:41:18 +00008432 }
David Blaikie639b3d12019-05-03 18:11:31 +00008433 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8434 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00008435 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008436
Eric Fiselieradd16a82019-04-24 02:23:30 +00008437 case Builtin::BI__builtin_is_constant_evaluated:
8438 return Success(Info.InConstantContext, E);
8439
Richard Smith80b3c8e2013-06-13 05:04:16 +00008440 case Builtin::BI__builtin_ctz:
8441 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008442 case Builtin::BI__builtin_ctzll:
8443 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008444 APSInt Val;
8445 if (!EvaluateInteger(E->getArg(0), Val, Info))
8446 return false;
8447 if (!Val)
8448 return Error(E);
8449
8450 return Success(Val.countTrailingZeros(), E);
8451 }
8452
Richard Smith8889a3d2013-06-13 06:26:32 +00008453 case Builtin::BI__builtin_eh_return_data_regno: {
8454 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8455 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8456 return Success(Operand, E);
8457 }
8458
8459 case Builtin::BI__builtin_expect:
8460 return Visit(E->getArg(0));
8461
8462 case Builtin::BI__builtin_ffs:
8463 case Builtin::BI__builtin_ffsl:
8464 case Builtin::BI__builtin_ffsll: {
8465 APSInt Val;
8466 if (!EvaluateInteger(E->getArg(0), Val, Info))
8467 return false;
8468
8469 unsigned N = Val.countTrailingZeros();
8470 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8471 }
8472
8473 case Builtin::BI__builtin_fpclassify: {
8474 APFloat Val(0.0);
8475 if (!EvaluateFloat(E->getArg(5), Val, Info))
8476 return false;
8477 unsigned Arg;
8478 switch (Val.getCategory()) {
8479 case APFloat::fcNaN: Arg = 0; break;
8480 case APFloat::fcInfinity: Arg = 1; break;
8481 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8482 case APFloat::fcZero: Arg = 4; break;
8483 }
8484 return Visit(E->getArg(Arg));
8485 }
8486
8487 case Builtin::BI__builtin_isinf_sign: {
8488 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00008489 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00008490 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8491 }
8492
Richard Smithea3019d2013-10-15 19:07:14 +00008493 case Builtin::BI__builtin_isinf: {
8494 APFloat Val(0.0);
8495 return EvaluateFloat(E->getArg(0), Val, Info) &&
8496 Success(Val.isInfinity() ? 1 : 0, E);
8497 }
8498
8499 case Builtin::BI__builtin_isfinite: {
8500 APFloat Val(0.0);
8501 return EvaluateFloat(E->getArg(0), Val, Info) &&
8502 Success(Val.isFinite() ? 1 : 0, E);
8503 }
8504
8505 case Builtin::BI__builtin_isnan: {
8506 APFloat Val(0.0);
8507 return EvaluateFloat(E->getArg(0), Val, Info) &&
8508 Success(Val.isNaN() ? 1 : 0, E);
8509 }
8510
8511 case Builtin::BI__builtin_isnormal: {
8512 APFloat Val(0.0);
8513 return EvaluateFloat(E->getArg(0), Val, Info) &&
8514 Success(Val.isNormal() ? 1 : 0, E);
8515 }
8516
Richard Smith8889a3d2013-06-13 06:26:32 +00008517 case Builtin::BI__builtin_parity:
8518 case Builtin::BI__builtin_parityl:
8519 case Builtin::BI__builtin_parityll: {
8520 APSInt Val;
8521 if (!EvaluateInteger(E->getArg(0), Val, Info))
8522 return false;
8523
8524 return Success(Val.countPopulation() % 2, E);
8525 }
8526
Richard Smith80b3c8e2013-06-13 05:04:16 +00008527 case Builtin::BI__builtin_popcount:
8528 case Builtin::BI__builtin_popcountl:
8529 case Builtin::BI__builtin_popcountll: {
8530 APSInt Val;
8531 if (!EvaluateInteger(E->getArg(0), Val, Info))
8532 return false;
8533
8534 return Success(Val.countPopulation(), E);
8535 }
8536
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008537 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00008538 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00008539 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008540 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008541 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00008542 << /*isConstexpr*/0 << /*isConstructor*/0
8543 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00008544 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00008545 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008546 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008547 case Builtin::BI__builtin_strlen:
8548 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00008549 // As an extension, we support __builtin_strlen() as a constant expression,
8550 // and support folding strlen() to a constant.
8551 LValue String;
8552 if (!EvaluatePointer(E->getArg(0), String, Info))
8553 return false;
8554
Richard Smith8110c9d2016-11-29 19:45:17 +00008555 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8556
Richard Smithe6c19f22013-11-15 02:10:04 +00008557 // Fast path: if it's a string literal, search the string value.
8558 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8559 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008560 // The string literal may have embedded null characters. Find the first
8561 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00008562 StringRef Str = S->getBytes();
8563 int64_t Off = String.Offset.getQuantity();
8564 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008565 S->getCharByteWidth() == 1 &&
8566 // FIXME: Add fast-path for wchar_t too.
8567 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00008568 Str = Str.substr(Off);
8569
8570 StringRef::size_type Pos = Str.find(0);
8571 if (Pos != StringRef::npos)
8572 Str = Str.substr(0, Pos);
8573
8574 return Success(Str.size(), E);
8575 }
8576
8577 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008578 }
Richard Smithe6c19f22013-11-15 02:10:04 +00008579
8580 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00008581 for (uint64_t Strlen = 0; /**/; ++Strlen) {
8582 APValue Char;
8583 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8584 !Char.isInt())
8585 return false;
8586 if (!Char.getInt())
8587 return Success(Strlen, E);
8588 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8589 return false;
8590 }
8591 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008592
Richard Smithe151bab2016-11-11 23:43:35 +00008593 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008594 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008595 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008596 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008597 case Builtin::BImemcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00008598 case Builtin::BIbcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008599 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008600 // A call to strlen is not a constant expression.
8601 if (Info.getLangOpts().CPlusPlus11)
8602 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8603 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00008604 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00008605 else
8606 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008607 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00008608 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008609 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008610 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008611 case Builtin::BI__builtin_wcsncmp:
8612 case Builtin::BI__builtin_memcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00008613 case Builtin::BI__builtin_bcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008614 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00008615 LValue String1, String2;
8616 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8617 !EvaluatePointer(E->getArg(1), String2, Info))
8618 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00008619
Richard Smithe151bab2016-11-11 23:43:35 +00008620 uint64_t MaxLength = uint64_t(-1);
8621 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008622 BuiltinOp != Builtin::BIwcscmp &&
8623 BuiltinOp != Builtin::BI__builtin_strcmp &&
8624 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00008625 APSInt N;
8626 if (!EvaluateInteger(E->getArg(2), N, Info))
8627 return false;
8628 MaxLength = N.getExtValue();
8629 }
Hubert Tong147b7432018-12-12 16:53:43 +00008630
8631 // Empty substrings compare equal by definition.
8632 if (MaxLength == 0u)
8633 return Success(0, E);
8634
8635 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8636 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8637 String1.Designator.Invalid || String2.Designator.Invalid)
8638 return false;
8639
8640 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
8641 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
8642
8643 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
Clement Courbet8c3343d2019-02-14 12:00:34 +00008644 BuiltinOp == Builtin::BIbcmp ||
8645 BuiltinOp == Builtin::BI__builtin_memcmp ||
8646 BuiltinOp == Builtin::BI__builtin_bcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00008647
8648 assert(IsRawByte ||
8649 (Info.Ctx.hasSameUnqualifiedType(
8650 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
8651 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
8652
8653 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
8654 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
8655 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
8656 Char1.isInt() && Char2.isInt();
8657 };
8658 const auto &AdvanceElems = [&] {
8659 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
8660 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
8661 };
8662
8663 if (IsRawByte) {
8664 uint64_t BytesRemaining = MaxLength;
8665 // Pointers to const void may point to objects of incomplete type.
8666 if (CharTy1->isIncompleteType()) {
8667 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
8668 return false;
8669 }
8670 if (CharTy2->isIncompleteType()) {
8671 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
8672 return false;
8673 }
8674 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
8675 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
8676 // Give up on comparing between elements with disparate widths.
8677 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
8678 return false;
8679 uint64_t BytesPerElement = CharTy1Size.getQuantity();
8680 assert(BytesRemaining && "BytesRemaining should not be zero: the "
8681 "following loop considers at least one element");
8682 while (true) {
8683 APValue Char1, Char2;
8684 if (!ReadCurElems(Char1, Char2))
8685 return false;
8686 // We have compatible in-memory widths, but a possible type and
8687 // (for `bool`) internal representation mismatch.
8688 // Assuming two's complement representation, including 0 for `false` and
8689 // 1 for `true`, we can check an appropriate number of elements for
8690 // equality even if they are not byte-sized.
8691 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
8692 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
8693 if (Char1InMem.ne(Char2InMem)) {
8694 // If the elements are byte-sized, then we can produce a three-way
8695 // comparison result in a straightforward manner.
8696 if (BytesPerElement == 1u) {
8697 // memcmp always compares unsigned chars.
8698 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
8699 }
8700 // The result is byte-order sensitive, and we have multibyte elements.
8701 // FIXME: We can compare the remaining bytes in the correct order.
8702 return false;
8703 }
8704 if (!AdvanceElems())
8705 return false;
8706 if (BytesRemaining <= BytesPerElement)
8707 break;
8708 BytesRemaining -= BytesPerElement;
8709 }
8710 // Enough elements are equal to account for the memcmp limit.
8711 return Success(0, E);
8712 }
8713
Clement Courbet8c3343d2019-02-14 12:00:34 +00008714 bool StopAtNull =
8715 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
8716 BuiltinOp != Builtin::BIwmemcmp &&
8717 BuiltinOp != Builtin::BI__builtin_memcmp &&
8718 BuiltinOp != Builtin::BI__builtin_bcmp &&
8719 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00008720 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8721 BuiltinOp == Builtin::BIwcsncmp ||
8722 BuiltinOp == Builtin::BIwmemcmp ||
8723 BuiltinOp == Builtin::BI__builtin_wcscmp ||
8724 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8725 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00008726
Richard Smithe151bab2016-11-11 23:43:35 +00008727 for (; MaxLength; --MaxLength) {
8728 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +00008729 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +00008730 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00008731 if (Char1.getInt() != Char2.getInt()) {
8732 if (IsWide) // wmemcmp compares with wchar_t signedness.
8733 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8734 // memcmp always compares unsigned chars.
8735 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8736 }
Richard Smithe151bab2016-11-11 23:43:35 +00008737 if (StopAtNull && !Char1.getInt())
8738 return Success(0, E);
8739 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +00008740 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +00008741 return false;
8742 }
8743 // We hit the strncmp / memcmp limit.
8744 return Success(0, E);
8745 }
8746
Richard Smith01ba47d2012-04-13 00:45:38 +00008747 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00008748 case Builtin::BI__atomic_is_lock_free:
8749 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00008750 APSInt SizeVal;
8751 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8752 return false;
8753
8754 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8755 // of two less than the maximum inline atomic width, we know it is
8756 // lock-free. If the size isn't a power of two, or greater than the
8757 // maximum alignment where we promote atomics, we know it is not lock-free
8758 // (at least not in the sense of atomic_is_lock_free). Otherwise,
8759 // the answer can only be determined at runtime; for example, 16-byte
8760 // atomics have lock-free implementations on some, but not all,
8761 // x86-64 processors.
8762
8763 // Check power-of-two.
8764 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00008765 if (Size.isPowerOfTwo()) {
8766 // Check against inlining width.
8767 unsigned InlineWidthBits =
8768 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8769 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8770 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8771 Size == CharUnits::One() ||
8772 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8773 Expr::NPC_NeverValueDependent))
8774 // OK, we will inline appropriately-aligned operations of this size,
8775 // and _Atomic(T) is appropriately-aligned.
8776 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008777
Richard Smith01ba47d2012-04-13 00:45:38 +00008778 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8779 castAs<PointerType>()->getPointeeType();
8780 if (!PointeeType->isIncompleteType() &&
8781 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8782 // OK, we will inline operations on this object.
8783 return Success(1, E);
8784 }
8785 }
8786 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008787
Richard Smith01ba47d2012-04-13 00:45:38 +00008788 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8789 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008790 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008791 case Builtin::BIomp_is_initial_device:
8792 // We can decide statically which value the runtime would return if called.
8793 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00008794 case Builtin::BI__builtin_add_overflow:
8795 case Builtin::BI__builtin_sub_overflow:
8796 case Builtin::BI__builtin_mul_overflow:
8797 case Builtin::BI__builtin_sadd_overflow:
8798 case Builtin::BI__builtin_uadd_overflow:
8799 case Builtin::BI__builtin_uaddl_overflow:
8800 case Builtin::BI__builtin_uaddll_overflow:
8801 case Builtin::BI__builtin_usub_overflow:
8802 case Builtin::BI__builtin_usubl_overflow:
8803 case Builtin::BI__builtin_usubll_overflow:
8804 case Builtin::BI__builtin_umul_overflow:
8805 case Builtin::BI__builtin_umull_overflow:
8806 case Builtin::BI__builtin_umulll_overflow:
8807 case Builtin::BI__builtin_saddl_overflow:
8808 case Builtin::BI__builtin_saddll_overflow:
8809 case Builtin::BI__builtin_ssub_overflow:
8810 case Builtin::BI__builtin_ssubl_overflow:
8811 case Builtin::BI__builtin_ssubll_overflow:
8812 case Builtin::BI__builtin_smul_overflow:
8813 case Builtin::BI__builtin_smull_overflow:
8814 case Builtin::BI__builtin_smulll_overflow: {
8815 LValue ResultLValue;
8816 APSInt LHS, RHS;
8817
8818 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
8819 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
8820 !EvaluateInteger(E->getArg(1), RHS, Info) ||
8821 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
8822 return false;
8823
8824 APSInt Result;
8825 bool DidOverflow = false;
8826
8827 // If the types don't have to match, enlarge all 3 to the largest of them.
8828 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8829 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8830 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8831 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
8832 ResultType->isSignedIntegerOrEnumerationType();
8833 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
8834 ResultType->isSignedIntegerOrEnumerationType();
8835 uint64_t LHSSize = LHS.getBitWidth();
8836 uint64_t RHSSize = RHS.getBitWidth();
8837 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
8838 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
8839
8840 // Add an additional bit if the signedness isn't uniformly agreed to. We
8841 // could do this ONLY if there is a signed and an unsigned that both have
8842 // MaxBits, but the code to check that is pretty nasty. The issue will be
8843 // caught in the shrink-to-result later anyway.
8844 if (IsSigned && !AllSigned)
8845 ++MaxBits;
8846
8847 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
8848 !IsSigned);
8849 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
8850 !IsSigned);
8851 Result = APSInt(MaxBits, !IsSigned);
8852 }
8853
8854 // Find largest int.
8855 switch (BuiltinOp) {
8856 default:
8857 llvm_unreachable("Invalid value for BuiltinOp");
8858 case Builtin::BI__builtin_add_overflow:
8859 case Builtin::BI__builtin_sadd_overflow:
8860 case Builtin::BI__builtin_saddl_overflow:
8861 case Builtin::BI__builtin_saddll_overflow:
8862 case Builtin::BI__builtin_uadd_overflow:
8863 case Builtin::BI__builtin_uaddl_overflow:
8864 case Builtin::BI__builtin_uaddll_overflow:
8865 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
8866 : LHS.uadd_ov(RHS, DidOverflow);
8867 break;
8868 case Builtin::BI__builtin_sub_overflow:
8869 case Builtin::BI__builtin_ssub_overflow:
8870 case Builtin::BI__builtin_ssubl_overflow:
8871 case Builtin::BI__builtin_ssubll_overflow:
8872 case Builtin::BI__builtin_usub_overflow:
8873 case Builtin::BI__builtin_usubl_overflow:
8874 case Builtin::BI__builtin_usubll_overflow:
8875 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
8876 : LHS.usub_ov(RHS, DidOverflow);
8877 break;
8878 case Builtin::BI__builtin_mul_overflow:
8879 case Builtin::BI__builtin_smul_overflow:
8880 case Builtin::BI__builtin_smull_overflow:
8881 case Builtin::BI__builtin_smulll_overflow:
8882 case Builtin::BI__builtin_umul_overflow:
8883 case Builtin::BI__builtin_umull_overflow:
8884 case Builtin::BI__builtin_umulll_overflow:
8885 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
8886 : LHS.umul_ov(RHS, DidOverflow);
8887 break;
8888 }
8889
8890 // In the case where multiple sizes are allowed, truncate and see if
8891 // the values are the same.
8892 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8893 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8894 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8895 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
8896 // since it will give us the behavior of a TruncOrSelf in the case where
8897 // its parameter <= its size. We previously set Result to be at least the
8898 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
8899 // will work exactly like TruncOrSelf.
8900 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
8901 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
8902
8903 if (!APSInt::isSameValue(Temp, Result))
8904 DidOverflow = true;
8905 Result = Temp;
8906 }
8907
8908 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +00008909 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
8910 return false;
Erich Keane00958272018-06-13 20:43:27 +00008911 return Success(DidOverflow, E);
8912 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008913 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008914}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008915
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008916/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +00008917/// object referred to by the lvalue.
8918static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8919 const LValue &LV) {
8920 // A null pointer can be viewed as being "past the end" but we don't
8921 // choose to look at it that way here.
8922 if (!LV.getLValueBase())
8923 return false;
8924
8925 // If the designator is valid and refers to a subobject, we're not pointing
8926 // past the end.
8927 if (!LV.getLValueDesignator().Invalid &&
8928 !LV.getLValueDesignator().isOnePastTheEnd())
8929 return false;
8930
David Majnemerc378ca52015-08-29 08:32:55 +00008931 // A pointer to an incomplete type might be past-the-end if the type's size is
8932 // zero. We cannot tell because the type is incomplete.
8933 QualType Ty = getType(LV.getLValueBase());
8934 if (Ty->isIncompleteType())
8935 return true;
8936
Richard Smithd20f1e62014-10-21 23:01:04 +00008937 // We're a past-the-end pointer if we point to the byte after the object,
8938 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008939 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008940 return LV.getLValueOffset() == Size;
8941}
8942
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008943namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008944
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008945/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008946///
8947/// We use a data recursive algorithm for binary operators so that we are able
8948/// to handle extreme cases of chained binary operators without causing stack
8949/// overflow.
8950class DataRecursiveIntBinOpEvaluator {
8951 struct EvalResult {
8952 APValue Val;
8953 bool Failed;
8954
8955 EvalResult() : Failed(false) { }
8956
8957 void swap(EvalResult &RHS) {
8958 Val.swap(RHS.Val);
8959 Failed = RHS.Failed;
8960 RHS.Failed = false;
8961 }
8962 };
8963
8964 struct Job {
8965 const Expr *E;
8966 EvalResult LHSResult; // meaningful only for binary operator expression.
8967 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008968
David Blaikie73726062015-08-12 23:09:24 +00008969 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008970 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008971
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008972 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008973 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008974 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008975
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008976 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008977 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008978 };
8979
8980 SmallVector<Job, 16> Queue;
8981
8982 IntExprEvaluator &IntEval;
8983 EvalInfo &Info;
8984 APValue &FinalResult;
8985
8986public:
8987 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8988 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8989
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008990 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008991 /// data recursively.
8992 /// We handle binary operators that are comma, logical, or that have operands
8993 /// with integral or enumeration type.
8994 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008995 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8996 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +00008997 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008998 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008999 }
9000
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009001 bool Traverse(const BinaryOperator *E) {
9002 enqueue(E);
9003 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00009004 while (!Queue.empty())
9005 process(PrevResult);
9006
9007 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009008
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009009 FinalResult.swap(PrevResult.Val);
9010 return true;
9011 }
9012
9013private:
9014 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
9015 return IntEval.Success(Value, E, Result);
9016 }
9017 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
9018 return IntEval.Success(Value, E, Result);
9019 }
9020 bool Error(const Expr *E) {
9021 return IntEval.Error(E);
9022 }
9023 bool Error(const Expr *E, diag::kind D) {
9024 return IntEval.Error(E, D);
9025 }
9026
9027 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
9028 return Info.CCEDiag(E, D);
9029 }
9030
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009031 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009032 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009033 bool &SuppressRHSDiags);
9034
9035 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
9036 const BinaryOperator *E, APValue &Result);
9037
9038 void EvaluateExpr(const Expr *E, EvalResult &Result) {
9039 Result.Failed = !Evaluate(Result.Val, Info, E);
9040 if (Result.Failed)
9041 Result.Val = APValue();
9042 }
9043
Richard Trieuba4d0872012-03-21 23:30:30 +00009044 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009045
9046 void enqueue(const Expr *E) {
9047 E = E->IgnoreParens();
9048 Queue.resize(Queue.size()+1);
9049 Queue.back().E = E;
9050 Queue.back().Kind = Job::AnyExprKind;
9051 }
9052};
9053
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009054}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009055
9056bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009057 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009058 bool &SuppressRHSDiags) {
9059 if (E->getOpcode() == BO_Comma) {
9060 // Ignore LHS but note if we could not evaluate it.
9061 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00009062 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009063 return true;
9064 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00009065
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009066 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00009067 bool LHSAsBool;
9068 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009069 // We were able to evaluate the LHS, see if we can get away with not
9070 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00009071 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
9072 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009073 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009074 }
9075 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00009076 LHSResult.Failed = true;
9077
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009078 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00009079 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00009080 if (!Info.noteSideEffect())
9081 return false;
9082
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009083 // We can't evaluate the LHS; however, sometimes the result
9084 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9085 // Don't ignore RHS and suppress diagnostics from this arm.
9086 SuppressRHSDiags = true;
9087 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00009088
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009089 return true;
9090 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00009091
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009092 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9093 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00009094
George Burgess IVa145e252016-05-25 22:38:36 +00009095 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009096 return false; // Ignore RHS;
9097
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009098 return true;
9099}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009100
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00009101static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
9102 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00009103 // Compute the new offset in the appropriate width, wrapping at 64 bits.
9104 // FIXME: When compiling for a 32-bit target, we should use 32-bit
9105 // offsets.
9106 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
9107 CharUnits &Offset = LVal.getLValueOffset();
9108 uint64_t Offset64 = Offset.getQuantity();
9109 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
9110 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
9111 : Offset64 + Index64);
9112}
9113
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009114bool DataRecursiveIntBinOpEvaluator::
9115 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
9116 const BinaryOperator *E, APValue &Result) {
9117 if (E->getOpcode() == BO_Comma) {
9118 if (RHSResult.Failed)
9119 return false;
9120 Result = RHSResult.Val;
9121 return true;
9122 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009123
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009124 if (E->isLogicalOp()) {
9125 bool lhsResult, rhsResult;
9126 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
9127 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +00009128
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009129 if (LHSIsOK) {
9130 if (RHSIsOK) {
9131 if (E->getOpcode() == BO_LOr)
9132 return Success(lhsResult || rhsResult, E, Result);
9133 else
9134 return Success(lhsResult && rhsResult, E, Result);
9135 }
9136 } else {
9137 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009138 // We can't evaluate the LHS; however, sometimes the result
9139 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9140 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009141 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009142 }
9143 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009144
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009145 return false;
9146 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009147
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009148 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9149 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +00009150
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009151 if (LHSResult.Failed || RHSResult.Failed)
9152 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009153
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009154 const APValue &LHSVal = LHSResult.Val;
9155 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +00009156
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009157 // Handle cases like (unsigned long)&a + 4.
9158 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
9159 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00009160 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009161 return true;
9162 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009163
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009164 // Handle cases like 4 + (unsigned long)&a
9165 if (E->getOpcode() == BO_Add &&
9166 RHSVal.isLValue() && LHSVal.isInt()) {
9167 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00009168 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009169 return true;
9170 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009171
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009172 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
9173 // Handle (intptr_t)&&A - (intptr_t)&&B.
9174 if (!LHSVal.getLValueOffset().isZero() ||
9175 !RHSVal.getLValueOffset().isZero())
9176 return false;
9177 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
9178 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
9179 if (!LHSExpr || !RHSExpr)
9180 return false;
9181 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9182 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9183 if (!LHSAddrExpr || !RHSAddrExpr)
9184 return false;
9185 // Make sure both labels come from the same function.
9186 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9187 RHSAddrExpr->getLabel()->getDeclContext())
9188 return false;
9189 Result = APValue(LHSAddrExpr, RHSAddrExpr);
9190 return true;
9191 }
Richard Smith43e77732013-05-07 04:50:00 +00009192
9193 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009194 if (!LHSVal.isInt() || !RHSVal.isInt())
9195 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00009196
9197 // Set up the width and signedness manually, in case it can't be deduced
9198 // from the operation we're performing.
9199 // FIXME: Don't do this in the cases where we can deduce it.
9200 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
9201 E->getType()->isUnsignedIntegerOrEnumerationType());
9202 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
9203 RHSVal.getInt(), Value))
9204 return false;
9205 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009206}
9207
Richard Trieuba4d0872012-03-21 23:30:30 +00009208void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009209 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +00009210
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009211 switch (job.Kind) {
9212 case Job::AnyExprKind: {
9213 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
9214 if (shouldEnqueue(Bop)) {
9215 job.Kind = Job::BinOpKind;
9216 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009217 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009218 }
9219 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009220
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009221 EvaluateExpr(job.E, Result);
9222 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009223 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009224 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009225
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009226 case Job::BinOpKind: {
9227 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009228 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009229 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009230 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009231 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009232 }
9233 if (SuppressRHSDiags)
9234 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009235 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009236 job.Kind = Job::BinOpVisitedLHSKind;
9237 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009238 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009239 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009240
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009241 case Job::BinOpVisitedLHSKind: {
9242 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9243 EvalResult RHS;
9244 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00009245 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009246 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009247 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009248 }
9249 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009250
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009251 llvm_unreachable("Invalid Job::Kind!");
9252}
9253
George Burgess IV8c892b52016-05-25 22:31:54 +00009254namespace {
9255/// Used when we determine that we should fail, but can keep evaluating prior to
9256/// noting that we had a failure.
9257class DelayedNoteFailureRAII {
9258 EvalInfo &Info;
9259 bool NoteFailure;
9260
9261public:
9262 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
9263 : Info(Info), NoteFailure(NoteFailure) {}
9264 ~DelayedNoteFailureRAII() {
9265 if (NoteFailure) {
9266 bool ContinueAfterFailure = Info.noteFailure();
9267 (void)ContinueAfterFailure;
9268 assert(ContinueAfterFailure &&
9269 "Shouldn't have kept evaluating on failure.");
9270 }
9271 }
9272};
9273}
9274
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009275template <class SuccessCB, class AfterCB>
9276static bool
9277EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
9278 SuccessCB &&Success, AfterCB &&DoAfter) {
9279 assert(E->isComparisonOp() && "expected comparison operator");
9280 assert((E->getOpcode() == BO_Cmp ||
9281 E->getType()->isIntegralOrEnumerationType()) &&
9282 "unsupported binary expression evaluation");
9283 auto Error = [&](const Expr *E) {
9284 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9285 return false;
9286 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009287
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009288 using CCR = ComparisonCategoryResult;
9289 bool IsRelational = E->isRelationalOp();
9290 bool IsEquality = E->isEqualityOp();
9291 if (E->getOpcode() == BO_Cmp) {
9292 const ComparisonCategoryInfo &CmpInfo =
9293 Info.Ctx.CompCategories.getInfoForType(E->getType());
9294 IsRelational = CmpInfo.isOrdered();
9295 IsEquality = CmpInfo.isEquality();
9296 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00009297
Anders Carlssonacc79812008-11-16 07:17:21 +00009298 QualType LHSTy = E->getLHS()->getType();
9299 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009300
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009301 if (LHSTy->isIntegralOrEnumerationType() &&
9302 RHSTy->isIntegralOrEnumerationType()) {
9303 APSInt LHS, RHS;
9304 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
9305 if (!LHSOK && !Info.noteFailure())
9306 return false;
9307 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
9308 return false;
9309 if (LHS < RHS)
9310 return Success(CCR::Less, E);
9311 if (LHS > RHS)
9312 return Success(CCR::Greater, E);
9313 return Success(CCR::Equal, E);
9314 }
9315
Leonard Chance1d4f12019-02-21 20:50:09 +00009316 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
9317 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
9318 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
9319
9320 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
9321 if (!LHSOK && !Info.noteFailure())
9322 return false;
9323 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
9324 return false;
9325 if (LHSFX < RHSFX)
9326 return Success(CCR::Less, E);
9327 if (LHSFX > RHSFX)
9328 return Success(CCR::Greater, E);
9329 return Success(CCR::Equal, E);
9330 }
9331
Chandler Carruthb29a7432014-10-11 11:03:30 +00009332 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009333 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00009334 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00009335 if (E->isAssignmentOp()) {
9336 LValue LV;
9337 EvaluateLValue(E->getLHS(), LV, Info);
9338 LHSOK = false;
9339 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00009340 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
9341 if (LHSOK) {
9342 LHS.makeComplexFloat();
9343 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
9344 }
9345 } else {
9346 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
9347 }
George Burgess IVa145e252016-05-25 22:38:36 +00009348 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009349 return false;
9350
Chandler Carruthb29a7432014-10-11 11:03:30 +00009351 if (E->getRHS()->getType()->isRealFloatingType()) {
9352 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
9353 return false;
9354 RHS.makeComplexFloat();
9355 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
9356 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009357 return false;
9358
9359 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00009360 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009361 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00009362 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009363 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009364 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9365 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009366 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009367 assert(IsEquality && "invalid complex comparison");
9368 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
9369 LHS.getComplexIntImag() == RHS.getComplexIntImag();
9370 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009371 }
9372 }
Mike Stump11289f42009-09-09 15:08:12 +00009373
Anders Carlssonacc79812008-11-16 07:17:21 +00009374 if (LHSTy->isRealFloatingType() &&
9375 RHSTy->isRealFloatingType()) {
9376 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00009377
Richard Smith253c2a32012-01-27 01:14:48 +00009378 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009379 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00009380 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009381
Richard Smith253c2a32012-01-27 01:14:48 +00009382 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00009383 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009384
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009385 assert(E->isComparisonOp() && "Invalid binary operator!");
9386 auto GetCmpRes = [&]() {
9387 switch (LHS.compare(RHS)) {
9388 case APFloat::cmpEqual:
9389 return CCR::Equal;
9390 case APFloat::cmpLessThan:
9391 return CCR::Less;
9392 case APFloat::cmpGreaterThan:
9393 return CCR::Greater;
9394 case APFloat::cmpUnordered:
9395 return CCR::Unordered;
9396 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +00009397 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009398 };
9399 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +00009400 }
Mike Stump11289f42009-09-09 15:08:12 +00009401
Eli Friedmana38da572009-04-28 19:17:36 +00009402 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009403 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +00009404
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009405 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9406 if (!LHSOK && !Info.noteFailure())
9407 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009408
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009409 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9410 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009411
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009412 // Reject differing bases from the normal codepath; we special-case
9413 // comparisons to null.
9414 if (!HasSameBase(LHSValue, RHSValue)) {
9415 // Inequalities and subtractions between unrelated pointers have
9416 // unspecified or undefined behavior.
9417 if (!IsEquality)
9418 return Error(E);
9419 // A constant address may compare equal to the address of a symbol.
9420 // The one exception is that address of an object cannot compare equal
9421 // to a null pointer constant.
9422 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9423 (!RHSValue.Base && !RHSValue.Offset.isZero()))
9424 return Error(E);
9425 // It's implementation-defined whether distinct literals will have
9426 // distinct addresses. In clang, the result of such a comparison is
9427 // unspecified, so it is not a constant expression. However, we do know
9428 // that the address of a literal will be non-null.
9429 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9430 LHSValue.Base && RHSValue.Base)
9431 return Error(E);
9432 // We can't tell whether weak symbols will end up pointing to the same
9433 // object.
9434 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9435 return Error(E);
9436 // We can't compare the address of the start of one object with the
9437 // past-the-end address of another object, per C++ DR1652.
9438 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9439 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9440 (RHSValue.Base && RHSValue.Offset.isZero() &&
9441 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9442 return Error(E);
9443 // We can't tell whether an object is at the same address as another
9444 // zero sized object.
9445 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9446 (LHSValue.Base && isZeroSized(RHSValue)))
9447 return Error(E);
9448 return Success(CCR::Nonequal, E);
9449 }
Eli Friedman64004332009-03-23 04:38:34 +00009450
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009451 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9452 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +00009453
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009454 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9455 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +00009456
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009457 // C++11 [expr.rel]p3:
9458 // Pointers to void (after pointer conversions) can be compared, with a
9459 // result defined as follows: If both pointers represent the same
9460 // address or are both the null pointer value, the result is true if the
9461 // operator is <= or >= and false otherwise; otherwise the result is
9462 // unspecified.
9463 // We interpret this as applying to pointers to *cv* void.
9464 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9465 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +00009466
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009467 // C++11 [expr.rel]p2:
9468 // - If two pointers point to non-static data members of the same object,
9469 // or to subobjects or array elements fo such members, recursively, the
9470 // pointer to the later declared member compares greater provided the
9471 // two members have the same access control and provided their class is
9472 // not a union.
9473 // [...]
9474 // - Otherwise pointer comparisons are unspecified.
9475 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9476 bool WasArrayIndex;
9477 unsigned Mismatch = FindDesignatorMismatch(
9478 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9479 // At the point where the designators diverge, the comparison has a
9480 // specified value if:
9481 // - we are comparing array indices
9482 // - we are comparing fields of a union, or fields with the same access
9483 // Otherwise, the result is unspecified and thus the comparison is not a
9484 // constant expression.
9485 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9486 Mismatch < RHSDesignator.Entries.size()) {
9487 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9488 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9489 if (!LF && !RF)
9490 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9491 else if (!LF)
9492 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009493 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9494 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009495 else if (!RF)
9496 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009497 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9498 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009499 else if (!LF->getParent()->isUnion() &&
9500 LF->getAccess() != RF->getAccess())
9501 Info.CCEDiag(E,
9502 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009503 << LF << LF->getAccess() << RF << RF->getAccess()
9504 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +00009505 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009506 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009507
9508 // The comparison here must be unsigned, and performed with the same
9509 // width as the pointer.
9510 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9511 uint64_t CompareLHS = LHSOffset.getQuantity();
9512 uint64_t CompareRHS = RHSOffset.getQuantity();
9513 assert(PtrSize <= 64 && "Unexpected pointer width");
9514 uint64_t Mask = ~0ULL >> (64 - PtrSize);
9515 CompareLHS &= Mask;
9516 CompareRHS &= Mask;
9517
9518 // If there is a base and this is a relational operator, we can only
9519 // compare pointers within the object in question; otherwise, the result
9520 // depends on where the object is located in memory.
9521 if (!LHSValue.Base.isNull() && IsRelational) {
9522 QualType BaseTy = getType(LHSValue.Base);
9523 if (BaseTy->isIncompleteType())
9524 return Error(E);
9525 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9526 uint64_t OffsetLimit = Size.getQuantity();
9527 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9528 return Error(E);
9529 }
9530
9531 if (CompareLHS < CompareRHS)
9532 return Success(CCR::Less, E);
9533 if (CompareLHS > CompareRHS)
9534 return Success(CCR::Greater, E);
9535 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009536 }
Richard Smith7bb00672012-02-01 01:42:44 +00009537
9538 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009539 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +00009540 assert(RHSTy->isMemberPointerType() && "invalid comparison");
9541
9542 MemberPtr LHSValue, RHSValue;
9543
9544 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009545 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00009546 return false;
9547
9548 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9549 return false;
9550
9551 // C++11 [expr.eq]p2:
9552 // If both operands are null, they compare equal. Otherwise if only one is
9553 // null, they compare unequal.
9554 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9555 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009556 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009557 }
9558
9559 // Otherwise if either is a pointer to a virtual member function, the
9560 // result is unspecified.
9561 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9562 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009563 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009564 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9565 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009566 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009567
9568 // Otherwise they compare equal if and only if they would refer to the
9569 // same member of the same most derived object or the same subobject if
9570 // they were dereferenced with a hypothetical object of the associated
9571 // class type.
9572 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009573 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009574 }
9575
Richard Smithab44d9b2012-02-14 22:35:28 +00009576 if (LHSTy->isNullPtrType()) {
9577 assert(E->isComparisonOp() && "unexpected nullptr operation");
9578 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9579 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9580 // are compared, the result is true of the operator is <=, >= or ==, and
9581 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009582 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +00009583 }
9584
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009585 return DoAfter();
9586}
9587
9588bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
9589 if (!CheckLiteralType(Info, E))
9590 return false;
9591
9592 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9593 const BinaryOperator *E) {
9594 // Evaluation succeeded. Lookup the information for the comparison category
9595 // type and fetch the VarDecl for the result.
9596 const ComparisonCategoryInfo &CmpInfo =
9597 Info.Ctx.CompCategories.getInfoForType(E->getType());
9598 const VarDecl *VD =
9599 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
9600 // Check and evaluate the result as a constant expression.
9601 LValue LV;
9602 LV.set(VD);
9603 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9604 return false;
9605 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9606 };
9607 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9608 return ExprEvaluatorBaseTy::VisitBinCmp(E);
9609 });
9610}
9611
9612bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9613 // We don't call noteFailure immediately because the assignment happens after
9614 // we evaluate LHS and RHS.
9615 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
9616 return Error(E);
9617
9618 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
9619 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
9620 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
9621
9622 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
9623 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009624 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009625
9626 if (E->isComparisonOp()) {
9627 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
9628 // comparisons and then translating the result.
9629 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9630 const BinaryOperator *E) {
9631 using CCR = ComparisonCategoryResult;
9632 bool IsEqual = ResKind == CCR::Equal,
9633 IsLess = ResKind == CCR::Less,
9634 IsGreater = ResKind == CCR::Greater;
9635 auto Op = E->getOpcode();
9636 switch (Op) {
9637 default:
9638 llvm_unreachable("unsupported binary operator");
9639 case BO_EQ:
9640 case BO_NE:
9641 return Success(IsEqual == (Op == BO_EQ), E);
9642 case BO_LT: return Success(IsLess, E);
9643 case BO_GT: return Success(IsGreater, E);
9644 case BO_LE: return Success(IsEqual || IsLess, E);
9645 case BO_GE: return Success(IsEqual || IsGreater, E);
9646 }
9647 };
9648 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9649 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9650 });
9651 }
9652
9653 QualType LHSTy = E->getLHS()->getType();
9654 QualType RHSTy = E->getRHS()->getType();
9655
9656 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
9657 E->getOpcode() == BO_Sub) {
9658 LValue LHSValue, RHSValue;
9659
9660 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9661 if (!LHSOK && !Info.noteFailure())
9662 return false;
9663
9664 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9665 return false;
9666
9667 // Reject differing bases from the normal codepath; we special-case
9668 // comparisons to null.
9669 if (!HasSameBase(LHSValue, RHSValue)) {
9670 // Handle &&A - &&B.
9671 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
9672 return Error(E);
9673 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
9674 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
9675 if (!LHSExpr || !RHSExpr)
9676 return Error(E);
9677 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9678 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9679 if (!LHSAddrExpr || !RHSAddrExpr)
9680 return Error(E);
9681 // Make sure both labels come from the same function.
9682 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9683 RHSAddrExpr->getLabel()->getDeclContext())
9684 return Error(E);
9685 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
9686 }
9687 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9688 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9689
9690 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9691 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9692
9693 // C++11 [expr.add]p6:
9694 // Unless both pointers point to elements of the same array object, or
9695 // one past the last element of the array object, the behavior is
9696 // undefined.
9697 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
9698 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
9699 RHSDesignator))
9700 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
9701
9702 QualType Type = E->getLHS()->getType();
9703 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
9704
9705 CharUnits ElementSize;
9706 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
9707 return false;
9708
9709 // As an extension, a type may have zero size (empty struct or union in
9710 // C, array of zero length). Pointer subtraction in such cases has
9711 // undefined behavior, so is not constant.
9712 if (ElementSize.isZero()) {
9713 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
9714 << ElementType;
9715 return false;
9716 }
9717
9718 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
9719 // and produce incorrect results when it overflows. Such behavior
9720 // appears to be non-conforming, but is common, so perhaps we should
9721 // assume the standard intended for such cases to be undefined behavior
9722 // and check for them.
9723
9724 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
9725 // overflow in the final conversion to ptrdiff_t.
9726 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
9727 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
9728 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
9729 false);
9730 APSInt TrueResult = (LHS - RHS) / ElemSize;
9731 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
9732
9733 if (Result.extend(65) != TrueResult &&
9734 !HandleOverflow(Info, E, TrueResult, E->getType()))
9735 return false;
9736 return Success(Result, E);
9737 }
9738
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009739 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00009740}
9741
Peter Collingbournee190dee2011-03-11 19:24:49 +00009742/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
9743/// a result as the expression's type.
9744bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
9745 const UnaryExprOrTypeTraitExpr *E) {
9746 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +00009747 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +00009748 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00009749 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +00009750 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
9751 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009752 else
Richard Smith6822bd72018-10-26 19:26:45 +00009753 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
9754 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009755 }
Eli Friedman64004332009-03-23 04:38:34 +00009756
Peter Collingbournee190dee2011-03-11 19:24:49 +00009757 case UETT_VecStep: {
9758 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00009759
Peter Collingbournee190dee2011-03-11 19:24:49 +00009760 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00009761 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00009762
Peter Collingbournee190dee2011-03-11 19:24:49 +00009763 // The vec_step built-in functions that take a 3-component
9764 // vector return 4. (OpenCL 1.1 spec 6.11.12)
9765 if (n == 3)
9766 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00009767
Peter Collingbournee190dee2011-03-11 19:24:49 +00009768 return Success(n, E);
9769 } else
9770 return Success(1, E);
9771 }
9772
9773 case UETT_SizeOf: {
9774 QualType SrcTy = E->getTypeOfArgument();
9775 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9776 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00009777 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9778 SrcTy = Ref->getPointeeType();
9779
Richard Smithd62306a2011-11-10 06:34:14 +00009780 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00009781 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00009782 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00009783 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009784 }
Alexey Bataev00396512015-07-02 03:40:19 +00009785 case UETT_OpenMPRequiredSimdAlign:
9786 assert(E->isArgumentType());
9787 return Success(
9788 Info.Ctx.toCharUnitsFromBits(
9789 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9790 .getQuantity(),
9791 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009792 }
9793
9794 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00009795}
9796
Peter Collingbournee9200682011-05-13 03:29:01 +00009797bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009798 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00009799 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00009800 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009801 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00009802 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00009803 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00009804 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00009805 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00009806 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00009807 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00009808 APSInt IdxResult;
9809 if (!EvaluateInteger(Idx, IdxResult, Info))
9810 return false;
9811 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9812 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009813 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009814 CurrentType = AT->getElementType();
9815 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9816 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00009817 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00009818 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009819
James Y Knight7281c352015-12-29 22:31:18 +00009820 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00009821 FieldDecl *MemberDecl = ON.getField();
9822 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009823 if (!RT)
9824 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009825 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009826 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00009827 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00009828 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00009829 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00009830 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00009831 CurrentType = MemberDecl->getType().getNonReferenceType();
9832 break;
9833 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009834
James Y Knight7281c352015-12-29 22:31:18 +00009835 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00009836 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00009837
James Y Knight7281c352015-12-29 22:31:18 +00009838 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00009839 CXXBaseSpecifier *BaseSpec = ON.getBase();
9840 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00009841 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009842
9843 // Find the layout of the class whose base we are looking into.
9844 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009845 if (!RT)
9846 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009847 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009848 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00009849 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9850
9851 // Find the base class itself.
9852 CurrentType = BaseSpec->getType();
9853 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9854 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009855 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +00009856
Douglas Gregord1702062010-04-29 00:18:15 +00009857 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00009858 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00009859 break;
9860 }
Douglas Gregor882211c2010-04-28 22:16:22 +00009861 }
9862 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009863 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009864}
9865
Chris Lattnere13042c2008-07-11 19:10:17 +00009866bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009867 switch (E->getOpcode()) {
9868 default:
9869 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9870 // See C99 6.6p3.
9871 return Error(E);
9872 case UO_Extension:
9873 // FIXME: Should extension allow i-c-e extension expressions in its scope?
9874 // If so, we could clear the diagnostic ID.
9875 return Visit(E->getSubExpr());
9876 case UO_Plus:
9877 // The result is just the value.
9878 return Visit(E->getSubExpr());
9879 case UO_Minus: {
9880 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00009881 return false;
9882 if (!Result.isInt()) return Error(E);
9883 const APSInt &Value = Result.getInt();
9884 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9885 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9886 E->getType()))
9887 return false;
Richard Smithfe800032012-01-31 04:08:20 +00009888 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009889 }
9890 case UO_Not: {
9891 if (!Visit(E->getSubExpr()))
9892 return false;
9893 if (!Result.isInt()) return Error(E);
9894 return Success(~Result.getInt(), E);
9895 }
9896 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00009897 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00009898 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00009899 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009900 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00009901 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009902 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009903}
Mike Stump11289f42009-09-09 15:08:12 +00009904
Chris Lattner477c4be2008-07-12 01:15:53 +00009905/// HandleCast - This is used to evaluate implicit or explicit casts where the
9906/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00009907bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9908 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009909 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00009910 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009911
Eli Friedmanc757de22011-03-25 00:43:55 +00009912 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00009913 case CK_BaseToDerived:
9914 case CK_DerivedToBase:
9915 case CK_UncheckedDerivedToBase:
9916 case CK_Dynamic:
9917 case CK_ToUnion:
9918 case CK_ArrayToPointerDecay:
9919 case CK_FunctionToPointerDecay:
9920 case CK_NullToPointer:
9921 case CK_NullToMemberPointer:
9922 case CK_BaseToDerivedMemberPointer:
9923 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00009924 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00009925 case CK_ConstructorConversion:
9926 case CK_IntegralToPointer:
9927 case CK_ToVoid:
9928 case CK_VectorSplat:
9929 case CK_IntegralToFloating:
9930 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009931 case CK_CPointerToObjCPointerCast:
9932 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009933 case CK_AnyPointerToBlockPointerCast:
9934 case CK_ObjCObjectLValueCast:
9935 case CK_FloatingRealToComplex:
9936 case CK_FloatingComplexToReal:
9937 case CK_FloatingComplexCast:
9938 case CK_FloatingComplexToIntegralComplex:
9939 case CK_IntegralRealToComplex:
9940 case CK_IntegralComplexCast:
9941 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00009942 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +00009943 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +00009944 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009945 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009946 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00009947 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +00009948 case CK_IntegralToFixedPoint:
Eli Friedmanc757de22011-03-25 00:43:55 +00009949 llvm_unreachable("invalid cast kind for integral value");
9950
Eli Friedman9faf2f92011-03-25 19:07:11 +00009951 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009952 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009953 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00009954 case CK_ARCProduceObject:
9955 case CK_ARCConsumeObject:
9956 case CK_ARCReclaimReturnedObject:
9957 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009958 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009959 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009960
Richard Smith4ef685b2012-01-17 21:17:26 +00009961 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00009962 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009963 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009964 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009965 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009966
9967 case CK_MemberPointerToBoolean:
9968 case CK_PointerToBoolean:
9969 case CK_IntegralToBoolean:
9970 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009971 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009972 case CK_FloatingComplexToBoolean:
9973 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009974 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009975 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009976 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009977 uint64_t IntResult = BoolResult;
9978 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9979 IntResult = (uint64_t)-1;
9980 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009981 }
9982
Leonard Chan8f7caae2019-03-06 00:28:43 +00009983 case CK_FixedPointToIntegral: {
9984 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
9985 if (!EvaluateFixedPoint(SubExpr, Src, Info))
9986 return false;
9987 bool Overflowed;
9988 llvm::APSInt Result = Src.convertToInt(
9989 Info.Ctx.getIntWidth(DestType),
9990 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
9991 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
9992 return false;
9993 return Success(Result, E);
9994 }
9995
Leonard Chanb4ba4672018-10-23 17:55:35 +00009996 case CK_FixedPointToBoolean: {
9997 // Unsigned padding does not affect this.
9998 APValue Val;
9999 if (!Evaluate(Val, Info, SubExpr))
10000 return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000010001 return Success(Val.getFixedPoint().getBoolValue(), E);
Leonard Chanb4ba4672018-10-23 17:55:35 +000010002 }
10003
Eli Friedmanc757de22011-03-25 00:43:55 +000010004 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +000010005 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +000010006 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +000010007
Eli Friedman742421e2009-02-20 01:15:07 +000010008 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +000010009 // Allow casts of address-of-label differences if they are no-ops
10010 // or narrowing. (The narrowing case isn't actually guaranteed to
10011 // be constant-evaluatable except in some narrow cases which are hard
10012 // to detect here. We let it through on the assumption the user knows
10013 // what they are doing.)
10014 if (Result.isAddrLabelDiff())
10015 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +000010016 // Only allow casts of lvalues if they are lossless.
10017 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
10018 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +000010019
Richard Smith911e1422012-01-30 22:27:01 +000010020 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
10021 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +000010022 }
Mike Stump11289f42009-09-09 15:08:12 +000010023
Eli Friedmanc757de22011-03-25 00:43:55 +000010024 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +000010025 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
10026
John McCall45d55e42010-05-07 21:00:08 +000010027 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +000010028 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +000010029 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +000010030
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000010031 if (LV.getLValueBase()) {
10032 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +000010033 // FIXME: Allow a larger integer size than the pointer size, and allow
10034 // narrowing back down to pointer width in subsequent integral casts.
10035 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000010036 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010037 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +000010038
Richard Smithcf74da72011-11-16 07:18:12 +000010039 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +000010040 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +000010041 return true;
10042 }
10043
Hans Wennborgdd1ea8a2019-03-06 10:26:19 +000010044 APSInt AsInt;
10045 APValue V;
10046 LV.moveInto(V);
10047 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
10048 llvm_unreachable("Can't cast this!");
Yaxun Liu402804b2016-12-15 08:09:08 +000010049
Richard Smith911e1422012-01-30 22:27:01 +000010050 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +000010051 }
Eli Friedman9a156e52008-11-12 09:44:48 +000010052
Eli Friedmanc757de22011-03-25 00:43:55 +000010053 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +000010054 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000010055 if (!EvaluateComplex(SubExpr, C, Info))
10056 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +000010057 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +000010058 }
Eli Friedmanc2b50172009-02-22 11:46:18 +000010059
Eli Friedmanc757de22011-03-25 00:43:55 +000010060 case CK_FloatingToIntegral: {
10061 APFloat F(0.0);
10062 if (!EvaluateFloat(SubExpr, F, Info))
10063 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +000010064
Richard Smith357362d2011-12-13 06:39:58 +000010065 APSInt Value;
10066 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
10067 return false;
10068 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +000010069 }
10070 }
Mike Stump11289f42009-09-09 15:08:12 +000010071
Eli Friedmanc757de22011-03-25 00:43:55 +000010072 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +000010073}
Anders Carlssonb5ad0212008-07-08 14:30:00 +000010074
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010075bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
10076 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +000010077 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010078 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
10079 return false;
10080 if (!LV.isComplexInt())
10081 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010082 return Success(LV.getComplexIntReal(), E);
10083 }
10084
10085 return Visit(E->getSubExpr());
10086}
10087
Eli Friedman4e7a2412009-02-27 04:45:43 +000010088bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010089 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +000010090 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010091 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
10092 return false;
10093 if (!LV.isComplexInt())
10094 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +000010095 return Success(LV.getComplexIntImag(), E);
10096 }
10097
Richard Smith4a678122011-10-24 18:44:57 +000010098 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +000010099 return Success(0, E);
10100}
10101
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010102bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
10103 return Success(E->getPackLength(), E);
10104}
10105
Sebastian Redl5f0180d2010-09-10 20:55:47 +000010106bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
10107 return Success(E->getValue(), E);
10108}
10109
Leonard Chandb01c3a2018-06-20 17:19:40 +000010110bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10111 switch (E->getOpcode()) {
10112 default:
10113 // Invalid unary operators
10114 return Error(E);
10115 case UO_Plus:
10116 // The result is just the value.
10117 return Visit(E->getSubExpr());
10118 case UO_Minus: {
10119 if (!Visit(E->getSubExpr())) return false;
Leonard Chand3f3e162019-01-18 21:04:25 +000010120 if (!Result.isFixedPoint())
10121 return Error(E);
10122 bool Overflowed;
10123 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
10124 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
10125 return false;
10126 return Success(Negated, E);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010127 }
10128 case UO_LNot: {
10129 bool bres;
10130 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
10131 return false;
10132 return Success(!bres, E);
10133 }
10134 }
10135}
10136
Leonard Chand3f3e162019-01-18 21:04:25 +000010137bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
10138 const Expr *SubExpr = E->getSubExpr();
10139 QualType DestType = E->getType();
10140 assert(DestType->isFixedPointType() &&
10141 "Expected destination type to be a fixed point type");
10142 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
10143
10144 switch (E->getCastKind()) {
10145 case CK_FixedPointCast: {
10146 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
10147 if (!EvaluateFixedPoint(SubExpr, Src, Info))
10148 return false;
10149 bool Overflowed;
10150 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
10151 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
10152 return false;
10153 return Success(Result, E);
10154 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000010155 case CK_IntegralToFixedPoint: {
10156 APSInt Src;
10157 if (!EvaluateInteger(SubExpr, Src, Info))
10158 return false;
10159
10160 bool Overflowed;
10161 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
10162 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
10163
10164 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
10165 return false;
10166
10167 return Success(IntResult, E);
10168 }
Leonard Chand3f3e162019-01-18 21:04:25 +000010169 case CK_NoOp:
10170 case CK_LValueToRValue:
10171 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10172 default:
10173 return Error(E);
10174 }
10175}
10176
10177bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10178 const Expr *LHS = E->getLHS();
10179 const Expr *RHS = E->getRHS();
10180 FixedPointSemantics ResultFXSema =
10181 Info.Ctx.getFixedPointSemantics(E->getType());
10182
10183 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
10184 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
10185 return false;
10186 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
10187 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
10188 return false;
10189
10190 switch (E->getOpcode()) {
10191 case BO_Add: {
10192 bool AddOverflow, ConversionOverflow;
10193 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
10194 .convert(ResultFXSema, &ConversionOverflow);
10195 if ((AddOverflow || ConversionOverflow) &&
10196 !HandleOverflow(Info, E, Result, E->getType()))
10197 return false;
10198 return Success(Result, E);
10199 }
10200 default:
10201 return false;
10202 }
10203 llvm_unreachable("Should've exited before this");
10204}
10205
Chris Lattner05706e882008-07-11 18:11:29 +000010206//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +000010207// Float Evaluation
10208//===----------------------------------------------------------------------===//
10209
10210namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000010211class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010212 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +000010213 APFloat &Result;
10214public:
10215 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +000010216 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +000010217
Richard Smith2e312c82012-03-03 22:46:17 +000010218 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010219 Result = V.getFloat();
10220 return true;
10221 }
Eli Friedman24c01542008-08-22 00:06:13 +000010222
Richard Smithfddd3842011-12-30 21:15:51 +000010223 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +000010224 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
10225 return true;
10226 }
10227
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010228 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +000010229
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010230 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +000010231 bool VisitBinaryOperator(const BinaryOperator *E);
10232 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000010233 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +000010234
John McCallb1fb0d32010-05-07 22:08:54 +000010235 bool VisitUnaryReal(const UnaryOperator *E);
10236 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +000010237
Richard Smithfddd3842011-12-30 21:15:51 +000010238 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +000010239};
10240} // end anonymous namespace
10241
10242static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000010243 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010244 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +000010245}
10246
Jay Foad39c79802011-01-12 09:06:06 +000010247static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +000010248 QualType ResultTy,
10249 const Expr *Arg,
10250 bool SNaN,
10251 llvm::APFloat &Result) {
10252 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
10253 if (!S) return false;
10254
10255 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
10256
10257 llvm::APInt fill;
10258
10259 // Treat empty strings as if they were zero.
10260 if (S->getString().empty())
10261 fill = llvm::APInt(32, 0);
10262 else if (S->getString().getAsInteger(0, fill))
10263 return false;
10264
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +000010265 if (Context.getTargetInfo().isNan2008()) {
10266 if (SNaN)
10267 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10268 else
10269 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10270 } else {
10271 // Prior to IEEE 754-2008, architectures were allowed to choose whether
10272 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
10273 // a different encoding to what became a standard in 2008, and for pre-
10274 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
10275 // sNaN. This is now known as "legacy NaN" encoding.
10276 if (SNaN)
10277 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10278 else
10279 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10280 }
10281
John McCall16291492010-02-28 13:00:19 +000010282 return true;
10283}
10284
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010285bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000010286 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010287 default:
10288 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10289
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010290 case Builtin::BI__builtin_huge_val:
10291 case Builtin::BI__builtin_huge_valf:
10292 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010293 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010294 case Builtin::BI__builtin_inf:
10295 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010296 case Builtin::BI__builtin_infl:
10297 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010298 const llvm::fltSemantics &Sem =
10299 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000010300 Result = llvm::APFloat::getInf(Sem);
10301 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010302 }
Mike Stump11289f42009-09-09 15:08:12 +000010303
John McCall16291492010-02-28 13:00:19 +000010304 case Builtin::BI__builtin_nans:
10305 case Builtin::BI__builtin_nansf:
10306 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010307 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010308 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10309 true, Result))
10310 return Error(E);
10311 return true;
John McCall16291492010-02-28 13:00:19 +000010312
Chris Lattner0b7282e2008-10-06 06:31:58 +000010313 case Builtin::BI__builtin_nan:
10314 case Builtin::BI__builtin_nanf:
10315 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010316 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000010317 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000010318 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000010319 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10320 false, Result))
10321 return Error(E);
10322 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010323
10324 case Builtin::BI__builtin_fabs:
10325 case Builtin::BI__builtin_fabsf:
10326 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010327 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010328 if (!EvaluateFloat(E->getArg(0), Result, Info))
10329 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010330
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010331 if (Result.isNegative())
10332 Result.changeSign();
10333 return true;
10334
Richard Smith8889a3d2013-06-13 06:26:32 +000010335 // FIXME: Builtin::BI__builtin_powi
10336 // FIXME: Builtin::BI__builtin_powif
10337 // FIXME: Builtin::BI__builtin_powil
10338
Mike Stump11289f42009-09-09 15:08:12 +000010339 case Builtin::BI__builtin_copysign:
10340 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010341 case Builtin::BI__builtin_copysignl:
10342 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010343 APFloat RHS(0.);
10344 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
10345 !EvaluateFloat(E->getArg(1), RHS, Info))
10346 return false;
10347 Result.copySign(RHS);
10348 return true;
10349 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010350 }
10351}
10352
John McCallb1fb0d32010-05-07 22:08:54 +000010353bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000010354 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10355 ComplexValue CV;
10356 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10357 return false;
10358 Result = CV.FloatReal;
10359 return true;
10360 }
10361
10362 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000010363}
10364
10365bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000010366 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10367 ComplexValue CV;
10368 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10369 return false;
10370 Result = CV.FloatImag;
10371 return true;
10372 }
10373
Richard Smith4a678122011-10-24 18:44:57 +000010374 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000010375 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
10376 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000010377 return true;
10378}
10379
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010380bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010381 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010382 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000010383 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000010384 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000010385 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000010386 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
10387 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010388 Result.changeSign();
10389 return true;
10390 }
10391}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010392
Eli Friedman24c01542008-08-22 00:06:13 +000010393bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000010394 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10395 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000010396
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010397 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000010398 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010399 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000010400 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000010401 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
10402 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000010403}
10404
10405bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
10406 Result = E->getValue();
10407 return true;
10408}
10409
Peter Collingbournee9200682011-05-13 03:29:01 +000010410bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
10411 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000010412
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010413 switch (E->getCastKind()) {
10414 default:
Richard Smith11562c52011-10-28 17:51:58 +000010415 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010416
10417 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010418 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000010419 return EvaluateInteger(SubExpr, IntResult, Info) &&
10420 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
10421 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000010422 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010423
10424 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010425 if (!Visit(SubExpr))
10426 return false;
Richard Smith357362d2011-12-13 06:39:58 +000010427 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
10428 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000010429 }
John McCalld7646252010-11-14 08:17:51 +000010430
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010431 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000010432 ComplexValue V;
10433 if (!EvaluateComplex(SubExpr, V, Info))
10434 return false;
10435 Result = V.getComplexFloatReal();
10436 return true;
10437 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010438 }
Eli Friedman9a156e52008-11-12 09:44:48 +000010439}
10440
Eli Friedman24c01542008-08-22 00:06:13 +000010441//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010442// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000010443//===----------------------------------------------------------------------===//
10444
10445namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000010446class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010447 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000010448 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000010449
Anders Carlsson537969c2008-11-16 20:27:53 +000010450public:
John McCall93d91dc2010-05-07 17:22:02 +000010451 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000010452 : ExprEvaluatorBaseTy(info), Result(Result) {}
10453
Richard Smith2e312c82012-03-03 22:46:17 +000010454 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010455 Result.setFrom(V);
10456 return true;
10457 }
Mike Stump11289f42009-09-09 15:08:12 +000010458
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010459 bool ZeroInitialization(const Expr *E);
10460
Anders Carlsson537969c2008-11-16 20:27:53 +000010461 //===--------------------------------------------------------------------===//
10462 // Visitor Methods
10463 //===--------------------------------------------------------------------===//
10464
Peter Collingbournee9200682011-05-13 03:29:01 +000010465 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000010466 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000010467 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010468 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010469 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010470};
10471} // end anonymous namespace
10472
John McCall93d91dc2010-05-07 17:22:02 +000010473static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
10474 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000010475 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010476 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010477}
10478
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010479bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000010480 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010481 if (ElemTy->isRealFloatingType()) {
10482 Result.makeComplexFloat();
10483 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10484 Result.FloatReal = Zero;
10485 Result.FloatImag = Zero;
10486 } else {
10487 Result.makeComplexInt();
10488 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10489 Result.IntReal = Zero;
10490 Result.IntImag = Zero;
10491 }
10492 return true;
10493}
10494
Peter Collingbournee9200682011-05-13 03:29:01 +000010495bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10496 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010497
10498 if (SubExpr->getType()->isRealFloatingType()) {
10499 Result.makeComplexFloat();
10500 APFloat &Imag = Result.FloatImag;
10501 if (!EvaluateFloat(SubExpr, Imag, Info))
10502 return false;
10503
10504 Result.FloatReal = APFloat(Imag.getSemantics());
10505 return true;
10506 } else {
10507 assert(SubExpr->getType()->isIntegerType() &&
10508 "Unexpected imaginary literal.");
10509
10510 Result.makeComplexInt();
10511 APSInt &Imag = Result.IntImag;
10512 if (!EvaluateInteger(SubExpr, Imag, Info))
10513 return false;
10514
10515 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10516 return true;
10517 }
10518}
10519
Peter Collingbournee9200682011-05-13 03:29:01 +000010520bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010521
John McCallfcef3cf2010-12-14 17:51:41 +000010522 switch (E->getCastKind()) {
10523 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010524 case CK_BaseToDerived:
10525 case CK_DerivedToBase:
10526 case CK_UncheckedDerivedToBase:
10527 case CK_Dynamic:
10528 case CK_ToUnion:
10529 case CK_ArrayToPointerDecay:
10530 case CK_FunctionToPointerDecay:
10531 case CK_NullToPointer:
10532 case CK_NullToMemberPointer:
10533 case CK_BaseToDerivedMemberPointer:
10534 case CK_DerivedToBaseMemberPointer:
10535 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000010536 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000010537 case CK_ConstructorConversion:
10538 case CK_IntegralToPointer:
10539 case CK_PointerToIntegral:
10540 case CK_PointerToBoolean:
10541 case CK_ToVoid:
10542 case CK_VectorSplat:
10543 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000010544 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000010545 case CK_IntegralToBoolean:
10546 case CK_IntegralToFloating:
10547 case CK_FloatingToIntegral:
10548 case CK_FloatingToBoolean:
10549 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000010550 case CK_CPointerToObjCPointerCast:
10551 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010552 case CK_AnyPointerToBlockPointerCast:
10553 case CK_ObjCObjectLValueCast:
10554 case CK_FloatingComplexToReal:
10555 case CK_FloatingComplexToBoolean:
10556 case CK_IntegralComplexToReal:
10557 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000010558 case CK_ARCProduceObject:
10559 case CK_ARCConsumeObject:
10560 case CK_ARCReclaimReturnedObject:
10561 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000010562 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000010563 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000010564 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000010565 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000010566 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000010567 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000010568 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000010569 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +000010570 case CK_FixedPointToIntegral:
10571 case CK_IntegralToFixedPoint:
John McCallfcef3cf2010-12-14 17:51:41 +000010572 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000010573
John McCallfcef3cf2010-12-14 17:51:41 +000010574 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010575 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000010576 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +000010577 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010578
10579 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000010580 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010581 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010582 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010583
10584 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010585 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000010586 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010587 return false;
10588
John McCallfcef3cf2010-12-14 17:51:41 +000010589 Result.makeComplexFloat();
10590 Result.FloatImag = APFloat(Real.getSemantics());
10591 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010592 }
10593
John McCallfcef3cf2010-12-14 17:51:41 +000010594 case CK_FloatingComplexCast: {
10595 if (!Visit(E->getSubExpr()))
10596 return false;
10597
10598 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10599 QualType From
10600 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10601
Richard Smith357362d2011-12-13 06:39:58 +000010602 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
10603 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010604 }
10605
10606 case CK_FloatingComplexToIntegralComplex: {
10607 if (!Visit(E->getSubExpr()))
10608 return false;
10609
10610 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10611 QualType From
10612 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10613 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000010614 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
10615 To, Result.IntReal) &&
10616 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
10617 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010618 }
10619
10620 case CK_IntegralRealToComplex: {
10621 APSInt &Real = Result.IntReal;
10622 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
10623 return false;
10624
10625 Result.makeComplexInt();
10626 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
10627 return true;
10628 }
10629
10630 case CK_IntegralComplexCast: {
10631 if (!Visit(E->getSubExpr()))
10632 return false;
10633
10634 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10635 QualType From
10636 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10637
Richard Smith911e1422012-01-30 22:27:01 +000010638 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
10639 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010640 return true;
10641 }
10642
10643 case CK_IntegralComplexToFloatingComplex: {
10644 if (!Visit(E->getSubExpr()))
10645 return false;
10646
Ted Kremenek28831752012-08-23 20:46:57 +000010647 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010648 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000010649 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010650 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000010651 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
10652 To, Result.FloatReal) &&
10653 HandleIntToFloatCast(Info, E, From, Result.IntImag,
10654 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010655 }
10656 }
10657
10658 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010659}
10660
John McCall93d91dc2010-05-07 17:22:02 +000010661bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000010662 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000010663 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10664
Chandler Carrutha216cad2014-10-11 00:57:18 +000010665 // Track whether the LHS or RHS is real at the type system level. When this is
10666 // the case we can simplify our evaluation strategy.
10667 bool LHSReal = false, RHSReal = false;
10668
10669 bool LHSOK;
10670 if (E->getLHS()->getType()->isRealFloatingType()) {
10671 LHSReal = true;
10672 APFloat &Real = Result.FloatReal;
10673 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
10674 if (LHSOK) {
10675 Result.makeComplexFloat();
10676 Result.FloatImag = APFloat(Real.getSemantics());
10677 }
10678 } else {
10679 LHSOK = Visit(E->getLHS());
10680 }
George Burgess IVa145e252016-05-25 22:38:36 +000010681 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000010682 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010683
John McCall93d91dc2010-05-07 17:22:02 +000010684 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010685 if (E->getRHS()->getType()->isRealFloatingType()) {
10686 RHSReal = true;
10687 APFloat &Real = RHS.FloatReal;
10688 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
10689 return false;
10690 RHS.makeComplexFloat();
10691 RHS.FloatImag = APFloat(Real.getSemantics());
10692 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000010693 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010694
Chandler Carrutha216cad2014-10-11 00:57:18 +000010695 assert(!(LHSReal && RHSReal) &&
10696 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010697 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010698 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000010699 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010700 if (Result.isComplexFloat()) {
10701 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
10702 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010703 if (LHSReal)
10704 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10705 else if (!RHSReal)
10706 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
10707 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010708 } else {
10709 Result.getComplexIntReal() += RHS.getComplexIntReal();
10710 Result.getComplexIntImag() += RHS.getComplexIntImag();
10711 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010712 break;
John McCalle3027922010-08-25 11:45:40 +000010713 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010714 if (Result.isComplexFloat()) {
10715 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
10716 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010717 if (LHSReal) {
10718 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10719 Result.getComplexFloatImag().changeSign();
10720 } else if (!RHSReal) {
10721 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
10722 APFloat::rmNearestTiesToEven);
10723 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010724 } else {
10725 Result.getComplexIntReal() -= RHS.getComplexIntReal();
10726 Result.getComplexIntImag() -= RHS.getComplexIntImag();
10727 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010728 break;
John McCalle3027922010-08-25 11:45:40 +000010729 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010730 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010731 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000010732 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010733 // following naming scheme:
10734 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000010735 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010736 APFloat &A = LHS.getComplexFloatReal();
10737 APFloat &B = LHS.getComplexFloatImag();
10738 APFloat &C = RHS.getComplexFloatReal();
10739 APFloat &D = RHS.getComplexFloatImag();
10740 APFloat &ResR = Result.getComplexFloatReal();
10741 APFloat &ResI = Result.getComplexFloatImag();
10742 if (LHSReal) {
10743 assert(!RHSReal && "Cannot have two real operands for a complex op!");
10744 ResR = A * C;
10745 ResI = A * D;
10746 } else if (RHSReal) {
10747 ResR = C * A;
10748 ResI = C * B;
10749 } else {
10750 // In the fully general case, we need to handle NaNs and infinities
10751 // robustly.
10752 APFloat AC = A * C;
10753 APFloat BD = B * D;
10754 APFloat AD = A * D;
10755 APFloat BC = B * C;
10756 ResR = AC - BD;
10757 ResI = AD + BC;
10758 if (ResR.isNaN() && ResI.isNaN()) {
10759 bool Recalc = false;
10760 if (A.isInfinity() || B.isInfinity()) {
10761 A = APFloat::copySign(
10762 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10763 B = APFloat::copySign(
10764 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10765 if (C.isNaN())
10766 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10767 if (D.isNaN())
10768 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10769 Recalc = true;
10770 }
10771 if (C.isInfinity() || D.isInfinity()) {
10772 C = APFloat::copySign(
10773 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10774 D = APFloat::copySign(
10775 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10776 if (A.isNaN())
10777 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10778 if (B.isNaN())
10779 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10780 Recalc = true;
10781 }
10782 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
10783 AD.isInfinity() || BC.isInfinity())) {
10784 if (A.isNaN())
10785 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10786 if (B.isNaN())
10787 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10788 if (C.isNaN())
10789 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10790 if (D.isNaN())
10791 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10792 Recalc = true;
10793 }
10794 if (Recalc) {
10795 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
10796 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
10797 }
10798 }
10799 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010800 } else {
John McCall93d91dc2010-05-07 17:22:02 +000010801 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000010802 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010803 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
10804 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000010805 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010806 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
10807 LHS.getComplexIntImag() * RHS.getComplexIntReal());
10808 }
10809 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010810 case BO_Div:
10811 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010812 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000010813 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010814 // following naming scheme:
10815 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010816 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010817 APFloat &A = LHS.getComplexFloatReal();
10818 APFloat &B = LHS.getComplexFloatImag();
10819 APFloat &C = RHS.getComplexFloatReal();
10820 APFloat &D = RHS.getComplexFloatImag();
10821 APFloat &ResR = Result.getComplexFloatReal();
10822 APFloat &ResI = Result.getComplexFloatImag();
10823 if (RHSReal) {
10824 ResR = A / C;
10825 ResI = B / C;
10826 } else {
10827 if (LHSReal) {
10828 // No real optimizations we can do here, stub out with zero.
10829 B = APFloat::getZero(A.getSemantics());
10830 }
10831 int DenomLogB = 0;
10832 APFloat MaxCD = maxnum(abs(C), abs(D));
10833 if (MaxCD.isFinite()) {
10834 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000010835 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
10836 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010837 }
10838 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000010839 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
10840 APFloat::rmNearestTiesToEven);
10841 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
10842 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010843 if (ResR.isNaN() && ResI.isNaN()) {
10844 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
10845 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
10846 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
10847 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
10848 D.isFinite()) {
10849 A = APFloat::copySign(
10850 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10851 B = APFloat::copySign(
10852 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10853 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
10854 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
10855 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
10856 C = APFloat::copySign(
10857 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10858 D = APFloat::copySign(
10859 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10860 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
10861 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
10862 }
10863 }
10864 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010865 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010866 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
10867 return Error(E, diag::note_expr_divide_by_zero);
10868
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010869 ComplexValue LHS = Result;
10870 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
10871 RHS.getComplexIntImag() * RHS.getComplexIntImag();
10872 Result.getComplexIntReal() =
10873 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10874 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10875 Result.getComplexIntImag() =
10876 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10877 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10878 }
10879 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010880 }
10881
John McCall93d91dc2010-05-07 17:22:02 +000010882 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010883}
10884
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010885bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10886 // Get the operand value into 'Result'.
10887 if (!Visit(E->getSubExpr()))
10888 return false;
10889
10890 switch (E->getOpcode()) {
10891 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010892 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010893 case UO_Extension:
10894 return true;
10895 case UO_Plus:
10896 // The result is always just the subexpr.
10897 return true;
10898 case UO_Minus:
10899 if (Result.isComplexFloat()) {
10900 Result.getComplexFloatReal().changeSign();
10901 Result.getComplexFloatImag().changeSign();
10902 }
10903 else {
10904 Result.getComplexIntReal() = -Result.getComplexIntReal();
10905 Result.getComplexIntImag() = -Result.getComplexIntImag();
10906 }
10907 return true;
10908 case UO_Not:
10909 if (Result.isComplexFloat())
10910 Result.getComplexFloatImag().changeSign();
10911 else
10912 Result.getComplexIntImag() = -Result.getComplexIntImag();
10913 return true;
10914 }
10915}
10916
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010917bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10918 if (E->getNumInits() == 2) {
10919 if (E->getType()->isComplexType()) {
10920 Result.makeComplexFloat();
10921 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10922 return false;
10923 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10924 return false;
10925 } else {
10926 Result.makeComplexInt();
10927 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10928 return false;
10929 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10930 return false;
10931 }
10932 return true;
10933 }
10934 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10935}
10936
Anders Carlsson537969c2008-11-16 20:27:53 +000010937//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000010938// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10939// implicit conversion.
10940//===----------------------------------------------------------------------===//
10941
10942namespace {
10943class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000010944 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010945 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000010946 APValue &Result;
10947public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010948 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10949 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000010950
10951 bool Success(const APValue &V, const Expr *E) {
10952 Result = V;
10953 return true;
10954 }
10955
10956 bool ZeroInitialization(const Expr *E) {
10957 ImplicitValueInitExpr VIE(
10958 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010959 // For atomic-qualified class (and array) types in C++, initialize the
10960 // _Atomic-wrapped subobject directly, in-place.
10961 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10962 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000010963 }
10964
10965 bool VisitCastExpr(const CastExpr *E) {
10966 switch (E->getCastKind()) {
10967 default:
10968 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10969 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010970 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10971 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000010972 }
10973 }
10974};
10975} // end anonymous namespace
10976
Richard Smith64cb9ca2017-02-22 22:09:50 +000010977static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10978 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000010979 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010980 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000010981}
10982
10983//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000010984// Void expression evaluation, primarily for a cast to void on the LHS of a
10985// comma operator
10986//===----------------------------------------------------------------------===//
10987
10988namespace {
10989class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010990 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000010991public:
10992 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10993
Richard Smith2e312c82012-03-03 22:46:17 +000010994 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000010995
Richard Smith7cd577b2017-08-17 19:35:50 +000010996 bool ZeroInitialization(const Expr *E) { return true; }
10997
Richard Smith42d3af92011-12-07 00:43:50 +000010998 bool VisitCastExpr(const CastExpr *E) {
10999 switch (E->getCastKind()) {
11000 default:
11001 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11002 case CK_ToVoid:
11003 VisitIgnoredValue(E->getSubExpr());
11004 return true;
11005 }
11006 }
Hal Finkela8443c32014-07-17 14:49:58 +000011007
11008 bool VisitCallExpr(const CallExpr *E) {
11009 switch (E->getBuiltinCallee()) {
11010 default:
11011 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11012 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000011013 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000011014 // The argument is not evaluated!
11015 return true;
11016 }
11017 }
Richard Smith42d3af92011-12-07 00:43:50 +000011018};
11019} // end anonymous namespace
11020
11021static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
11022 assert(E->isRValue() && E->getType()->isVoidType());
11023 return VoidExprEvaluator(Info).Visit(E);
11024}
11025
11026//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000011027// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000011028//===----------------------------------------------------------------------===//
11029
Richard Smith2e312c82012-03-03 22:46:17 +000011030static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000011031 // In C, function designators are not lvalues, but we evaluate them as if they
11032 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000011033 QualType T = E->getType();
11034 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000011035 LValue LV;
11036 if (!EvaluateLValue(E, LV, Info))
11037 return false;
11038 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000011039 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000011040 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000011041 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011042 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000011043 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011044 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011045 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000011046 LValue LV;
11047 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011048 return false;
Richard Smith725810a2011-10-16 21:26:27 +000011049 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000011050 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000011051 llvm::APFloat F(0.0);
11052 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011053 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000011054 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000011055 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000011056 ComplexValue C;
11057 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011058 return false;
Richard Smith725810a2011-10-16 21:26:27 +000011059 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000011060 } else if (T->isFixedPointType()) {
11061 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011062 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000011063 MemberPtr P;
11064 if (!EvaluateMemberPointer(E, P, Info))
11065 return false;
11066 P.moveInto(Result);
11067 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000011068 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000011069 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011070 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000011071 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000011072 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000011073 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000011074 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000011075 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011076 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000011077 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000011078 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000011079 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000011080 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011081 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000011082 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000011083 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000011084 if (!EvaluateVoid(E, Info))
11085 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000011086 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000011087 QualType Unqual = T.getAtomicUnqualifiedType();
11088 if (Unqual->isArrayType() || Unqual->isRecordType()) {
11089 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011090 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000011091 if (!EvaluateAtomic(E, &LV, Value, Info))
11092 return false;
11093 } else {
11094 if (!EvaluateAtomic(E, nullptr, Result, Info))
11095 return false;
11096 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011097 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000011098 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000011099 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011100 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000011101 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000011102 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011103 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000011104
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000011105 return true;
11106}
11107
Richard Smithb228a862012-02-15 02:18:13 +000011108/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
11109/// cases, the in-place evaluation is essential, since later initializers for
11110/// an object can indirectly refer to subobjects which were initialized earlier.
11111static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000011112 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000011113 assert(!E->isValueDependent());
11114
Richard Smith7525ff62013-05-09 07:14:00 +000011115 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000011116 return false;
11117
11118 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000011119 // Evaluate arrays and record types in-place, so that later initializers can
11120 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000011121 QualType T = E->getType();
11122 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000011123 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000011124 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000011125 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000011126 else if (T->isAtomicType()) {
11127 QualType Unqual = T.getAtomicUnqualifiedType();
11128 if (Unqual->isArrayType() || Unqual->isRecordType())
11129 return EvaluateAtomic(E, &This, Result, Info);
11130 }
Richard Smithed5165f2011-11-04 05:33:44 +000011131 }
11132
11133 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000011134 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000011135}
11136
Richard Smithf57d8cb2011-12-09 22:58:01 +000011137/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
11138/// lvalue-to-rvalue cast if it is an lvalue.
11139static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000011140 if (E->getType().isNull())
11141 return false;
11142
Nick Lewyckyc190f962017-05-02 01:06:16 +000011143 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000011144 return false;
11145
Richard Smith2e312c82012-03-03 22:46:17 +000011146 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011147 return false;
11148
11149 if (E->isGLValue()) {
11150 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000011151 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000011152 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011153 return false;
11154 }
11155
Richard Smith2e312c82012-03-03 22:46:17 +000011156 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000011157 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011158}
Richard Smith11562c52011-10-28 17:51:58 +000011159
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011160static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000011161 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011162 // Fast-path evaluations of integer literals, since we sometimes see files
11163 // containing vast quantities of these.
11164 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
11165 Result.Val = APValue(APSInt(L->getValue(),
11166 L->getType()->isUnsignedIntegerType()));
11167 IsConst = true;
11168 return true;
11169 }
James Dennett0492ef02014-03-14 17:44:10 +000011170
11171 // This case should be rare, but we need to check it before we check on
11172 // the type below.
11173 if (Exp->getType().isNull()) {
11174 IsConst = false;
11175 return true;
11176 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011177
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011178 // FIXME: Evaluating values of large array and record types can cause
11179 // performance problems. Only do so in C++11 for now.
11180 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
11181 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000011182 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011183 IsConst = false;
11184 return true;
11185 }
11186 return false;
11187}
11188
Fangrui Song407659a2018-11-30 23:41:18 +000011189static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
11190 Expr::SideEffectsKind SEK) {
11191 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
11192 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
11193}
11194
11195static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
11196 const ASTContext &Ctx, EvalInfo &Info) {
11197 bool IsConst;
11198 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
11199 return IsConst;
11200
11201 return EvaluateAsRValue(Info, E, Result.Val);
11202}
11203
11204static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
11205 const ASTContext &Ctx,
11206 Expr::SideEffectsKind AllowSideEffects,
11207 EvalInfo &Info) {
11208 if (!E->getType()->isIntegralOrEnumerationType())
11209 return false;
11210
11211 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
11212 !ExprResult.Val.isInt() ||
11213 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11214 return false;
11215
11216 return true;
11217}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011218
Leonard Chand3f3e162019-01-18 21:04:25 +000011219static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
11220 const ASTContext &Ctx,
11221 Expr::SideEffectsKind AllowSideEffects,
11222 EvalInfo &Info) {
11223 if (!E->getType()->isFixedPointType())
11224 return false;
11225
11226 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
11227 return false;
11228
11229 if (!ExprResult.Val.isFixedPoint() ||
11230 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11231 return false;
11232
11233 return true;
11234}
11235
Richard Smith7b553f12011-10-29 00:50:52 +000011236/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000011237/// any crazy technique (that has nothing to do with language standards) that
11238/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000011239/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
11240/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000011241bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
11242 bool InConstantContext) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000011243 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000011244 Info.InConstantContext = InConstantContext;
11245 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000011246}
11247
Jay Foad39c79802011-01-12 09:06:06 +000011248bool Expr::EvaluateAsBooleanCondition(bool &Result,
11249 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000011250 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000011251 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000011252 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000011253}
11254
Fangrui Song407659a2018-11-30 23:41:18 +000011255bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Richard Smith5fab0c92011-12-28 19:48:30 +000011256 SideEffectsKind AllowSideEffects) const {
Fangrui Song407659a2018-11-30 23:41:18 +000011257 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11258 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000011259}
11260
Leonard Chand3f3e162019-01-18 21:04:25 +000011261bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
11262 SideEffectsKind AllowSideEffects) const {
11263 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11264 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
11265}
11266
Richard Trieube234c32016-04-21 21:04:55 +000011267bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
11268 SideEffectsKind AllowSideEffects) const {
11269 if (!getType()->isRealFloatingType())
11270 return false;
11271
11272 EvalResult ExprResult;
11273 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000011274 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000011275 return false;
11276
11277 Result = ExprResult.Val.getFloat();
11278 return true;
11279}
11280
Jay Foad39c79802011-01-12 09:06:06 +000011281bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000011282 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000011283
John McCall45d55e42010-05-07 21:00:08 +000011284 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000011285 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
11286 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000011287 Ctx.getLValueReferenceType(getType()), LV,
11288 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000011289 return false;
11290
Richard Smith2e312c82012-03-03 22:46:17 +000011291 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000011292 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000011293}
11294
Reid Kleckner1a840d22018-05-10 18:57:35 +000011295bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
11296 const ASTContext &Ctx) const {
11297 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
11298 EvalInfo Info(Ctx, Result, EM);
Eric Fiselier680e8652019-03-08 22:06:48 +000011299 Info.InConstantContext = true;
Eric Fiselieradd16a82019-04-24 02:23:30 +000011300
Reid Kleckner1a840d22018-05-10 18:57:35 +000011301 if (!::Evaluate(Result.Val, Info, this))
11302 return false;
11303
11304 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
11305 Usage);
11306}
11307
Richard Smithd0b4dd62011-12-19 06:19:21 +000011308bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
11309 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011310 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000011311 // FIXME: Evaluating initializers for large array and record types can cause
11312 // performance problems. Only do so in C++11 for now.
11313 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011314 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000011315 return false;
11316
Richard Smithd0b4dd62011-12-19 06:19:21 +000011317 Expr::EvalStatus EStatus;
11318 EStatus.Diag = &Notes;
11319
Richard Smith0c6124b2015-12-03 01:36:22 +000011320 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
11321 ? EvalInfo::EM_ConstantExpression
11322 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000011323 InitInfo.setEvaluatingDecl(VD, Value);
Fangrui Song407659a2018-11-30 23:41:18 +000011324 InitInfo.InConstantContext = true;
Richard Smithd0b4dd62011-12-19 06:19:21 +000011325
11326 LValue LVal;
11327 LVal.set(VD);
11328
Richard Smithfddd3842011-12-30 21:15:51 +000011329 // C++11 [basic.start.init]p2:
11330 // Variables with static storage duration or thread storage duration shall be
11331 // zero-initialized before any other initialization takes place.
11332 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011333 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000011334 !VD->getType()->isReferenceType()) {
11335 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000011336 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000011337 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000011338 return false;
11339 }
11340
Richard Smith7525ff62013-05-09 07:14:00 +000011341 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
11342 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000011343 EStatus.HasSideEffects)
11344 return false;
11345
11346 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
11347 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000011348}
11349
Richard Smith7b553f12011-10-29 00:50:52 +000011350/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
11351/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000011352bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000011353 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000011354 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000011355 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000011356}
Anders Carlsson59689ed2008-11-22 21:04:56 +000011357
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000011358APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011359 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Fangrui Song407659a2018-11-30 23:41:18 +000011360 EvalResult EVResult;
11361 EVResult.Diag = Diag;
11362 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
11363 Info.InConstantContext = true;
11364
11365 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000011366 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000011367 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000011368 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000011369
Fangrui Song407659a2018-11-30 23:41:18 +000011370 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000011371}
John McCall864e3962010-05-07 05:32:02 +000011372
David Bolvansky3b6ae572018-10-18 20:49:06 +000011373APSInt Expr::EvaluateKnownConstIntCheckOverflow(
11374 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Fangrui Song407659a2018-11-30 23:41:18 +000011375 EvalResult EVResult;
11376 EVResult.Diag = Diag;
11377 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11378 Info.InConstantContext = true;
11379
11380 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000011381 (void)Result;
11382 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000011383 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000011384
Fangrui Song407659a2018-11-30 23:41:18 +000011385 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000011386}
11387
Richard Smithe9ff7702013-11-05 22:23:30 +000011388void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011389 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000011390 EvalResult EVResult;
11391 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
11392 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11393 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011394 }
11395}
11396
Richard Smithe6c01442013-06-05 00:46:14 +000011397bool Expr::EvalResult::isGlobalLValue() const {
11398 assert(Val.isLValue());
11399 return IsGlobalLValue(Val.getLValueBase());
11400}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000011401
11402
John McCall864e3962010-05-07 05:32:02 +000011403/// isIntegerConstantExpr - this recursive routine will test if an expression is
11404/// an integer constant expression.
11405
11406/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
11407/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000011408
11409// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000011410// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
11411// and a (possibly null) SourceLocation indicating the location of the problem.
11412//
John McCall864e3962010-05-07 05:32:02 +000011413// Note that to reduce code duplication, this helper does no evaluation
11414// itself; the caller checks whether the expression is evaluatable, and
11415// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000011416// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000011417
Dan Gohman28ade552010-07-26 21:25:24 +000011418namespace {
11419
Richard Smith9e575da2012-12-28 13:25:52 +000011420enum ICEKind {
11421 /// This expression is an ICE.
11422 IK_ICE,
11423 /// This expression is not an ICE, but if it isn't evaluated, it's
11424 /// a legal subexpression for an ICE. This return value is used to handle
11425 /// the comma operator in C99 mode, and non-constant subexpressions.
11426 IK_ICEIfUnevaluated,
11427 /// This expression is not an ICE, and is not a legal subexpression for one.
11428 IK_NotICE
11429};
11430
John McCall864e3962010-05-07 05:32:02 +000011431struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000011432 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000011433 SourceLocation Loc;
11434
Richard Smith9e575da2012-12-28 13:25:52 +000011435 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000011436};
11437
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011438}
Dan Gohman28ade552010-07-26 21:25:24 +000011439
Richard Smith9e575da2012-12-28 13:25:52 +000011440static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
11441
11442static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000011443
Craig Toppera31a8822013-08-22 07:09:37 +000011444static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000011445 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000011446 Expr::EvalStatus Status;
11447 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11448
11449 Info.InConstantContext = true;
11450 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000011451 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011452 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000011453
John McCall864e3962010-05-07 05:32:02 +000011454 return NoDiag();
11455}
11456
Craig Toppera31a8822013-08-22 07:09:37 +000011457static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000011458 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000011459 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011460 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011461
11462 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000011463#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000011464#define STMT(Node, Base) case Expr::Node##Class:
11465#define EXPR(Node, Base)
11466#include "clang/AST/StmtNodes.inc"
11467 case Expr::PredefinedExprClass:
11468 case Expr::FloatingLiteralClass:
11469 case Expr::ImaginaryLiteralClass:
11470 case Expr::StringLiteralClass:
11471 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011472 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000011473 case Expr::MemberExprClass:
11474 case Expr::CompoundAssignOperatorClass:
11475 case Expr::CompoundLiteralExprClass:
11476 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000011477 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000011478 case Expr::ArrayInitLoopExprClass:
11479 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000011480 case Expr::NoInitExprClass:
11481 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000011482 case Expr::ImplicitValueInitExprClass:
11483 case Expr::ParenListExprClass:
11484 case Expr::VAArgExprClass:
11485 case Expr::AddrLabelExprClass:
11486 case Expr::StmtExprClass:
11487 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000011488 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000011489 case Expr::CXXDynamicCastExprClass:
11490 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000011491 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000011492 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000011493 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011494 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000011495 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011496 case Expr::CXXThisExprClass:
11497 case Expr::CXXThrowExprClass:
11498 case Expr::CXXNewExprClass:
11499 case Expr::CXXDeleteExprClass:
11500 case Expr::CXXPseudoDestructorExprClass:
11501 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000011502 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000011503 case Expr::DependentScopeDeclRefExprClass:
11504 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000011505 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000011506 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000011507 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000011508 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000011509 case Expr::CXXTemporaryObjectExprClass:
11510 case Expr::CXXUnresolvedConstructExprClass:
11511 case Expr::CXXDependentScopeMemberExprClass:
11512 case Expr::UnresolvedMemberExprClass:
11513 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000011514 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011515 case Expr::ObjCArrayLiteralClass:
11516 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011517 case Expr::ObjCEncodeExprClass:
11518 case Expr::ObjCMessageExprClass:
11519 case Expr::ObjCSelectorExprClass:
11520 case Expr::ObjCProtocolExprClass:
11521 case Expr::ObjCIvarRefExprClass:
11522 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011523 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000011524 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000011525 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000011526 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000011527 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000011528 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000011529 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000011530 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000011531 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000011532 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000011533 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000011534 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000011535 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000011536 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000011537 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000011538 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000011539 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000011540 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011541 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000011542 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011543 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011544 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000011545
Richard Smithf137f932014-01-25 20:50:08 +000011546 case Expr::InitListExprClass: {
11547 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
11548 // form "T x = { a };" is equivalent to "T x = a;".
11549 // Unless we're initializing a reference, T is a scalar as it is known to be
11550 // of integral or enumeration type.
11551 if (E->isRValue())
11552 if (cast<InitListExpr>(E)->getNumInits() == 1)
11553 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011554 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000011555 }
11556
Douglas Gregor820ba7b2011-01-04 17:33:58 +000011557 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000011558 case Expr::GNUNullExprClass:
11559 // GCC considers the GNU __null value to be an integral constant expression.
11560 return NoDiag();
11561
John McCall7c454bb2011-07-15 05:09:51 +000011562 case Expr::SubstNonTypeTemplateParmExprClass:
11563 return
11564 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
11565
Bill Wendling7c44da22018-10-31 03:48:47 +000011566 case Expr::ConstantExprClass:
11567 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
11568
John McCall864e3962010-05-07 05:32:02 +000011569 case Expr::ParenExprClass:
11570 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000011571 case Expr::GenericSelectionExprClass:
11572 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011573 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000011574 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011575 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011576 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000011577 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000011578 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000011579 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000011580 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000011581 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000011582 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011583 return NoDiag();
11584 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000011585 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000011586 // C99 6.6/3 allows function calls within unevaluated subexpressions of
11587 // constant expressions, but they can never be ICEs because an ICE cannot
11588 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000011589 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000011590 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000011591 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011592 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011593 }
Richard Smith6365c912012-02-24 22:12:32 +000011594 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011595 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
11596 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000011597 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011598 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000011599 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000011600 // Parameter variables are never constants. Without this check,
11601 // getAnyInitializer() can find a default argument, which leads
11602 // to chaos.
11603 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000011604 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011605
11606 // C++ 7.1.5.1p2
11607 // A variable of non-volatile const-qualified integral or enumeration
11608 // type initialized by an ICE can be used in ICEs.
11609 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000011610 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000011611 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000011612
Richard Smithd0b4dd62011-12-19 06:19:21 +000011613 const VarDecl *VD;
11614 // Look for a declaration of this variable that has an initializer, and
11615 // check whether it is an ICE.
11616 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
11617 return NoDiag();
11618 else
Richard Smith9e575da2012-12-28 13:25:52 +000011619 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011620 }
11621 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011622 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000011623 }
John McCall864e3962010-05-07 05:32:02 +000011624 case Expr::UnaryOperatorClass: {
11625 const UnaryOperator *Exp = cast<UnaryOperator>(E);
11626 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011627 case UO_PostInc:
11628 case UO_PostDec:
11629 case UO_PreInc:
11630 case UO_PreDec:
11631 case UO_AddrOf:
11632 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000011633 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000011634 // C99 6.6/3 allows increment and decrement within unevaluated
11635 // subexpressions of constant expressions, but they can never be ICEs
11636 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011637 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000011638 case UO_Extension:
11639 case UO_LNot:
11640 case UO_Plus:
11641 case UO_Minus:
11642 case UO_Not:
11643 case UO_Real:
11644 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000011645 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011646 }
Reid Klecknere540d972018-11-01 17:51:48 +000011647 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000011648 }
11649 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000011650 // Note that per C99, offsetof must be an ICE. And AFAIK, using
11651 // EvaluateAsRValue matches the proposed gcc behavior for cases like
11652 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
11653 // compliance: we should warn earlier for offsetof expressions with
11654 // array subscripts that aren't ICEs, and if the array subscripts
11655 // are ICEs, the value of the offsetof must be an integer constant.
11656 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011657 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000011658 case Expr::UnaryExprOrTypeTraitExprClass: {
11659 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
11660 if ((Exp->getKind() == UETT_SizeOf) &&
11661 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011662 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011663 return NoDiag();
11664 }
11665 case Expr::BinaryOperatorClass: {
11666 const BinaryOperator *Exp = cast<BinaryOperator>(E);
11667 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011668 case BO_PtrMemD:
11669 case BO_PtrMemI:
11670 case BO_Assign:
11671 case BO_MulAssign:
11672 case BO_DivAssign:
11673 case BO_RemAssign:
11674 case BO_AddAssign:
11675 case BO_SubAssign:
11676 case BO_ShlAssign:
11677 case BO_ShrAssign:
11678 case BO_AndAssign:
11679 case BO_XorAssign:
11680 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000011681 // C99 6.6/3 allows assignments within unevaluated subexpressions of
11682 // constant expressions, but they can never be ICEs because an ICE cannot
11683 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011684 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011685
John McCalle3027922010-08-25 11:45:40 +000011686 case BO_Mul:
11687 case BO_Div:
11688 case BO_Rem:
11689 case BO_Add:
11690 case BO_Sub:
11691 case BO_Shl:
11692 case BO_Shr:
11693 case BO_LT:
11694 case BO_GT:
11695 case BO_LE:
11696 case BO_GE:
11697 case BO_EQ:
11698 case BO_NE:
11699 case BO_And:
11700 case BO_Xor:
11701 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011702 case BO_Comma:
11703 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000011704 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11705 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000011706 if (Exp->getOpcode() == BO_Div ||
11707 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000011708 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000011709 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000011710 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000011711 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011712 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011713 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011714 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000011715 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011716 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011717 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011718 }
11719 }
11720 }
John McCalle3027922010-08-25 11:45:40 +000011721 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011722 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000011723 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
11724 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000011725 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011726 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011727 } else {
11728 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011729 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011730 }
11731 }
Richard Smith9e575da2012-12-28 13:25:52 +000011732 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011733 }
John McCalle3027922010-08-25 11:45:40 +000011734 case BO_LAnd:
11735 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000011736 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11737 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011738 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000011739 // Rare case where the RHS has a comma "side-effect"; we need
11740 // to actually check the condition to see whether the side
11741 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000011742 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000011743 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000011744 return RHSResult;
11745 return NoDiag();
11746 }
11747
Richard Smith9e575da2012-12-28 13:25:52 +000011748 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011749 }
11750 }
Reid Klecknere540d972018-11-01 17:51:48 +000011751 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000011752 }
11753 case Expr::ImplicitCastExprClass:
11754 case Expr::CStyleCastExprClass:
11755 case Expr::CXXFunctionalCastExprClass:
11756 case Expr::CXXStaticCastExprClass:
11757 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000011758 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000011759 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011760 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000011761 if (isa<ExplicitCastExpr>(E)) {
11762 if (const FloatingLiteral *FL
11763 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
11764 unsigned DestWidth = Ctx.getIntWidth(E->getType());
11765 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
11766 APSInt IgnoredVal(DestWidth, !DestSigned);
11767 bool Ignored;
11768 // If the value does not fit in the destination type, the behavior is
11769 // undefined, so we are not required to treat it as a constant
11770 // expression.
11771 if (FL->getValue().convertToInteger(IgnoredVal,
11772 llvm::APFloat::rmTowardZero,
11773 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011774 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000011775 return NoDiag();
11776 }
11777 }
Eli Friedman76d4e432011-09-29 21:49:34 +000011778 switch (cast<CastExpr>(E)->getCastKind()) {
11779 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011780 case CK_AtomicToNonAtomic:
11781 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000011782 case CK_NoOp:
11783 case CK_IntegralToBoolean:
11784 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000011785 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000011786 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011787 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000011788 }
John McCall864e3962010-05-07 05:32:02 +000011789 }
John McCallc07a0c72011-02-17 10:25:35 +000011790 case Expr::BinaryConditionalOperatorClass: {
11791 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
11792 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011793 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000011794 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011795 if (FalseResult.Kind == IK_NotICE) return FalseResult;
11796 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
11797 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000011798 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000011799 return FalseResult;
11800 }
John McCall864e3962010-05-07 05:32:02 +000011801 case Expr::ConditionalOperatorClass: {
11802 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
11803 // If the condition (ignoring parens) is a __builtin_constant_p call,
11804 // then only the true side is actually considered in an integer constant
11805 // expression, and it is fully evaluated. This is an important GNU
11806 // extension. See GCC PR38377 for discussion.
11807 if (const CallExpr *CallCE
11808 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000011809 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000011810 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011811 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011812 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011813 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011814
Richard Smithf57d8cb2011-12-09 22:58:01 +000011815 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
11816 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011817
Richard Smith9e575da2012-12-28 13:25:52 +000011818 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011819 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011820 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011821 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011822 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000011823 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011824 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000011825 return NoDiag();
11826 // Rare case where the diagnostics depend on which side is evaluated
11827 // Note that if we get here, CondResult is 0, and at least one of
11828 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000011829 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000011830 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000011831 return TrueResult;
11832 }
11833 case Expr::CXXDefaultArgExprClass:
11834 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000011835 case Expr::CXXDefaultInitExprClass:
11836 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011837 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000011838 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011839 }
11840 }
11841
David Blaikiee4d798f2012-01-20 21:50:17 +000011842 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000011843}
11844
Richard Smithf57d8cb2011-12-09 22:58:01 +000011845/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000011846static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011847 const Expr *E,
11848 llvm::APSInt *Value,
11849 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000011850 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011851 if (Loc) *Loc = E->getExprLoc();
11852 return false;
11853 }
11854
Richard Smith66e05fe2012-01-18 05:21:49 +000011855 APValue Result;
11856 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000011857 return false;
11858
Richard Smith98710fc2014-11-13 23:03:19 +000011859 if (!Result.isInt()) {
11860 if (Loc) *Loc = E->getExprLoc();
11861 return false;
11862 }
11863
Richard Smith66e05fe2012-01-18 05:21:49 +000011864 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000011865 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011866}
11867
Craig Toppera31a8822013-08-22 07:09:37 +000011868bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
11869 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011870 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000011871 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011872
Richard Smith9e575da2012-12-28 13:25:52 +000011873 ICEDiag D = CheckICE(this, Ctx);
11874 if (D.Kind != IK_ICE) {
11875 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000011876 return false;
11877 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011878 return true;
11879}
11880
Craig Toppera31a8822013-08-22 07:09:37 +000011881bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011882 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011883 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011884 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
11885
11886 if (!isIntegerConstantExpr(Ctx, Loc))
11887 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000011888
Richard Smith5c40f092015-12-04 03:00:44 +000011889 // The only possible side-effects here are due to UB discovered in the
11890 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
11891 // required to treat the expression as an ICE, so we produce the folded
11892 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000011893 EvalResult ExprResult;
11894 Expr::EvalStatus Status;
11895 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
11896 Info.InConstantContext = true;
11897
11898 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000011899 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000011900
11901 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000011902 return true;
11903}
Richard Smith66e05fe2012-01-18 05:21:49 +000011904
Craig Toppera31a8822013-08-22 07:09:37 +000011905bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000011906 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000011907}
11908
Craig Toppera31a8822013-08-22 07:09:37 +000011909bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000011910 SourceLocation *Loc) const {
11911 // We support this checking in C++98 mode in order to diagnose compatibility
11912 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011913 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000011914
Richard Smith98a0a492012-02-14 21:38:30 +000011915 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000011916 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011917 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000011918 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000011919 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000011920
11921 APValue Scratch;
11922 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
11923
11924 if (!Diags.empty()) {
11925 IsConstExpr = false;
11926 if (Loc) *Loc = Diags[0].first;
11927 } else if (!IsConstExpr) {
11928 // FIXME: This shouldn't happen.
11929 if (Loc) *Loc = getExprLoc();
11930 }
11931
11932 return IsConstExpr;
11933}
Richard Smith253c2a32012-01-27 01:14:48 +000011934
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011935bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
11936 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000011937 ArrayRef<const Expr*> Args,
11938 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011939 Expr::EvalStatus Status;
11940 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000011941 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011942
George Burgess IV177399e2017-01-09 04:12:14 +000011943 LValue ThisVal;
11944 const LValue *ThisPtr = nullptr;
11945 if (This) {
11946#ifndef NDEBUG
11947 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11948 assert(MD && "Don't provide `this` for non-methods.");
11949 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11950#endif
11951 if (EvaluateObjectArgument(Info, This, ThisVal))
11952 ThisPtr = &ThisVal;
11953 if (Info.EvalStatus.HasSideEffects)
11954 return false;
11955 }
11956
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011957 ArgVector ArgValues(Args.size());
11958 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11959 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000011960 if ((*I)->isValueDependent() ||
11961 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011962 // If evaluation fails, throw away the argument entirely.
11963 ArgValues[I - Args.begin()] = APValue();
11964 if (Info.EvalStatus.HasSideEffects)
11965 return false;
11966 }
11967
11968 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000011969 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011970 ArgValues.data());
11971 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11972}
11973
Richard Smith253c2a32012-01-27 01:14:48 +000011974bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011975 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000011976 PartialDiagnosticAt> &Diags) {
11977 // FIXME: It would be useful to check constexpr function templates, but at the
11978 // moment the constant expression evaluator cannot cope with the non-rigorous
11979 // ASTs which we build for dependent expressions.
11980 if (FD->isDependentContext())
11981 return true;
11982
11983 Expr::EvalStatus Status;
11984 Status.Diag = &Diags;
11985
Richard Smith6d4c6582013-11-05 22:18:15 +000011986 EvalInfo Info(FD->getASTContext(), Status,
11987 EvalInfo::EM_PotentialConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000011988 Info.InConstantContext = true;
Richard Smith253c2a32012-01-27 01:14:48 +000011989
11990 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000011991 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000011992
Richard Smith7525ff62013-05-09 07:14:00 +000011993 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000011994 // is a temporary being used as the 'this' pointer.
11995 LValue This;
11996 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011997 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000011998
Richard Smith253c2a32012-01-27 01:14:48 +000011999 ArrayRef<const Expr*> Args;
12000
Richard Smith2e312c82012-03-03 22:46:17 +000012001 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000012002 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
12003 // Evaluate the call as a constant initializer, to allow the construction
12004 // of objects of non-literal types.
12005 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000012006 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
12007 } else {
12008 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000012009 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000012010 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000012011 }
Richard Smith253c2a32012-01-27 01:14:48 +000012012
12013 return Diags.empty();
12014}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012015
12016bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
12017 const FunctionDecl *FD,
12018 SmallVectorImpl<
12019 PartialDiagnosticAt> &Diags) {
12020 Expr::EvalStatus Status;
12021 Status.Diag = &Diags;
12022
12023 EvalInfo Info(FD->getASTContext(), Status,
12024 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000012025 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012026
12027 // Fabricate a call stack frame to give the arguments a plausible cover story.
12028 ArrayRef<const Expr*> Args;
12029 ArgVector ArgValues(0);
12030 bool Success = EvaluateArgs(Args, ArgValues, Info);
12031 (void)Success;
12032 assert(Success &&
12033 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000012034 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000012035
12036 APValue ResultScratch;
12037 Evaluate(ResultScratch, Info, E);
12038 return Diags.empty();
12039}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012040
12041bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
12042 unsigned Type) const {
12043 if (!getType()->isPointerType())
12044 return false;
12045
12046 Expr::EvalStatus Status;
12047 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000012048 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012049}