blob: a85d5cf9d5f389d8054f01697738bcd17ebd222f [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000039#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000040#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000041#include "clang/AST/Expr.h"
Tim Northover314fbfa2018-11-02 13:14:11 +000042#include "clang/AST/OSLog.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000043#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000044#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000045#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000046#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000047#include "clang/Basic/TargetInfo.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000048#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000049#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000050#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000051
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000052#define DEBUG_TYPE "exprconstant"
53
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000055using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000056using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000057
Richard Smithb228a862012-02-15 02:18:13 +000058static bool IsGlobalLValue(APValue::LValueBase B);
59
John McCall93d91dc2010-05-07 17:22:02 +000060namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000061 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000062 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000063 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000064
Richard Smithb228a862012-02-15 02:18:13 +000065 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000066 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000067 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000068 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000069 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000070 //
71 // extern int arr[]; void f() { extern int arr[3]; };
72 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000073 //
74 // For now, we take the array bound from the most recent declaration.
75 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
76 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
77 QualType T = Redecl->getType();
78 if (!T->isIncompleteArrayType())
79 return T;
80 }
81 return D->getType();
82 }
Richard Smith84401042013-06-03 05:03:02 +000083
84 const Expr *Base = B.get<const Expr*>();
85
86 // For a materialized temporary, the type of the temporary we materialized
87 // may not be the type of the expression.
88 if (const MaterializeTemporaryExpr *MTE =
89 dyn_cast<MaterializeTemporaryExpr>(Base)) {
90 SmallVector<const Expr *, 2> CommaLHSs;
91 SmallVector<SubobjectAdjustment, 2> Adjustments;
92 const Expr *Temp = MTE->GetTemporaryExpr();
93 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
94 Adjustments);
95 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000096 // for it directly. Otherwise use the type after adjustment.
97 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000098 return Inner->getType();
99 }
100
101 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000102 }
103
Richard Smithd62306a2011-11-10 06:34:14 +0000104 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000105 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +0000106 static
Richard Smith84f6dcf2012-02-02 01:16:57 +0000107 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +0000108 APValue::BaseOrMemberType Value;
109 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +0000110 return Value;
111 }
112
113 /// Get an LValue path entry, which is known to not be an array index, as a
114 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000115 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000116 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000117 }
118 /// Get an LValue path entry, which is known to not be an array index, as a
119 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000120 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000121 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000122 }
123 /// Determine whether this LValue path entry for a base class names a virtual
124 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000125 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000126 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000127 }
128
George Burgess IVe3763372016-12-22 02:50:20 +0000129 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
130 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
131 const FunctionDecl *Callee = CE->getDirectCallee();
132 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
133 }
134
135 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
136 /// This will look through a single cast.
137 ///
138 /// Returns null if we couldn't unwrap a function with alloc_size.
139 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
140 if (!E->getType()->isPointerType())
141 return nullptr;
142
143 E = E->IgnoreParens();
144 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000145 // probably be a cast of some kind. In exotic cases, we might also see a
146 // top-level ExprWithCleanups. Ignore them either way.
Bill Wendling7c44da22018-10-31 03:48:47 +0000147 if (const auto *FE = dyn_cast<FullExpr>(E))
148 E = FE->getSubExpr()->IgnoreParens();
George Burgess IV47638762018-03-07 04:52:34 +0000149
George Burgess IVe3763372016-12-22 02:50:20 +0000150 if (const auto *Cast = dyn_cast<CastExpr>(E))
151 E = Cast->getSubExpr()->IgnoreParens();
152
153 if (const auto *CE = dyn_cast<CallExpr>(E))
154 return getAllocSizeAttr(CE) ? CE : nullptr;
155 return nullptr;
156 }
157
158 /// Determines whether or not the given Base contains a call to a function
159 /// with the alloc_size attribute.
160 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
161 const auto *E = Base.dyn_cast<const Expr *>();
162 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
163 }
164
Richard Smith6f4f0f12017-10-20 22:56:25 +0000165 /// The bound to claim that an array of unknown bound has.
166 /// The value in MostDerivedArraySize is undefined in this case. So, set it
167 /// to an arbitrary value that's likely to loudly break things if it's used.
168 static const uint64_t AssumedSizeForUnsizedArray =
169 std::numeric_limits<uint64_t>::max() / 2;
170
George Burgess IVe3763372016-12-22 02:50:20 +0000171 /// Determines if an LValue with the given LValueBase will have an unsized
172 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000173 /// Find the path length and type of the most-derived subobject in the given
174 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000175 static unsigned
176 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
177 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000178 uint64_t &ArraySize, QualType &Type, bool &IsArray,
179 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000180 // This only accepts LValueBases from APValues, and APValues don't support
181 // arrays that lack size info.
182 assert(!isBaseAnAllocSizeCall(Base) &&
183 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000184 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000185 Type = getType(Base);
186
Richard Smith80815602011-11-07 05:07:52 +0000187 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000188 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000189 const ArrayType *AT = Ctx.getAsArrayType(Type);
190 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000191 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000192 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000193
194 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
195 ArraySize = CAT->getSize().getZExtValue();
196 } else {
197 assert(I == 0 && "unexpected unsized array designator");
198 FirstEntryIsUnsizedArray = true;
199 ArraySize = AssumedSizeForUnsizedArray;
200 }
Richard Smith66c96992012-02-18 22:04:06 +0000201 } else if (Type->isAnyComplexType()) {
202 const ComplexType *CT = Type->castAs<ComplexType>();
203 Type = CT->getElementType();
204 ArraySize = 2;
205 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000206 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000207 } else if (const FieldDecl *FD = getAsField(Path[I])) {
208 Type = FD->getType();
209 ArraySize = 0;
210 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000211 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000212 } else {
Richard Smith80815602011-11-07 05:07:52 +0000213 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000214 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000215 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000216 }
Richard Smith80815602011-11-07 05:07:52 +0000217 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000218 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000219 }
220
Richard Smitha8105bc2012-01-06 16:39:00 +0000221 // The order of this enum is important for diagnostics.
222 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000223 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000224 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000225 };
226
Richard Smith96e0c102011-11-04 02:25:55 +0000227 /// A path from a glvalue to a subobject of that glvalue.
228 struct SubobjectDesignator {
229 /// True if the subobject was named in a manner not supported by C++11. Such
230 /// lvalues can still be folded, but they are not core constant expressions
231 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000232 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000233
Richard Smitha8105bc2012-01-06 16:39:00 +0000234 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000235 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000236
Daniel Jasperffdee092017-05-02 19:21:42 +0000237 /// Indicator of whether the first entry is an unsized array.
238 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000239
George Burgess IVa51c4072015-10-16 01:49:01 +0000240 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000241 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000242
Richard Smitha8105bc2012-01-06 16:39:00 +0000243 /// The length of the path to the most-derived object of which this is a
244 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000245 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000246
George Burgess IVa51c4072015-10-16 01:49:01 +0000247 /// The size of the array of which the most-derived object is an element.
248 /// This will always be 0 if the most-derived object is not an array
249 /// element. 0 is not an indicator of whether or not the most-derived object
250 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000251 ///
252 /// If the current array is an unsized array, the value of this is
253 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000254 uint64_t MostDerivedArraySize;
255
256 /// The type of the most derived object referred to by this address.
257 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000258
Richard Smith80815602011-11-07 05:07:52 +0000259 typedef APValue::LValuePathEntry PathEntry;
260
Richard Smith96e0c102011-11-04 02:25:55 +0000261 /// The entries on the path from the glvalue to the designated subobject.
262 SmallVector<PathEntry, 8> Entries;
263
Richard Smitha8105bc2012-01-06 16:39:00 +0000264 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000265
Richard Smitha8105bc2012-01-06 16:39:00 +0000266 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000267 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000268 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000269 MostDerivedPathLength(0), MostDerivedArraySize(0),
270 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000271
272 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000273 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000274 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000275 MostDerivedPathLength(0), MostDerivedArraySize(0) {
276 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000277 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000278 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000279 ArrayRef<PathEntry> VEntries = V.getLValuePath();
280 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000281 if (V.getLValueBase()) {
282 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000283 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000284 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000285 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000286 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000287 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000288 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000289 }
Richard Smith80815602011-11-07 05:07:52 +0000290 }
291 }
292
Richard Smith96e0c102011-11-04 02:25:55 +0000293 void setInvalid() {
294 Invalid = true;
295 Entries.clear();
296 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000297
George Burgess IVe3763372016-12-22 02:50:20 +0000298 /// Determine whether the most derived subobject is an array without a
299 /// known bound.
300 bool isMostDerivedAnUnsizedArray() const {
301 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000302 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000303 }
304
305 /// Determine what the most derived array's size is. Results in an assertion
306 /// failure if the most derived array lacks a size.
307 uint64_t getMostDerivedArraySize() const {
308 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
309 return MostDerivedArraySize;
310 }
311
Richard Smitha8105bc2012-01-06 16:39:00 +0000312 /// Determine whether this is a one-past-the-end pointer.
313 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000314 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000315 if (IsOnePastTheEnd)
316 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000317 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000318 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
319 return true;
320 return false;
321 }
322
Richard Smith06f71b52018-08-04 00:57:17 +0000323 /// Get the range of valid index adjustments in the form
324 /// {maximum value that can be subtracted from this pointer,
325 /// maximum value that can be added to this pointer}
326 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
327 if (Invalid || isMostDerivedAnUnsizedArray())
328 return {0, 0};
329
330 // [expr.add]p4: For the purposes of these operators, a pointer to a
331 // nonarray object behaves the same as a pointer to the first element of
332 // an array of length one with the type of the object as its element type.
333 bool IsArray = MostDerivedPathLength == Entries.size() &&
334 MostDerivedIsArrayElement;
335 uint64_t ArrayIndex =
336 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
337 uint64_t ArraySize =
338 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
339 return {ArrayIndex, ArraySize - ArrayIndex};
340 }
341
Richard Smitha8105bc2012-01-06 16:39:00 +0000342 /// Check that this refers to a valid subobject.
343 bool isValidSubobject() const {
344 if (Invalid)
345 return false;
346 return !isOnePastTheEnd();
347 }
348 /// Check that this refers to a valid subobject, and if not, produce a
349 /// relevant diagnostic and set the designator as invalid.
350 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
351
Richard Smith06f71b52018-08-04 00:57:17 +0000352 /// Get the type of the designated object.
353 QualType getType(ASTContext &Ctx) const {
354 assert(!Invalid && "invalid designator has no subobject type");
355 return MostDerivedPathLength == Entries.size()
356 ? MostDerivedType
357 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
358 }
359
Richard Smitha8105bc2012-01-06 16:39:00 +0000360 /// Update this designator to refer to the first element within this array.
361 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000362 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000363 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000364 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000365
366 // This is a most-derived object.
367 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000368 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000369 MostDerivedArraySize = CAT->getSize().getZExtValue();
370 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000371 }
George Burgess IVe3763372016-12-22 02:50:20 +0000372 /// Update this designator to refer to the first element within the array of
373 /// elements of type T. This is an array of unknown size.
374 void addUnsizedArrayUnchecked(QualType ElemTy) {
375 PathEntry Entry;
376 Entry.ArrayIndex = 0;
377 Entries.push_back(Entry);
378
379 MostDerivedType = ElemTy;
380 MostDerivedIsArrayElement = true;
381 // The value in MostDerivedArraySize is undefined in this case. So, set it
382 // to an arbitrary value that's likely to loudly break things if it's
383 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000384 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000385 MostDerivedPathLength = Entries.size();
386 }
Richard Smith96e0c102011-11-04 02:25:55 +0000387 /// Update this designator to refer to the given base or member of this
388 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000389 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000390 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000391 APValue::BaseOrMemberType Value(D, Virtual);
392 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000393 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000394
395 // If this isn't a base class, it's a new most-derived object.
396 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
397 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000398 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000399 MostDerivedArraySize = 0;
400 MostDerivedPathLength = Entries.size();
401 }
Richard Smith96e0c102011-11-04 02:25:55 +0000402 }
Richard Smith66c96992012-02-18 22:04:06 +0000403 /// Update this designator to refer to the given complex component.
404 void addComplexUnchecked(QualType EltTy, bool Imag) {
405 PathEntry Entry;
406 Entry.ArrayIndex = Imag;
407 Entries.push_back(Entry);
408
409 // This is technically a most-derived object, though in practice this
410 // is unlikely to matter.
411 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000412 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000413 MostDerivedArraySize = 2;
414 MostDerivedPathLength = Entries.size();
415 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000416 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000417 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
418 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000419 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000420 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
421 if (Invalid || !N) return;
422 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
423 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000424 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000425 // Can't verify -- trust that the user is doing the right thing (or if
426 // not, trust that the caller will catch the bad behavior).
427 // FIXME: Should we reject if this overflows, at least?
428 Entries.back().ArrayIndex += TruncatedN;
429 return;
430 }
431
432 // [expr.add]p4: For the purposes of these operators, a pointer to a
433 // nonarray object behaves the same as a pointer to the first element of
434 // an array of length one with the type of the object as its element type.
435 bool IsArray = MostDerivedPathLength == Entries.size() &&
436 MostDerivedIsArrayElement;
437 uint64_t ArrayIndex =
438 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
439 uint64_t ArraySize =
440 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
441
442 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
443 // Calculate the actual index in a wide enough type, so we can include
444 // it in the note.
445 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
446 (llvm::APInt&)N += ArrayIndex;
447 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
448 diagnosePointerArithmetic(Info, E, N);
449 setInvalid();
450 return;
451 }
452
453 ArrayIndex += TruncatedN;
454 assert(ArrayIndex <= ArraySize &&
455 "bounds check succeeded for out-of-bounds index");
456
457 if (IsArray)
458 Entries.back().ArrayIndex = ArrayIndex;
459 else
460 IsOnePastTheEnd = (ArrayIndex != 0);
461 }
Richard Smith96e0c102011-11-04 02:25:55 +0000462 };
463
Richard Smith254a73d2011-10-28 22:34:42 +0000464 /// A stack frame in the constexpr call stack.
465 struct CallStackFrame {
466 EvalInfo &Info;
467
468 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000469 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000470
Richard Smithf6f003a2011-12-16 19:06:07 +0000471 /// Callee - The function which was called.
472 const FunctionDecl *Callee;
473
Richard Smithd62306a2011-11-10 06:34:14 +0000474 /// This - The binding for the this pointer in this call, if any.
475 const LValue *This;
476
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000477 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000478 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000479 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000480
Eli Friedman4830ec82012-06-25 21:21:08 +0000481 // Note that we intentionally use std::map here so that references to
482 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000483 typedef std::pair<const void *, unsigned> MapKeyTy;
484 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000485 /// Temporaries - Temporary lvalues materialized within this stack frame.
486 MapTy Temporaries;
487
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000488 /// CallLoc - The location of the call expression for this call.
489 SourceLocation CallLoc;
490
491 /// Index - The call index of this call.
492 unsigned Index;
493
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000494 /// The stack of integers for tracking version numbers for temporaries.
495 SmallVector<unsigned, 2> TempVersionStack = {1};
496 unsigned CurTempVersion = TempVersionStack.back();
497
498 unsigned getTempVersion() const { return TempVersionStack.back(); }
499
500 void pushTempVersion() {
501 TempVersionStack.push_back(++CurTempVersion);
502 }
503
504 void popTempVersion() {
505 TempVersionStack.pop_back();
506 }
507
Faisal Vali051e3a22017-02-16 04:12:21 +0000508 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
509 // on the overall stack usage of deeply-recursing constexpr evaluataions.
510 // (We should cache this map rather than recomputing it repeatedly.)
511 // But let's try this and see how it goes; we can look into caching the map
512 // as a later change.
513
514 /// LambdaCaptureFields - Mapping from captured variables/this to
515 /// corresponding data members in the closure class.
516 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
517 FieldDecl *LambdaThisCaptureField;
518
Richard Smithf6f003a2011-12-16 19:06:07 +0000519 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
520 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000521 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000522 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000523
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000524 // Return the temporary for Key whose version number is Version.
525 APValue *getTemporary(const void *Key, unsigned Version) {
526 MapKeyTy KV(Key, Version);
527 auto LB = Temporaries.lower_bound(KV);
528 if (LB != Temporaries.end() && LB->first == KV)
529 return &LB->second;
530 // Pair (Key,Version) wasn't found in the map. Check that no elements
531 // in the map have 'Key' as their key.
532 assert((LB == Temporaries.end() || LB->first.first != Key) &&
533 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
534 "Element with key 'Key' found in map");
535 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000536 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000537
538 // Return the current temporary for Key in the map.
539 APValue *getCurrentTemporary(const void *Key) {
540 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
541 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
542 return &std::prev(UB)->second;
543 return nullptr;
544 }
545
546 // Return the version number of the current temporary for Key.
547 unsigned getCurrentTemporaryVersion(const void *Key) const {
548 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
549 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
550 return std::prev(UB)->first.second;
551 return 0;
552 }
553
Richard Smith08d6a2c2013-07-24 07:11:57 +0000554 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000555 };
556
Richard Smith852c9db2013-04-20 22:23:05 +0000557 /// Temporarily override 'this'.
558 class ThisOverrideRAII {
559 public:
560 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
561 : Frame(Frame), OldThis(Frame.This) {
562 if (Enable)
563 Frame.This = NewThis;
564 }
565 ~ThisOverrideRAII() {
566 Frame.This = OldThis;
567 }
568 private:
569 CallStackFrame &Frame;
570 const LValue *OldThis;
571 };
572
Richard Smith92b1ce02011-12-12 09:28:41 +0000573 /// A partial diagnostic which we might know in advance that we are not going
574 /// to emit.
575 class OptionalDiagnostic {
576 PartialDiagnostic *Diag;
577
578 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000579 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
580 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000581
582 template<typename T>
583 OptionalDiagnostic &operator<<(const T &v) {
584 if (Diag)
585 *Diag << v;
586 return *this;
587 }
Richard Smithfe800032012-01-31 04:08:20 +0000588
589 OptionalDiagnostic &operator<<(const APSInt &I) {
590 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000591 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000592 I.toString(Buffer);
593 *Diag << StringRef(Buffer.data(), Buffer.size());
594 }
595 return *this;
596 }
597
598 OptionalDiagnostic &operator<<(const APFloat &F) {
599 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000600 // FIXME: Force the precision of the source value down so we don't
601 // print digits which are usually useless (we don't really care here if
602 // we truncate a digit by accident in edge cases). Ideally,
Fangrui Song6907ce22018-07-30 19:24:48 +0000603 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000604 // representation which rounds to the correct value, but it's a bit
605 // tricky to implement.
606 unsigned precision =
607 llvm::APFloat::semanticsPrecision(F.getSemantics());
608 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000609 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000610 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000611 *Diag << StringRef(Buffer.data(), Buffer.size());
612 }
613 return *this;
614 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000615 };
616
Richard Smith08d6a2c2013-07-24 07:11:57 +0000617 /// A cleanup, and a flag indicating whether it is lifetime-extended.
618 class Cleanup {
619 llvm::PointerIntPair<APValue*, 1, bool> Value;
620
621 public:
622 Cleanup(APValue *Val, bool IsLifetimeExtended)
623 : Value(Val, IsLifetimeExtended) {}
624
625 bool isLifetimeExtended() const { return Value.getInt(); }
626 void endLifetime() {
627 *Value.getPointer() = APValue();
628 }
629 };
630
Richard Smithb228a862012-02-15 02:18:13 +0000631 /// EvalInfo - This is a private struct used by the evaluator to capture
632 /// information about a subexpression as it is folded. It retains information
633 /// about the AST context, but also maintains information about the folded
634 /// expression.
635 ///
636 /// If an expression could be evaluated, it is still possible it is not a C
637 /// "integer constant expression" or constant expression. If not, this struct
638 /// captures information about how and why not.
639 ///
640 /// One bit of information passed *into* the request for constant folding
641 /// indicates whether the subexpression is "evaluated" or not according to C
642 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
643 /// evaluate the expression regardless of what the RHS is, but C only allows
644 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000645 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000646 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000647
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000648 /// EvalStatus - Contains information about the evaluation.
649 Expr::EvalStatus &EvalStatus;
650
651 /// CurrentCall - The top of the constexpr call stack.
652 CallStackFrame *CurrentCall;
653
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000654 /// CallStackDepth - The number of calls in the call stack right now.
655 unsigned CallStackDepth;
656
Richard Smithb228a862012-02-15 02:18:13 +0000657 /// NextCallIndex - The next call index to assign.
658 unsigned NextCallIndex;
659
Richard Smitha3d3bd22013-05-08 02:12:03 +0000660 /// StepsLeft - The remaining number of evaluation steps we're permitted
661 /// to perform. This is essentially a limit for the number of statements
662 /// we will evaluate.
663 unsigned StepsLeft;
664
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000665 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000666 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000667 CallStackFrame BottomFrame;
668
Richard Smith08d6a2c2013-07-24 07:11:57 +0000669 /// A stack of values whose lifetimes end at the end of some surrounding
670 /// evaluation frame.
671 llvm::SmallVector<Cleanup, 16> CleanupStack;
672
Richard Smithd62306a2011-11-10 06:34:14 +0000673 /// EvaluatingDecl - This is the declaration whose initializer is being
674 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000675 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000676
677 /// EvaluatingDeclValue - This is the value being constructed for the
678 /// declaration whose initializer is being evaluated, if any.
679 APValue *EvaluatingDeclValue;
680
Erik Pilkington42925492017-10-04 00:18:55 +0000681 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
682 /// the call index that that lvalue was allocated in.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000683 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
684 EvaluatingObject;
Erik Pilkington42925492017-10-04 00:18:55 +0000685
686 /// EvaluatingConstructors - Set of objects that are currently being
687 /// constructed.
688 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
689
690 struct EvaluatingConstructorRAII {
691 EvalInfo &EI;
692 EvaluatingObject Object;
693 bool DidInsert;
694 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
695 : EI(EI), Object(Object) {
696 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
697 }
698 ~EvaluatingConstructorRAII() {
699 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
700 }
701 };
702
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000703 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
704 unsigned Version) {
705 return EvaluatingConstructors.count(
706 EvaluatingObject(Decl, {CallIndex, Version}));
Erik Pilkington42925492017-10-04 00:18:55 +0000707 }
708
Richard Smith410306b2016-12-12 02:53:20 +0000709 /// The current array initialization index, if we're performing array
710 /// initialization.
711 uint64_t ArrayInitIndex = -1;
712
Richard Smith357362d2011-12-13 06:39:58 +0000713 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
714 /// notes attached to it will also be stored, otherwise they will not be.
715 bool HasActiveDiagnostic;
716
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000717 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000718 /// fold (not just why it's not strictly a constant expression)?
719 bool HasFoldFailureDiagnostic;
720
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000721 /// Whether or not we're currently speculatively evaluating.
George Burgess IV8c892b52016-05-25 22:31:54 +0000722 bool IsSpeculativelyEvaluating;
723
Richard Smith6d4c6582013-11-05 22:18:15 +0000724 enum EvaluationMode {
725 /// Evaluate as a constant expression. Stop if we find that the expression
726 /// is not a constant expression.
727 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000728
Richard Smith6d4c6582013-11-05 22:18:15 +0000729 /// Evaluate as a potential constant expression. Keep going if we hit a
730 /// construct that we can't evaluate yet (because we don't yet know the
731 /// value of something) but stop if we hit something that could never be
732 /// a constant expression.
733 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000734
Richard Smith6d4c6582013-11-05 22:18:15 +0000735 /// Fold the expression to a constant. Stop if we hit a side-effect that
736 /// we can't model.
737 EM_ConstantFold,
738
739 /// Evaluate the expression looking for integer overflow and similar
740 /// issues. Don't worry about side-effects, and try to visit all
741 /// subexpressions.
742 EM_EvaluateForOverflow,
743
744 /// Evaluate in any way we know how. Don't worry about side-effects that
745 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000746 EM_IgnoreSideEffects,
747
748 /// Evaluate as a constant expression. Stop if we find that the expression
749 /// is not a constant expression. Some expressions can be retried in the
750 /// optimizer if we don't constant fold them here, but in an unevaluated
751 /// context we try to fold them immediately since the optimizer never
752 /// gets a chance to look at it.
753 EM_ConstantExpressionUnevaluated,
754
755 /// Evaluate as a potential constant expression. Keep going if we hit a
756 /// construct that we can't evaluate yet (because we don't yet know the
757 /// value of something) but stop if we hit something that could never be
758 /// a constant expression. Some expressions can be retried in the
759 /// optimizer if we don't constant fold them here, but in an unevaluated
760 /// context we try to fold them immediately since the optimizer never
761 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000762 EM_PotentialConstantExpressionUnevaluated,
Richard Smith6d4c6582013-11-05 22:18:15 +0000763 } EvalMode;
764
765 /// Are we checking whether the expression is a potential constant
766 /// expression?
767 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000768 return EvalMode == EM_PotentialConstantExpression ||
769 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000770 }
771
772 /// Are we checking an expression for overflow?
773 // FIXME: We should check for any kind of undefined or suspicious behavior
774 // in such constructs, not just overflow.
775 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
776
777 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000778 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000779 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000780 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000781 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
782 EvaluatingDecl((const ValueDecl *)nullptr),
783 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000784 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
785 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000786
Richard Smith7525ff62013-05-09 07:14:00 +0000787 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
788 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000789 EvaluatingDeclValue = &Value;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000790 EvaluatingConstructors.insert({Base, {0, 0}});
Richard Smithd62306a2011-11-10 06:34:14 +0000791 }
792
David Blaikiebbafb8a2012-03-11 07:00:24 +0000793 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000794
Richard Smith357362d2011-12-13 06:39:58 +0000795 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000796 // Don't perform any constexpr calls (other than the call we're checking)
797 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000798 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000799 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000800 if (NextCallIndex == 0) {
801 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000802 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000803 return false;
804 }
Richard Smith357362d2011-12-13 06:39:58 +0000805 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
806 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000807 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000808 << getLangOpts().ConstexprCallDepth;
809 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000810 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000811
Richard Smithb228a862012-02-15 02:18:13 +0000812 CallStackFrame *getCallFrame(unsigned CallIndex) {
813 assert(CallIndex && "no call index in getCallFrame");
814 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
815 // be null in this loop.
816 CallStackFrame *Frame = CurrentCall;
817 while (Frame->Index > CallIndex)
818 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000819 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000820 }
821
Richard Smitha3d3bd22013-05-08 02:12:03 +0000822 bool nextStep(const Stmt *S) {
823 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000824 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000825 return false;
826 }
827 --StepsLeft;
828 return true;
829 }
830
Richard Smith357362d2011-12-13 06:39:58 +0000831 private:
832 /// Add a diagnostic to the diagnostics list.
833 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
834 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
835 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
836 return EvalStatus.Diag->back().second;
837 }
838
Richard Smithf6f003a2011-12-16 19:06:07 +0000839 /// Add notes containing a call stack to the current point of evaluation.
840 void addCallStack(unsigned Limit);
841
Faisal Valie690b7a2016-07-02 22:34:24 +0000842 private:
843 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
844 unsigned ExtraNotes, bool IsCCEDiag) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000845
Richard Smith92b1ce02011-12-12 09:28:41 +0000846 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000847 // If we have a prior diagnostic, it will be noting that the expression
848 // isn't a constant expression. This diagnostic is more important,
849 // unless we require this evaluation to produce a constant expression.
850 //
851 // FIXME: We might want to show both diagnostics to the user in
852 // EM_ConstantFold mode.
853 if (!EvalStatus.Diag->empty()) {
854 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000855 case EM_ConstantFold:
856 case EM_IgnoreSideEffects:
857 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000858 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000859 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000860 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000861 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000862 case EM_ConstantExpression:
863 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000864 case EM_ConstantExpressionUnevaluated:
865 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000866 HasActiveDiagnostic = false;
867 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000868 }
869 }
870
Richard Smithf6f003a2011-12-16 19:06:07 +0000871 unsigned CallStackNotes = CallStackDepth - 1;
872 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
873 if (Limit)
874 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000875 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000876 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000877
Richard Smith357362d2011-12-13 06:39:58 +0000878 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000879 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000880 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000881 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
882 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000883 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000884 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000885 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000886 }
Richard Smith357362d2011-12-13 06:39:58 +0000887 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000888 return OptionalDiagnostic();
889 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000890 public:
891 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
892 OptionalDiagnostic
893 FFDiag(SourceLocation Loc,
894 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
895 unsigned ExtraNotes = 0) {
896 return Diag(Loc, DiagId, ExtraNotes, false);
897 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000898
Faisal Valie690b7a2016-07-02 22:34:24 +0000899 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000900 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000901 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000902 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000903 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000904 HasActiveDiagnostic = false;
905 return OptionalDiagnostic();
906 }
907
Richard Smith92b1ce02011-12-12 09:28:41 +0000908 /// Diagnose that the evaluation does not produce a C++11 core constant
909 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000910 ///
911 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
912 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000913 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000914 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000915 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000916 // Don't override a previous diagnostic. Don't bother collecting
917 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000918 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000919 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000920 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000921 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000922 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000923 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000924 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
925 = diag::note_invalid_subexpr_in_const_expr,
926 unsigned ExtraNotes = 0) {
927 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
928 }
Richard Smith357362d2011-12-13 06:39:58 +0000929 /// Add a note to a prior diagnostic.
930 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
931 if (!HasActiveDiagnostic)
932 return OptionalDiagnostic();
933 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000934 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000935
936 /// Add a stack of notes to a prior diagnostic.
937 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
938 if (HasActiveDiagnostic) {
939 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
940 Diags.begin(), Diags.end());
941 }
942 }
Richard Smith253c2a32012-01-27 01:14:48 +0000943
Richard Smith6d4c6582013-11-05 22:18:15 +0000944 /// Should we continue evaluation after encountering a side-effect that we
945 /// couldn't model?
946 bool keepEvaluatingAfterSideEffect() {
947 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000948 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000949 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000950 case EM_EvaluateForOverflow:
951 case EM_IgnoreSideEffects:
952 return true;
953
Richard Smith6d4c6582013-11-05 22:18:15 +0000954 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000955 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000956 case EM_ConstantFold:
957 return false;
958 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000959 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000960 }
961
962 /// Note that we have had a side-effect, and determine whether we should
963 /// keep evaluating.
964 bool noteSideEffect() {
965 EvalStatus.HasSideEffects = true;
966 return keepEvaluatingAfterSideEffect();
967 }
968
Richard Smithce8eca52015-12-08 03:21:47 +0000969 /// Should we continue evaluation after encountering undefined behavior?
970 bool keepEvaluatingAfterUndefinedBehavior() {
971 switch (EvalMode) {
972 case EM_EvaluateForOverflow:
973 case EM_IgnoreSideEffects:
974 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000975 return true;
976
977 case EM_PotentialConstantExpression:
978 case EM_PotentialConstantExpressionUnevaluated:
979 case EM_ConstantExpression:
980 case EM_ConstantExpressionUnevaluated:
981 return false;
982 }
983 llvm_unreachable("Missed EvalMode case");
984 }
985
986 /// Note that we hit something that was technically undefined behavior, but
987 /// that we can evaluate past it (such as signed overflow or floating-point
988 /// division by zero.)
989 bool noteUndefinedBehavior() {
990 EvalStatus.HasUndefinedBehavior = true;
991 return keepEvaluatingAfterUndefinedBehavior();
992 }
993
Richard Smith253c2a32012-01-27 01:14:48 +0000994 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000995 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000996 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000997 if (!StepsLeft)
998 return false;
999
1000 switch (EvalMode) {
1001 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001002 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001003 case EM_EvaluateForOverflow:
1004 return true;
1005
1006 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001007 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001008 case EM_ConstantFold:
1009 case EM_IgnoreSideEffects:
1010 return false;
1011 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001012 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001013 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001014
George Burgess IV8c892b52016-05-25 22:31:54 +00001015 /// Notes that we failed to evaluate an expression that other expressions
1016 /// directly depend on, and determine if we should keep evaluating. This
1017 /// should only be called if we actually intend to keep evaluating.
1018 ///
1019 /// Call noteSideEffect() instead if we may be able to ignore the value that
1020 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1021 ///
1022 /// (Foo(), 1) // use noteSideEffect
1023 /// (Foo() || true) // use noteSideEffect
1024 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001025 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001026 // Failure when evaluating some expression often means there is some
1027 // subexpression whose evaluation was skipped. Therefore, (because we
1028 // don't track whether we skipped an expression when unwinding after an
1029 // evaluation failure) every evaluation failure that bubbles up from a
1030 // subexpression implies that a side-effect has potentially happened. We
1031 // skip setting the HasSideEffects flag to true until we decide to
1032 // continue evaluating after that point, which happens here.
1033 bool KeepGoing = keepEvaluatingAfterFailure();
1034 EvalStatus.HasSideEffects |= KeepGoing;
1035 return KeepGoing;
1036 }
1037
Richard Smith410306b2016-12-12 02:53:20 +00001038 class ArrayInitLoopIndex {
1039 EvalInfo &Info;
1040 uint64_t OuterIndex;
1041
1042 public:
1043 ArrayInitLoopIndex(EvalInfo &Info)
1044 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1045 Info.ArrayInitIndex = 0;
1046 }
1047 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1048
1049 operator uint64_t&() { return Info.ArrayInitIndex; }
1050 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001051 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001052
1053 /// Object used to treat all foldable expressions as constant expressions.
1054 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001055 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001056 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001057 bool HadNoPriorDiags;
1058 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001059
Richard Smith6d4c6582013-11-05 22:18:15 +00001060 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1061 : Info(Info),
1062 Enabled(Enabled),
1063 HadNoPriorDiags(Info.EvalStatus.Diag &&
1064 Info.EvalStatus.Diag->empty() &&
1065 !Info.EvalStatus.HasSideEffects),
1066 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001067 if (Enabled &&
1068 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1069 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001070 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001071 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001072 void keepDiagnostics() { Enabled = false; }
1073 ~FoldConstant() {
1074 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001075 !Info.EvalStatus.HasSideEffects)
1076 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001077 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001078 }
1079 };
Richard Smith17100ba2012-02-16 02:46:34 +00001080
James Y Knight892b09b2018-10-10 02:53:43 +00001081 /// RAII object used to set the current evaluation mode to ignore
1082 /// side-effects.
1083 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001084 EvalInfo &Info;
1085 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001086 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001087 : Info(Info), OldMode(Info.EvalMode) {
1088 if (!Info.checkingPotentialConstantExpression())
James Y Knight892b09b2018-10-10 02:53:43 +00001089 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001090 }
1091
James Y Knight892b09b2018-10-10 02:53:43 +00001092 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001093 };
1094
George Burgess IV8c892b52016-05-25 22:31:54 +00001095 /// RAII object used to optionally suppress diagnostics and side-effects from
1096 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001097 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001098 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001099 Expr::EvalStatus OldStatus;
1100 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001101
George Burgess IV8c892b52016-05-25 22:31:54 +00001102 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001103 Info = Other.Info;
1104 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001105 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001106 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001107 }
1108
1109 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001110 if (!Info)
1111 return;
1112
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001113 Info->EvalStatus = OldStatus;
1114 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001115 }
1116
Richard Smith17100ba2012-02-16 02:46:34 +00001117 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001118 SpeculativeEvaluationRAII() = default;
1119
1120 SpeculativeEvaluationRAII(
1121 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001122 : Info(&Info), OldStatus(Info.EvalStatus),
1123 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001124 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001125 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001126 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001127
1128 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1129 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1130 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001131 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001132
1133 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1134 maybeRestoreState();
1135 moveFromAndCancel(std::move(Other));
1136 return *this;
1137 }
1138
1139 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001140 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001141
1142 /// RAII object wrapping a full-expression or block scope, and handling
1143 /// the ending of the lifetime of temporaries created within it.
1144 template<bool IsFullExpression>
1145 class ScopeRAII {
1146 EvalInfo &Info;
1147 unsigned OldStackSize;
1148 public:
1149 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001150 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1151 // Push a new temporary version. This is needed to distinguish between
1152 // temporaries created in different iterations of a loop.
1153 Info.CurrentCall->pushTempVersion();
1154 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001155 ~ScopeRAII() {
1156 // Body moved to a static method to encourage the compiler to inline away
1157 // instances of this class.
1158 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001159 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001160 }
1161 private:
1162 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1163 unsigned NewEnd = OldStackSize;
1164 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1165 I != N; ++I) {
1166 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1167 // Full-expression cleanup of a lifetime-extended temporary: nothing
1168 // to do, just move this cleanup to the right place in the stack.
1169 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1170 ++NewEnd;
1171 } else {
1172 // End the lifetime of the object.
1173 Info.CleanupStack[I].endLifetime();
1174 }
1175 }
1176 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1177 Info.CleanupStack.end());
1178 }
1179 };
1180 typedef ScopeRAII<false> BlockScopeRAII;
1181 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001182}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001183
Richard Smitha8105bc2012-01-06 16:39:00 +00001184bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1185 CheckSubobjectKind CSK) {
1186 if (Invalid)
1187 return false;
1188 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001189 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001190 << CSK;
1191 setInvalid();
1192 return false;
1193 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001194 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1195 // must actually be at least one array element; even a VLA cannot have a
1196 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001197 return true;
1198}
1199
Richard Smith6f4f0f12017-10-20 22:56:25 +00001200void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1201 const Expr *E) {
1202 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1203 // Do not set the designator as invalid: we can represent this situation,
1204 // and correct handling of __builtin_object_size requires us to do so.
1205}
1206
Richard Smitha8105bc2012-01-06 16:39:00 +00001207void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001208 const Expr *E,
1209 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001210 // If we're complaining, we must be able to statically determine the size of
1211 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001212 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001213 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001214 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001215 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001216 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001217 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001218 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001219 setInvalid();
1220}
1221
Richard Smithf6f003a2011-12-16 19:06:07 +00001222CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1223 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001224 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001225 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1226 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001227 Info.CurrentCall = this;
1228 ++Info.CallStackDepth;
1229}
1230
1231CallStackFrame::~CallStackFrame() {
1232 assert(Info.CurrentCall == this && "calls retired out of order");
1233 --Info.CallStackDepth;
1234 Info.CurrentCall = Caller;
1235}
1236
Richard Smith08d6a2c2013-07-24 07:11:57 +00001237APValue &CallStackFrame::createTemporary(const void *Key,
1238 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001239 unsigned Version = Info.CurrentCall->getTempVersion();
1240 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smith08d6a2c2013-07-24 07:11:57 +00001241 assert(Result.isUninit() && "temporary created multiple times");
1242 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1243 return Result;
1244}
1245
Richard Smith84401042013-06-03 05:03:02 +00001246static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001247
1248void EvalInfo::addCallStack(unsigned Limit) {
1249 // Determine which calls to skip, if any.
1250 unsigned ActiveCalls = CallStackDepth - 1;
1251 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1252 if (Limit && Limit < ActiveCalls) {
1253 SkipStart = Limit / 2 + Limit % 2;
1254 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001255 }
1256
Richard Smithf6f003a2011-12-16 19:06:07 +00001257 // Walk the call stack and add the diagnostics.
1258 unsigned CallIdx = 0;
1259 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1260 Frame = Frame->Caller, ++CallIdx) {
1261 // Skip this call?
1262 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1263 if (CallIdx == SkipStart) {
1264 // Note that we're skipping calls.
1265 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1266 << unsigned(ActiveCalls - Limit);
1267 }
1268 continue;
1269 }
1270
Richard Smith5179eb72016-06-28 19:03:57 +00001271 // Use a different note for an inheriting constructor, because from the
1272 // user's perspective it's not really a function at all.
1273 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1274 if (CD->isInheritingConstructor()) {
1275 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1276 << CD->getParent();
1277 continue;
1278 }
1279 }
1280
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001281 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001282 llvm::raw_svector_ostream Out(Buffer);
1283 describeCall(Frame, Out);
1284 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1285 }
1286}
1287
1288namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001289 struct ComplexValue {
1290 private:
1291 bool IsInt;
1292
1293 public:
1294 APSInt IntReal, IntImag;
1295 APFloat FloatReal, FloatImag;
1296
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001297 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001298
1299 void makeComplexFloat() { IsInt = false; }
1300 bool isComplexFloat() const { return !IsInt; }
1301 APFloat &getComplexFloatReal() { return FloatReal; }
1302 APFloat &getComplexFloatImag() { return FloatImag; }
1303
1304 void makeComplexInt() { IsInt = true; }
1305 bool isComplexInt() const { return IsInt; }
1306 APSInt &getComplexIntReal() { return IntReal; }
1307 APSInt &getComplexIntImag() { return IntImag; }
1308
Richard Smith2e312c82012-03-03 22:46:17 +00001309 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001310 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001311 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001312 else
Richard Smith2e312c82012-03-03 22:46:17 +00001313 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001314 }
Richard Smith2e312c82012-03-03 22:46:17 +00001315 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001316 assert(v.isComplexFloat() || v.isComplexInt());
1317 if (v.isComplexFloat()) {
1318 makeComplexFloat();
1319 FloatReal = v.getComplexFloatReal();
1320 FloatImag = v.getComplexFloatImag();
1321 } else {
1322 makeComplexInt();
1323 IntReal = v.getComplexIntReal();
1324 IntImag = v.getComplexIntImag();
1325 }
1326 }
John McCall93d91dc2010-05-07 17:22:02 +00001327 };
John McCall45d55e42010-05-07 21:00:08 +00001328
1329 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001330 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001331 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001332 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001333 bool IsNullPtr : 1;
1334 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001335
Richard Smithce40ad62011-11-12 22:28:03 +00001336 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001337 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001338 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001339 SubobjectDesignator &getLValueDesignator() { return Designator; }
1340 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001341 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001342
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001343 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1344 unsigned getLValueVersion() const { return Base.getVersion(); }
1345
Richard Smith2e312c82012-03-03 22:46:17 +00001346 void moveInto(APValue &V) const {
1347 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001348 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001349 else {
1350 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001351 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001352 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001353 }
John McCall45d55e42010-05-07 21:00:08 +00001354 }
Richard Smith2e312c82012-03-03 22:46:17 +00001355 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001356 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001357 Base = V.getLValueBase();
1358 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001359 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001360 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001361 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001362 }
1363
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001364 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001365#ifndef NDEBUG
1366 // We only allow a few types of invalid bases. Enforce that here.
1367 if (BInvalid) {
1368 const auto *E = B.get<const Expr *>();
1369 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1370 "Unexpected type of invalid base");
1371 }
1372#endif
1373
Richard Smithce40ad62011-11-12 22:28:03 +00001374 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001375 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001376 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001377 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001378 IsNullPtr = false;
1379 }
1380
1381 void setNull(QualType PointerTy, uint64_t TargetVal) {
1382 Base = (Expr *)nullptr;
1383 Offset = CharUnits::fromQuantity(TargetVal);
1384 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001385 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1386 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001387 }
1388
George Burgess IV3a03fab2015-09-04 21:28:13 +00001389 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001390 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001391 }
1392
Richard Smitha8105bc2012-01-06 16:39:00 +00001393 // Check that this LValue is not based on a null pointer. If it is, produce
1394 // a diagnostic and mark the designator as invalid.
1395 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1396 CheckSubobjectKind CSK) {
1397 if (Designator.Invalid)
1398 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001399 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001400 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001401 << CSK;
1402 Designator.setInvalid();
1403 return false;
1404 }
1405 return true;
1406 }
1407
1408 // Check this LValue refers to an object. If not, set the designator to be
1409 // invalid and emit a diagnostic.
1410 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001411 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001412 Designator.checkSubobject(Info, E, CSK);
1413 }
1414
1415 void addDecl(EvalInfo &Info, const Expr *E,
1416 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001417 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1418 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001419 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001420 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1421 if (!Designator.Entries.empty()) {
1422 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1423 Designator.setInvalid();
1424 return;
1425 }
Richard Smithefdb5032017-11-15 03:03:56 +00001426 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1427 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1428 Designator.FirstEntryIsAnUnsizedArray = true;
1429 Designator.addUnsizedArrayUnchecked(ElemTy);
1430 }
George Burgess IVe3763372016-12-22 02:50:20 +00001431 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001432 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001433 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1434 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001435 }
Richard Smith66c96992012-02-18 22:04:06 +00001436 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001437 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1438 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001439 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001440 void clearIsNullPointer() {
1441 IsNullPtr = false;
1442 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001443 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1444 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001445 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1446 // but we're not required to diagnose it and it's valid in C++.)
1447 if (!Index)
1448 return;
1449
1450 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1451 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1452 // offsets.
1453 uint64_t Offset64 = Offset.getQuantity();
1454 uint64_t ElemSize64 = ElementSize.getQuantity();
1455 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1456 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1457
1458 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001459 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001460 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001461 }
1462 void adjustOffset(CharUnits N) {
1463 Offset += N;
1464 if (N.getQuantity())
1465 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001466 }
John McCall45d55e42010-05-07 21:00:08 +00001467 };
Richard Smith027bf112011-11-17 22:56:20 +00001468
1469 struct MemberPtr {
1470 MemberPtr() {}
1471 explicit MemberPtr(const ValueDecl *Decl) :
1472 DeclAndIsDerivedMember(Decl, false), Path() {}
1473
1474 /// The member or (direct or indirect) field referred to by this member
1475 /// pointer, or 0 if this is a null member pointer.
1476 const ValueDecl *getDecl() const {
1477 return DeclAndIsDerivedMember.getPointer();
1478 }
1479 /// Is this actually a member of some type derived from the relevant class?
1480 bool isDerivedMember() const {
1481 return DeclAndIsDerivedMember.getInt();
1482 }
1483 /// Get the class which the declaration actually lives in.
1484 const CXXRecordDecl *getContainingRecord() const {
1485 return cast<CXXRecordDecl>(
1486 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1487 }
1488
Richard Smith2e312c82012-03-03 22:46:17 +00001489 void moveInto(APValue &V) const {
1490 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001491 }
Richard Smith2e312c82012-03-03 22:46:17 +00001492 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001493 assert(V.isMemberPointer());
1494 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1495 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1496 Path.clear();
1497 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1498 Path.insert(Path.end(), P.begin(), P.end());
1499 }
1500
1501 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1502 /// whether the member is a member of some class derived from the class type
1503 /// of the member pointer.
1504 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1505 /// Path - The path of base/derived classes from the member declaration's
1506 /// class (exclusive) to the class type of the member pointer (inclusive).
1507 SmallVector<const CXXRecordDecl*, 4> Path;
1508
1509 /// Perform a cast towards the class of the Decl (either up or down the
1510 /// hierarchy).
1511 bool castBack(const CXXRecordDecl *Class) {
1512 assert(!Path.empty());
1513 const CXXRecordDecl *Expected;
1514 if (Path.size() >= 2)
1515 Expected = Path[Path.size() - 2];
1516 else
1517 Expected = getContainingRecord();
1518 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1519 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1520 // if B does not contain the original member and is not a base or
1521 // derived class of the class containing the original member, the result
1522 // of the cast is undefined.
1523 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1524 // (D::*). We consider that to be a language defect.
1525 return false;
1526 }
1527 Path.pop_back();
1528 return true;
1529 }
1530 /// Perform a base-to-derived member pointer cast.
1531 bool castToDerived(const CXXRecordDecl *Derived) {
1532 if (!getDecl())
1533 return true;
1534 if (!isDerivedMember()) {
1535 Path.push_back(Derived);
1536 return true;
1537 }
1538 if (!castBack(Derived))
1539 return false;
1540 if (Path.empty())
1541 DeclAndIsDerivedMember.setInt(false);
1542 return true;
1543 }
1544 /// Perform a derived-to-base member pointer cast.
1545 bool castToBase(const CXXRecordDecl *Base) {
1546 if (!getDecl())
1547 return true;
1548 if (Path.empty())
1549 DeclAndIsDerivedMember.setInt(true);
1550 if (isDerivedMember()) {
1551 Path.push_back(Base);
1552 return true;
1553 }
1554 return castBack(Base);
1555 }
1556 };
Richard Smith357362d2011-12-13 06:39:58 +00001557
Richard Smith7bb00672012-02-01 01:42:44 +00001558 /// Compare two member pointers, which are assumed to be of the same type.
1559 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1560 if (!LHS.getDecl() || !RHS.getDecl())
1561 return !LHS.getDecl() && !RHS.getDecl();
1562 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1563 return false;
1564 return LHS.Path == RHS.Path;
1565 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001566}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001567
Richard Smith2e312c82012-03-03 22:46:17 +00001568static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001569static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1570 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001571 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001572static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1573 bool InvalidBaseOK = false);
1574static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1575 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001576static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1577 EvalInfo &Info);
1578static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001579static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001580static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001581 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001582static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001583static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001584static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1585 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001586static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001587
1588//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001589// Misc utilities
1590//===----------------------------------------------------------------------===//
1591
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001592/// A helper function to create a temporary and set an LValue.
1593template <class KeyTy>
1594static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1595 LValue &LV, CallStackFrame &Frame) {
1596 LV.set({Key, Frame.Info.CurrentCall->Index,
1597 Frame.Info.CurrentCall->getTempVersion()});
1598 return Frame.createTemporary(Key, IsLifetimeExtended);
1599}
1600
Richard Smithd6cc1982017-01-31 02:23:02 +00001601/// Negate an APSInt in place, converting it to a signed form if necessary, and
1602/// preserving its value (by extending by up to one bit as needed).
1603static void negateAsSigned(APSInt &Int) {
1604 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1605 Int = Int.extend(Int.getBitWidth() + 1);
1606 Int.setIsSigned(true);
1607 }
1608 Int = -Int;
1609}
1610
Richard Smith84401042013-06-03 05:03:02 +00001611/// Produce a string describing the given constexpr call.
1612static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1613 unsigned ArgIndex = 0;
1614 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1615 !isa<CXXConstructorDecl>(Frame->Callee) &&
1616 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1617
1618 if (!IsMemberCall)
1619 Out << *Frame->Callee << '(';
1620
1621 if (Frame->This && IsMemberCall) {
1622 APValue Val;
1623 Frame->This->moveInto(Val);
1624 Val.printPretty(Out, Frame->Info.Ctx,
1625 Frame->This->Designator.MostDerivedType);
1626 // FIXME: Add parens around Val if needed.
1627 Out << "->" << *Frame->Callee << '(';
1628 IsMemberCall = false;
1629 }
1630
1631 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1632 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1633 if (ArgIndex > (unsigned)IsMemberCall)
1634 Out << ", ";
1635
1636 const ParmVarDecl *Param = *I;
1637 const APValue &Arg = Frame->Arguments[ArgIndex];
1638 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1639
1640 if (ArgIndex == 0 && IsMemberCall)
1641 Out << "->" << *Frame->Callee << '(';
1642 }
1643
1644 Out << ')';
1645}
1646
Richard Smithd9f663b2013-04-22 15:31:51 +00001647/// Evaluate an expression to see if it had side-effects, and discard its
1648/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001649/// \return \c true if the caller should keep evaluating.
1650static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001651 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001652 if (!Evaluate(Scratch, Info, E))
1653 // We don't need the value, but we might have skipped a side effect here.
1654 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001655 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001656}
1657
Richard Smithd62306a2011-11-10 06:34:14 +00001658/// Should this call expression be treated as a string literal?
1659static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001660 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001661 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1662 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1663}
1664
Richard Smithce40ad62011-11-12 22:28:03 +00001665static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001666 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1667 // constant expression of pointer type that evaluates to...
1668
1669 // ... a null pointer value, or a prvalue core constant expression of type
1670 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001671 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001672
Richard Smithce40ad62011-11-12 22:28:03 +00001673 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1674 // ... the address of an object with static storage duration,
1675 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1676 return VD->hasGlobalStorage();
1677 // ... the address of a function,
1678 return isa<FunctionDecl>(D);
1679 }
1680
1681 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001682 switch (E->getStmtClass()) {
1683 default:
1684 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001685 case Expr::CompoundLiteralExprClass: {
1686 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1687 return CLE->isFileScope() && CLE->isLValue();
1688 }
Richard Smithe6c01442013-06-05 00:46:14 +00001689 case Expr::MaterializeTemporaryExprClass:
1690 // A materialized temporary might have been lifetime-extended to static
1691 // storage duration.
1692 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001693 // A string literal has static storage duration.
1694 case Expr::StringLiteralClass:
1695 case Expr::PredefinedExprClass:
1696 case Expr::ObjCStringLiteralClass:
1697 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001698 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001699 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001700 return true;
1701 case Expr::CallExprClass:
1702 return IsStringLiteralCall(cast<CallExpr>(E));
1703 // For GCC compatibility, &&label has static storage duration.
1704 case Expr::AddrLabelExprClass:
1705 return true;
1706 // A Block literal expression may be used as the initialization value for
1707 // Block variables at global or local static scope.
1708 case Expr::BlockExprClass:
1709 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001710 case Expr::ImplicitValueInitExprClass:
1711 // FIXME:
1712 // We can never form an lvalue with an implicit value initialization as its
1713 // base through expression evaluation, so these only appear in one case: the
1714 // implicit variable declaration we invent when checking whether a constexpr
1715 // constructor can produce a constant expression. We must assume that such
1716 // an expression might be a global lvalue.
1717 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001718 }
John McCall95007602010-05-10 23:27:23 +00001719}
1720
Richard Smith06f71b52018-08-04 00:57:17 +00001721static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1722 return LVal.Base.dyn_cast<const ValueDecl*>();
1723}
1724
1725static bool IsLiteralLValue(const LValue &Value) {
1726 if (Value.getLValueCallIndex())
1727 return false;
1728 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1729 return E && !isa<MaterializeTemporaryExpr>(E);
1730}
1731
1732static bool IsWeakLValue(const LValue &Value) {
1733 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1734 return Decl && Decl->isWeak();
1735}
1736
1737static bool isZeroSized(const LValue &Value) {
1738 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1739 if (Decl && isa<VarDecl>(Decl)) {
1740 QualType Ty = Decl->getType();
1741 if (Ty->isArrayType())
1742 return Ty->isIncompleteType() ||
1743 Decl->getASTContext().getTypeSize(Ty) == 0;
1744 }
1745 return false;
1746}
1747
1748static bool HasSameBase(const LValue &A, const LValue &B) {
1749 if (!A.getLValueBase())
1750 return !B.getLValueBase();
1751 if (!B.getLValueBase())
1752 return false;
1753
1754 if (A.getLValueBase().getOpaqueValue() !=
1755 B.getLValueBase().getOpaqueValue()) {
1756 const Decl *ADecl = GetLValueBaseDecl(A);
1757 if (!ADecl)
1758 return false;
1759 const Decl *BDecl = GetLValueBaseDecl(B);
1760 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1761 return false;
1762 }
1763
1764 return IsGlobalLValue(A.getLValueBase()) ||
1765 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1766 A.getLValueVersion() == B.getLValueVersion());
1767}
1768
Richard Smithb228a862012-02-15 02:18:13 +00001769static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1770 assert(Base && "no location for a null lvalue");
1771 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1772 if (VD)
1773 Info.Note(VD->getLocation(), diag::note_declared_at);
1774 else
Ted Kremenek28831752012-08-23 20:46:57 +00001775 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001776 diag::note_constexpr_temporary_here);
1777}
1778
Richard Smith80815602011-11-07 05:07:52 +00001779/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001780/// value for an address or reference constant expression. Return true if we
1781/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001782static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001783 QualType Type, const LValue &LVal,
1784 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001785 bool IsReferenceType = Type->isReferenceType();
1786
Richard Smith357362d2011-12-13 06:39:58 +00001787 APValue::LValueBase Base = LVal.getLValueBase();
1788 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1789
Richard Smith0dea49e2012-02-18 04:58:18 +00001790 // Check that the object is a global. Note that the fake 'this' object we
1791 // manufacture when checking potential constant expressions is conservatively
1792 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001793 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001794 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001795 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001796 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001797 << IsReferenceType << !Designator.Entries.empty()
1798 << !!VD << VD;
1799 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001800 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001801 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001802 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001803 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001804 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001805 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001806 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001807 LVal.getLValueCallIndex() == 0) &&
1808 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001809
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001810 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1811 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001812 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001813 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001814 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001815
Hans Wennborg82dd8772014-06-25 22:19:48 +00001816 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001817 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001818 return false;
1819 }
1820 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1821 // __declspec(dllimport) must be handled very carefully:
1822 // We must never initialize an expression with the thunk in C++.
1823 // Doing otherwise would allow the same id-expression to yield
1824 // different addresses for the same function in different translation
1825 // units. However, this means that we must dynamically initialize the
1826 // expression with the contents of the import address table at runtime.
1827 //
1828 // The C language has no notion of ODR; furthermore, it has no notion of
1829 // dynamic initialization. This means that we are permitted to
1830 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001831 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1832 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001833 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001834 }
1835 }
1836
Richard Smitha8105bc2012-01-06 16:39:00 +00001837 // Allow address constant expressions to be past-the-end pointers. This is
1838 // an extension: the standard requires them to point to an object.
1839 if (!IsReferenceType)
1840 return true;
1841
1842 // A reference constant expression must refer to an object.
1843 if (!Base) {
1844 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001845 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001846 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001847 }
1848
Richard Smith357362d2011-12-13 06:39:58 +00001849 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001850 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001851 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001852 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001853 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001854 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001855 }
1856
Richard Smith80815602011-11-07 05:07:52 +00001857 return true;
1858}
1859
Reid Klecknercd016d82017-07-07 22:04:29 +00001860/// Member pointers are constant expressions unless they point to a
1861/// non-virtual dllimport member function.
1862static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1863 SourceLocation Loc,
1864 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001865 const APValue &Value,
1866 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00001867 const ValueDecl *Member = Value.getMemberPointerDecl();
1868 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1869 if (!FD)
1870 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001871 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1872 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00001873}
1874
Richard Smithfddd3842011-12-30 21:15:51 +00001875/// Check that this core constant expression is of literal type, and if not,
1876/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001877static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001878 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001879 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001880 return true;
1881
Richard Smith7525ff62013-05-09 07:14:00 +00001882 // C++1y: A constant initializer for an object o [...] may also invoke
1883 // constexpr constructors for o and its subobjects even if those objects
1884 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001885 //
1886 // C++11 missed this detail for aggregates, so classes like this:
1887 // struct foo_t { union { int i; volatile int j; } u; };
1888 // are not (obviously) initializable like so:
1889 // __attribute__((__require_constant_initialization__))
1890 // static const foo_t x = {{0}};
1891 // because "i" is a subobject with non-literal initialization (due to the
1892 // volatile member of the union). See:
1893 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1894 // Therefore, we use the C++1y behavior.
1895 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001896 return true;
1897
Richard Smithfddd3842011-12-30 21:15:51 +00001898 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001899 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001900 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001901 << E->getType();
1902 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001903 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001904 return false;
1905}
1906
Richard Smith0b0a0b62011-10-29 20:57:55 +00001907/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001908/// constant expression. If not, report an appropriate diagnostic. Does not
1909/// check that the expression is of literal type.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001910static bool
1911CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1912 const APValue &Value,
1913 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
Richard Smith1a90f592013-06-18 17:51:51 +00001914 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001915 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001916 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001917 return false;
1918 }
1919
Richard Smith77be48a2014-07-31 06:31:19 +00001920 // We allow _Atomic(T) to be initialized from anything that T can be
1921 // initialized from.
1922 if (const AtomicType *AT = Type->getAs<AtomicType>())
1923 Type = AT->getValueType();
1924
Richard Smithb228a862012-02-15 02:18:13 +00001925 // Core issue 1454: For a literal constant expression of array or class type,
1926 // each subobject of its value shall have been initialized by a constant
1927 // expression.
1928 if (Value.isArray()) {
1929 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1930 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1931 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001932 Value.getArrayInitializedElt(I), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001933 return false;
1934 }
1935 if (!Value.hasArrayFiller())
1936 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001937 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1938 Usage);
Richard Smith80815602011-11-07 05:07:52 +00001939 }
Richard Smithb228a862012-02-15 02:18:13 +00001940 if (Value.isUnion() && Value.getUnionField()) {
1941 return CheckConstantExpression(Info, DiagLoc,
1942 Value.getUnionField()->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001943 Value.getUnionValue(), Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001944 }
1945 if (Value.isStruct()) {
1946 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1947 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1948 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001949 for (const CXXBaseSpecifier &BS : CD->bases()) {
1950 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
1951 Value.getStructBase(BaseIndex), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001952 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001953 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00001954 }
1955 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001956 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001957 if (I->isUnnamedBitfield())
1958 continue;
1959
David Blaikie2d7c57e2012-04-30 02:36:29 +00001960 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001961 Value.getStructField(I->getFieldIndex()),
1962 Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001963 return false;
1964 }
1965 }
1966
1967 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001968 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001969 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00001970 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001971 }
1972
Reid Klecknercd016d82017-07-07 22:04:29 +00001973 if (Value.isMemberPointer())
Reid Kleckner1a840d22018-05-10 18:57:35 +00001974 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00001975
Richard Smithb228a862012-02-15 02:18:13 +00001976 // Everything else is fine.
1977 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001978}
1979
Richard Smith2e312c82012-03-03 22:46:17 +00001980static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001981 // A null base expression indicates a null pointer. These are always
1982 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001983 if (!Value.getLValueBase()) {
1984 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001985 return true;
1986 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001987
Richard Smith027bf112011-11-17 22:56:20 +00001988 // We have a non-null base. These are generally known to be true, but if it's
1989 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001990 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001991 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001992 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001993}
1994
Richard Smith2e312c82012-03-03 22:46:17 +00001995static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001996 switch (Val.getKind()) {
1997 case APValue::Uninitialized:
1998 return false;
1999 case APValue::Int:
2000 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002001 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002002 case APValue::Float:
2003 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002004 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002005 case APValue::ComplexInt:
2006 Result = Val.getComplexIntReal().getBoolValue() ||
2007 Val.getComplexIntImag().getBoolValue();
2008 return true;
2009 case APValue::ComplexFloat:
2010 Result = !Val.getComplexFloatReal().isZero() ||
2011 !Val.getComplexFloatImag().isZero();
2012 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002013 case APValue::LValue:
2014 return EvalPointerValueAsBool(Val, Result);
2015 case APValue::MemberPointer:
2016 Result = Val.getMemberPointerDecl();
2017 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002018 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002019 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002020 case APValue::Struct:
2021 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002022 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002023 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002024 }
2025
Richard Smith11562c52011-10-28 17:51:58 +00002026 llvm_unreachable("unknown APValue kind");
2027}
2028
2029static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2030 EvalInfo &Info) {
2031 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002032 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002033 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002034 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002035 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002036}
2037
Richard Smith357362d2011-12-13 06:39:58 +00002038template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002039static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002040 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002041 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002042 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002043 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002044}
2045
2046static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2047 QualType SrcType, const APFloat &Value,
2048 QualType DestType, APSInt &Result) {
2049 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002050 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002051 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002052
Richard Smith357362d2011-12-13 06:39:58 +00002053 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002054 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002055 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2056 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002057 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002058 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002059}
2060
Richard Smith357362d2011-12-13 06:39:58 +00002061static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2062 QualType SrcType, QualType DestType,
2063 APFloat &Result) {
2064 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002065 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002066 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2067 APFloat::rmNearestTiesToEven, &ignored)
2068 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002069 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002070 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002071}
2072
Richard Smith911e1422012-01-30 22:27:01 +00002073static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2074 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002075 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002076 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002077 APSInt Result = Value;
2078 // Figure out if this is a truncate, extend or noop cast.
2079 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00002080 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002081 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002082 return Result;
2083}
2084
Richard Smith357362d2011-12-13 06:39:58 +00002085static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2086 QualType SrcType, const APSInt &Value,
2087 QualType DestType, APFloat &Result) {
2088 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2089 if (Result.convertFromAPInt(Value, Value.isSigned(),
2090 APFloat::rmNearestTiesToEven)
2091 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002092 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002093 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002094}
2095
Richard Smith49ca8aa2013-08-06 07:09:20 +00002096static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2097 APValue &Value, const FieldDecl *FD) {
2098 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2099
2100 if (!Value.isInt()) {
2101 // Trying to store a pointer-cast-to-integer into a bitfield.
2102 // FIXME: In this case, we should provide the diagnostic for casting
2103 // a pointer to an integer.
2104 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002105 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002106 return false;
2107 }
2108
2109 APSInt &Int = Value.getInt();
2110 unsigned OldBitWidth = Int.getBitWidth();
2111 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2112 if (NewBitWidth < OldBitWidth)
2113 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2114 return true;
2115}
2116
Eli Friedman803acb32011-12-22 03:51:45 +00002117static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2118 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002119 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002120 if (!Evaluate(SVal, Info, E))
2121 return false;
2122 if (SVal.isInt()) {
2123 Res = SVal.getInt();
2124 return true;
2125 }
2126 if (SVal.isFloat()) {
2127 Res = SVal.getFloat().bitcastToAPInt();
2128 return true;
2129 }
2130 if (SVal.isVector()) {
2131 QualType VecTy = E->getType();
2132 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2133 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2134 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2135 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2136 Res = llvm::APInt::getNullValue(VecSize);
2137 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2138 APValue &Elt = SVal.getVectorElt(i);
2139 llvm::APInt EltAsInt;
2140 if (Elt.isInt()) {
2141 EltAsInt = Elt.getInt();
2142 } else if (Elt.isFloat()) {
2143 EltAsInt = Elt.getFloat().bitcastToAPInt();
2144 } else {
2145 // Don't try to handle vectors of anything other than int or float
2146 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002147 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002148 return false;
2149 }
2150 unsigned BaseEltSize = EltAsInt.getBitWidth();
2151 if (BigEndian)
2152 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2153 else
2154 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2155 }
2156 return true;
2157 }
2158 // Give up if the input isn't an int, float, or vector. For example, we
2159 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002160 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002161 return false;
2162}
2163
Richard Smith43e77732013-05-07 04:50:00 +00002164/// Perform the given integer operation, which is known to need at most BitWidth
2165/// bits, and check for overflow in the original type (if that type was not an
2166/// unsigned type).
2167template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002168static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2169 const APSInt &LHS, const APSInt &RHS,
2170 unsigned BitWidth, Operation Op,
2171 APSInt &Result) {
2172 if (LHS.isUnsigned()) {
2173 Result = Op(LHS, RHS);
2174 return true;
2175 }
Richard Smith43e77732013-05-07 04:50:00 +00002176
2177 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002178 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002179 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002180 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002181 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002182 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002183 << Result.toString(10) << E->getType();
2184 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002185 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002186 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002187 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002188}
2189
2190/// Perform the given binary integer operation.
2191static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2192 BinaryOperatorKind Opcode, APSInt RHS,
2193 APSInt &Result) {
2194 switch (Opcode) {
2195 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002196 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002197 return false;
2198 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002199 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2200 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002201 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002202 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2203 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002204 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002205 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2206 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002207 case BO_And: Result = LHS & RHS; return true;
2208 case BO_Xor: Result = LHS ^ RHS; return true;
2209 case BO_Or: Result = LHS | RHS; return true;
2210 case BO_Div:
2211 case BO_Rem:
2212 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002213 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002214 return false;
2215 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002216 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2217 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2218 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002219 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2220 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002221 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2222 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002223 return true;
2224 case BO_Shl: {
2225 if (Info.getLangOpts().OpenCL)
2226 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2227 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2228 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2229 RHS.isUnsigned());
2230 else if (RHS.isSigned() && RHS.isNegative()) {
2231 // During constant-folding, a negative shift is an opposite shift. Such
2232 // a shift is not a constant expression.
2233 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2234 RHS = -RHS;
2235 goto shift_right;
2236 }
2237 shift_left:
2238 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2239 // the shifted type.
2240 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2241 if (SA != RHS) {
2242 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2243 << RHS << E->getType() << LHS.getBitWidth();
2244 } else if (LHS.isSigned()) {
2245 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2246 // operand, and must not overflow the corresponding unsigned type.
2247 if (LHS.isNegative())
2248 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2249 else if (LHS.countLeadingZeros() < SA)
2250 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2251 }
2252 Result = LHS << SA;
2253 return true;
2254 }
2255 case BO_Shr: {
2256 if (Info.getLangOpts().OpenCL)
2257 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2258 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2259 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2260 RHS.isUnsigned());
2261 else if (RHS.isSigned() && RHS.isNegative()) {
2262 // During constant-folding, a negative shift is an opposite shift. Such a
2263 // shift is not a constant expression.
2264 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2265 RHS = -RHS;
2266 goto shift_left;
2267 }
2268 shift_right:
2269 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2270 // shifted type.
2271 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2272 if (SA != RHS)
2273 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2274 << RHS << E->getType() << LHS.getBitWidth();
2275 Result = LHS >> SA;
2276 return true;
2277 }
2278
2279 case BO_LT: Result = LHS < RHS; return true;
2280 case BO_GT: Result = LHS > RHS; return true;
2281 case BO_LE: Result = LHS <= RHS; return true;
2282 case BO_GE: Result = LHS >= RHS; return true;
2283 case BO_EQ: Result = LHS == RHS; return true;
2284 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002285 case BO_Cmp:
2286 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002287 }
2288}
2289
Richard Smith861b5b52013-05-07 23:34:45 +00002290/// Perform the given binary floating-point operation, in-place, on LHS.
2291static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2292 APFloat &LHS, BinaryOperatorKind Opcode,
2293 const APFloat &RHS) {
2294 switch (Opcode) {
2295 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002296 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002297 return false;
2298 case BO_Mul:
2299 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2300 break;
2301 case BO_Add:
2302 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2303 break;
2304 case BO_Sub:
2305 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2306 break;
2307 case BO_Div:
2308 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2309 break;
2310 }
2311
Richard Smith0c6124b2015-12-03 01:36:22 +00002312 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002313 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002314 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002315 }
Richard Smith861b5b52013-05-07 23:34:45 +00002316 return true;
2317}
2318
Richard Smitha8105bc2012-01-06 16:39:00 +00002319/// Cast an lvalue referring to a base subobject to a derived class, by
2320/// truncating the lvalue's path to the given length.
2321static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2322 const RecordDecl *TruncatedType,
2323 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002324 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002325
2326 // Check we actually point to a derived class object.
2327 if (TruncatedElements == D.Entries.size())
2328 return true;
2329 assert(TruncatedElements >= D.MostDerivedPathLength &&
2330 "not casting to a derived class");
2331 if (!Result.checkSubobject(Info, E, CSK_Derived))
2332 return false;
2333
2334 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002335 const RecordDecl *RD = TruncatedType;
2336 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002337 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002338 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2339 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002340 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002341 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002342 else
Richard Smithd62306a2011-11-10 06:34:14 +00002343 Result.Offset -= Layout.getBaseClassOffset(Base);
2344 RD = Base;
2345 }
Richard Smith027bf112011-11-17 22:56:20 +00002346 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002347 return true;
2348}
2349
John McCalld7bca762012-05-01 00:38:49 +00002350static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002351 const CXXRecordDecl *Derived,
2352 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002353 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002354 if (!RL) {
2355 if (Derived->isInvalidDecl()) return false;
2356 RL = &Info.Ctx.getASTRecordLayout(Derived);
2357 }
2358
Richard Smithd62306a2011-11-10 06:34:14 +00002359 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002360 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002361 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002362}
2363
Richard Smitha8105bc2012-01-06 16:39:00 +00002364static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002365 const CXXRecordDecl *DerivedDecl,
2366 const CXXBaseSpecifier *Base) {
2367 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2368
John McCalld7bca762012-05-01 00:38:49 +00002369 if (!Base->isVirtual())
2370 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002371
Richard Smitha8105bc2012-01-06 16:39:00 +00002372 SubobjectDesignator &D = Obj.Designator;
2373 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002374 return false;
2375
Richard Smitha8105bc2012-01-06 16:39:00 +00002376 // Extract most-derived object and corresponding type.
2377 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2378 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2379 return false;
2380
2381 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002382 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002383 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2384 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002385 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002386 return true;
2387}
2388
Richard Smith84401042013-06-03 05:03:02 +00002389static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2390 QualType Type, LValue &Result) {
2391 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2392 PathE = E->path_end();
2393 PathI != PathE; ++PathI) {
2394 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2395 *PathI))
2396 return false;
2397 Type = (*PathI)->getType();
2398 }
2399 return true;
2400}
2401
Richard Smithd62306a2011-11-10 06:34:14 +00002402/// Update LVal to refer to the given field, which must be a member of the type
2403/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002404static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002405 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002406 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002407 if (!RL) {
2408 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002409 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002410 }
Richard Smithd62306a2011-11-10 06:34:14 +00002411
2412 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002413 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002414 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002415 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002416}
2417
Richard Smith1b78b3d2012-01-25 22:15:11 +00002418/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002419static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002420 LValue &LVal,
2421 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002422 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002423 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002424 return false;
2425 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002426}
2427
Richard Smithd62306a2011-11-10 06:34:14 +00002428/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002429static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2430 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002431 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2432 // extension.
2433 if (Type->isVoidType() || Type->isFunctionType()) {
2434 Size = CharUnits::One();
2435 return true;
2436 }
2437
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002438 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002439 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002440 return false;
2441 }
2442
Richard Smithd62306a2011-11-10 06:34:14 +00002443 if (!Type->isConstantSizeType()) {
2444 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002445 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002446 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002447 return false;
2448 }
2449
2450 Size = Info.Ctx.getTypeSizeInChars(Type);
2451 return true;
2452}
2453
2454/// Update a pointer value to model pointer arithmetic.
2455/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002456/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002457/// \param LVal - The pointer value to be updated.
2458/// \param EltTy - The pointee type represented by LVal.
2459/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002460static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2461 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002462 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002463 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002464 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002465 return false;
2466
Yaxun Liu402804b2016-12-15 08:09:08 +00002467 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002468 return true;
2469}
2470
Richard Smithd6cc1982017-01-31 02:23:02 +00002471static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2472 LValue &LVal, QualType EltTy,
2473 int64_t Adjustment) {
2474 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2475 APSInt::get(Adjustment));
2476}
2477
Richard Smith66c96992012-02-18 22:04:06 +00002478/// Update an lvalue to refer to a component of a complex number.
2479/// \param Info - Information about the ongoing evaluation.
2480/// \param LVal - The lvalue to be updated.
2481/// \param EltTy - The complex number's component type.
2482/// \param Imag - False for the real component, true for the imaginary.
2483static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2484 LValue &LVal, QualType EltTy,
2485 bool Imag) {
2486 if (Imag) {
2487 CharUnits SizeOfComponent;
2488 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2489 return false;
2490 LVal.Offset += SizeOfComponent;
2491 }
2492 LVal.addComplex(Info, E, EltTy, Imag);
2493 return true;
2494}
2495
Faisal Vali051e3a22017-02-16 04:12:21 +00002496static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2497 QualType Type, const LValue &LVal,
2498 APValue &RVal);
2499
Richard Smith27908702011-10-24 17:54:18 +00002500/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002501///
2502/// \param Info Information about the ongoing evaluation.
2503/// \param E An expression to be used when printing diagnostics.
2504/// \param VD The variable whose initializer should be obtained.
2505/// \param Frame The frame in which the variable was created. Must be null
2506/// if this variable is not local to the evaluation.
2507/// \param Result Filled in with a pointer to the value of the variable.
2508static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2509 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002510 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002511
Richard Smith254a73d2011-10-28 22:34:42 +00002512 // If this is a parameter to an active constexpr function call, perform
2513 // argument substitution.
2514 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002515 // Assume arguments of a potential constant expression are unknown
2516 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002517 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002518 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002519 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002520 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002521 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002522 }
Richard Smith3229b742013-05-05 21:17:10 +00002523 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002524 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002525 }
Richard Smith27908702011-10-24 17:54:18 +00002526
Richard Smithd9f663b2013-04-22 15:31:51 +00002527 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002528 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002529 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2530 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002531 if (!Result) {
2532 // Assume variables referenced within a lambda's call operator that were
2533 // not declared within the call operator are captures and during checking
2534 // of a potential constant expression, assume they are unknown constant
2535 // expressions.
2536 assert(isLambdaCallOperator(Frame->Callee) &&
2537 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2538 "missing value for local variable");
2539 if (Info.checkingPotentialConstantExpression())
2540 return false;
2541 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002542 Info.FFDiag(E->getBeginLoc(),
2543 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002544 << "captures not currently allowed";
2545 return false;
2546 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002547 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002548 }
2549
Richard Smithd0b4dd62011-12-19 06:19:21 +00002550 // Dig out the initializer, and use the declaration which it's attached to.
2551 const Expr *Init = VD->getAnyInitializer(VD);
2552 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002553 // If we're checking a potential constant expression, the variable could be
2554 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002555 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002556 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002557 return false;
2558 }
2559
Richard Smithd62306a2011-11-10 06:34:14 +00002560 // If we're currently evaluating the initializer of this declaration, use that
2561 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002562 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002563 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002564 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002565 }
2566
Richard Smithcecf1842011-11-01 21:06:14 +00002567 // Never evaluate the initializer of a weak variable. We can't be sure that
2568 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002569 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002570 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002571 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002572 }
Richard Smithcecf1842011-11-01 21:06:14 +00002573
Richard Smithd0b4dd62011-12-19 06:19:21 +00002574 // Check that we can fold the initializer. In C++, we will have already done
2575 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002576 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002577 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002578 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002579 Notes.size() + 1) << VD;
2580 Info.Note(VD->getLocation(), diag::note_declared_at);
2581 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002582 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002583 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002584 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002585 Notes.size() + 1) << VD;
2586 Info.Note(VD->getLocation(), diag::note_declared_at);
2587 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002588 }
Richard Smith27908702011-10-24 17:54:18 +00002589
Richard Smith3229b742013-05-05 21:17:10 +00002590 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002591 return true;
Richard Smith27908702011-10-24 17:54:18 +00002592}
2593
Richard Smith11562c52011-10-28 17:51:58 +00002594static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002595 Qualifiers Quals = T.getQualifiers();
2596 return Quals.hasConst() && !Quals.hasVolatile();
2597}
2598
Richard Smithe97cbd72011-11-11 04:05:33 +00002599/// Get the base index of the given base class within an APValue representing
2600/// the given derived class.
2601static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2602 const CXXRecordDecl *Base) {
2603 Base = Base->getCanonicalDecl();
2604 unsigned Index = 0;
2605 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2606 E = Derived->bases_end(); I != E; ++I, ++Index) {
2607 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2608 return Index;
2609 }
2610
2611 llvm_unreachable("base class missing from derived class's bases list");
2612}
2613
Richard Smith3da88fa2013-04-26 14:36:30 +00002614/// Extract the value of a character from a string literal.
2615static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2616 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002617 // FIXME: Support MakeStringConstant
2618 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2619 std::string Str;
2620 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2621 assert(Index <= Str.size() && "Index too large");
2622 return APSInt::getUnsigned(Str.c_str()[Index]);
2623 }
2624
Alexey Bataevec474782014-10-09 08:45:04 +00002625 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2626 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002627 const StringLiteral *S = cast<StringLiteral>(Lit);
2628 const ConstantArrayType *CAT =
2629 Info.Ctx.getAsConstantArrayType(S->getType());
2630 assert(CAT && "string literal isn't an array");
2631 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002632 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002633
2634 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002635 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002636 if (Index < S->getLength())
2637 Value = S->getCodeUnit(Index);
2638 return Value;
2639}
2640
Richard Smith3da88fa2013-04-26 14:36:30 +00002641// Expand a string literal into an array of characters.
2642static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2643 APValue &Result) {
2644 const StringLiteral *S = cast<StringLiteral>(Lit);
2645 const ConstantArrayType *CAT =
2646 Info.Ctx.getAsConstantArrayType(S->getType());
2647 assert(CAT && "string literal isn't an array");
2648 QualType CharType = CAT->getElementType();
2649 assert(CharType->isIntegerType() && "unexpected character type");
2650
2651 unsigned Elts = CAT->getSize().getZExtValue();
2652 Result = APValue(APValue::UninitArray(),
2653 std::min(S->getLength(), Elts), Elts);
2654 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2655 CharType->isUnsignedIntegerType());
2656 if (Result.hasArrayFiller())
2657 Result.getArrayFiller() = APValue(Value);
2658 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2659 Value = S->getCodeUnit(I);
2660 Result.getArrayInitializedElt(I) = APValue(Value);
2661 }
2662}
2663
2664// Expand an array so that it has more than Index filled elements.
2665static void expandArray(APValue &Array, unsigned Index) {
2666 unsigned Size = Array.getArraySize();
2667 assert(Index < Size);
2668
2669 // Always at least double the number of elements for which we store a value.
2670 unsigned OldElts = Array.getArrayInitializedElts();
2671 unsigned NewElts = std::max(Index+1, OldElts * 2);
2672 NewElts = std::min(Size, std::max(NewElts, 8u));
2673
2674 // Copy the data across.
2675 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2676 for (unsigned I = 0; I != OldElts; ++I)
2677 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2678 for (unsigned I = OldElts; I != NewElts; ++I)
2679 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2680 if (NewValue.hasArrayFiller())
2681 NewValue.getArrayFiller() = Array.getArrayFiller();
2682 Array.swap(NewValue);
2683}
2684
Richard Smithb01fe402014-09-16 01:24:02 +00002685/// Determine whether a type would actually be read by an lvalue-to-rvalue
2686/// conversion. If it's of class type, we may assume that the copy operation
2687/// is trivial. Note that this is never true for a union type with fields
2688/// (because the copy always "reads" the active member) and always true for
2689/// a non-class type.
2690static bool isReadByLvalueToRvalueConversion(QualType T) {
2691 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2692 if (!RD || (RD->isUnion() && !RD->field_empty()))
2693 return true;
2694 if (RD->isEmpty())
2695 return false;
2696
2697 for (auto *Field : RD->fields())
2698 if (isReadByLvalueToRvalueConversion(Field->getType()))
2699 return true;
2700
2701 for (auto &BaseSpec : RD->bases())
2702 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2703 return true;
2704
2705 return false;
2706}
2707
2708/// Diagnose an attempt to read from any unreadable field within the specified
2709/// type, which might be a class type.
2710static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2711 QualType T) {
2712 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2713 if (!RD)
2714 return false;
2715
2716 if (!RD->hasMutableFields())
2717 return false;
2718
2719 for (auto *Field : RD->fields()) {
2720 // If we're actually going to read this field in some way, then it can't
2721 // be mutable. If we're in a union, then assigning to a mutable field
2722 // (even an empty one) can change the active member, so that's not OK.
2723 // FIXME: Add core issue number for the union case.
2724 if (Field->isMutable() &&
2725 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002726 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002727 Info.Note(Field->getLocation(), diag::note_declared_at);
2728 return true;
2729 }
2730
2731 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2732 return true;
2733 }
2734
2735 for (auto &BaseSpec : RD->bases())
2736 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2737 return true;
2738
2739 // All mutable fields were empty, and thus not actually read.
2740 return false;
2741}
2742
Richard Smith861b5b52013-05-07 23:34:45 +00002743/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002744enum AccessKinds {
2745 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002746 AK_Assign,
2747 AK_Increment,
2748 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002749};
2750
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002751namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002752/// A handle to a complete object (an object that is not a subobject of
2753/// another object).
2754struct CompleteObject {
2755 /// The value of the complete object.
2756 APValue *Value;
2757 /// The type of the complete object.
2758 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002759 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002760
Craig Topper36250ad2014-05-12 05:36:57 +00002761 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002762 CompleteObject(APValue *Value, QualType Type,
2763 bool LifetimeStartedInEvaluation)
2764 : Value(Value), Type(Type),
2765 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002766 assert(Value && "missing value for complete object");
2767 }
2768
Aaron Ballman67347662015-02-15 22:00:28 +00002769 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002770};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002771} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002772
Richard Smith3da88fa2013-04-26 14:36:30 +00002773/// Find the designated sub-object of an rvalue.
2774template<typename SubobjectHandler>
2775typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002776findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002777 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002778 if (Sub.Invalid)
2779 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002780 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002781 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002782 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002783 Info.FFDiag(E, Sub.isOnePastTheEnd()
2784 ? diag::note_constexpr_access_past_end
2785 : diag::note_constexpr_access_unsized_array)
2786 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002787 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002788 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002789 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002790 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002791
Richard Smith3229b742013-05-05 21:17:10 +00002792 APValue *O = Obj.Value;
2793 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002794 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002795 const bool MayReadMutableMembers =
2796 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002797
Richard Smithd62306a2011-11-10 06:34:14 +00002798 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002799 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2800 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002801 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002802 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002803 return handler.failed();
2804 }
2805
Richard Smith49ca8aa2013-08-06 07:09:20 +00002806 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002807 // If we are reading an object of class type, there may still be more
2808 // things we need to check: if there are any mutable subobjects, we
2809 // cannot perform this read. (This only happens when performing a trivial
2810 // copy or assignment.)
2811 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002812 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002813 return handler.failed();
2814
Richard Smith49ca8aa2013-08-06 07:09:20 +00002815 if (!handler.found(*O, ObjType))
2816 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002817
Richard Smith49ca8aa2013-08-06 07:09:20 +00002818 // If we modified a bit-field, truncate it to the right width.
2819 if (handler.AccessKind != AK_Read &&
2820 LastField && LastField->isBitField() &&
2821 !truncateBitfieldValue(Info, E, *O, LastField))
2822 return false;
2823
2824 return true;
2825 }
2826
Craig Topper36250ad2014-05-12 05:36:57 +00002827 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002828 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002829 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002830 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002831 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002832 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002833 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002834 // Note, it should not be possible to form a pointer with a valid
2835 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002836 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002837 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002838 << handler.AccessKind;
2839 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002840 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002841 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002842 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002843
2844 ObjType = CAT->getElementType();
2845
Richard Smith14a94132012-02-17 03:35:37 +00002846 // An array object is represented as either an Array APValue or as an
2847 // LValue which refers to a string literal.
2848 if (O->isLValue()) {
2849 assert(I == N - 1 && "extracting subobject of character?");
2850 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002851 if (handler.AccessKind != AK_Read)
2852 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2853 *O);
2854 else
2855 return handler.foundString(*O, ObjType, Index);
2856 }
2857
2858 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002859 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002860 else if (handler.AccessKind != AK_Read) {
2861 expandArray(*O, Index);
2862 O = &O->getArrayInitializedElt(Index);
2863 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002864 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002865 } else if (ObjType->isAnyComplexType()) {
2866 // Next subobject is a complex number.
2867 uint64_t Index = Sub.Entries[I].ArrayIndex;
2868 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002869 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002870 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002871 << handler.AccessKind;
2872 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002873 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002874 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002875 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002876
2877 bool WasConstQualified = ObjType.isConstQualified();
2878 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2879 if (WasConstQualified)
2880 ObjType.addConst();
2881
Richard Smith66c96992012-02-18 22:04:06 +00002882 assert(I == N - 1 && "extracting subobject of scalar?");
2883 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002884 return handler.found(Index ? O->getComplexIntImag()
2885 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002886 } else {
2887 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002888 return handler.found(Index ? O->getComplexFloatImag()
2889 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002890 }
Richard Smithd62306a2011-11-10 06:34:14 +00002891 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002892 // In C++14 onwards, it is permitted to read a mutable member whose
2893 // lifetime began within the evaluation.
2894 // FIXME: Should we also allow this in C++11?
2895 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2896 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002897 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002898 << Field;
2899 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002900 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002901 }
2902
Richard Smithd62306a2011-11-10 06:34:14 +00002903 // Next subobject is a class, struct or union field.
2904 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2905 if (RD->isUnion()) {
2906 const FieldDecl *UnionField = O->getUnionField();
2907 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002908 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002909 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002910 << handler.AccessKind << Field << !UnionField << UnionField;
2911 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002912 }
Richard Smithd62306a2011-11-10 06:34:14 +00002913 O = &O->getUnionValue();
2914 } else
2915 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002916
2917 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002918 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002919 if (WasConstQualified && !Field->isMutable())
2920 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002921
2922 if (ObjType.isVolatileQualified()) {
2923 if (Info.getLangOpts().CPlusPlus) {
2924 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002925 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002926 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002927 Info.Note(Field->getLocation(), diag::note_declared_at);
2928 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002929 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002930 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002931 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002932 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002933
2934 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002935 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002936 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002937 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2938 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2939 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002940
2941 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002942 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002943 if (WasConstQualified)
2944 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002945 }
2946 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002947}
2948
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002949namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002950struct ExtractSubobjectHandler {
2951 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002952 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002953
2954 static const AccessKinds AccessKind = AK_Read;
2955
2956 typedef bool result_type;
2957 bool failed() { return false; }
2958 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002959 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002960 return true;
2961 }
2962 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002963 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002964 return true;
2965 }
2966 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002967 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002968 return true;
2969 }
2970 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002971 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002972 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2973 return true;
2974 }
2975};
Richard Smith3229b742013-05-05 21:17:10 +00002976} // end anonymous namespace
2977
Richard Smith3da88fa2013-04-26 14:36:30 +00002978const AccessKinds ExtractSubobjectHandler::AccessKind;
2979
2980/// Extract the designated sub-object of an rvalue.
2981static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002982 const CompleteObject &Obj,
2983 const SubobjectDesignator &Sub,
2984 APValue &Result) {
2985 ExtractSubobjectHandler Handler = { Info, Result };
2986 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002987}
2988
Richard Smith3229b742013-05-05 21:17:10 +00002989namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002990struct ModifySubobjectHandler {
2991 EvalInfo &Info;
2992 APValue &NewVal;
2993 const Expr *E;
2994
2995 typedef bool result_type;
2996 static const AccessKinds AccessKind = AK_Assign;
2997
2998 bool checkConst(QualType QT) {
2999 // Assigning to a const object has undefined behavior.
3000 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003001 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003002 return false;
3003 }
3004 return true;
3005 }
3006
3007 bool failed() { return false; }
3008 bool found(APValue &Subobj, QualType SubobjType) {
3009 if (!checkConst(SubobjType))
3010 return false;
3011 // We've been given ownership of NewVal, so just swap it in.
3012 Subobj.swap(NewVal);
3013 return true;
3014 }
3015 bool found(APSInt &Value, QualType SubobjType) {
3016 if (!checkConst(SubobjType))
3017 return false;
3018 if (!NewVal.isInt()) {
3019 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003020 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003021 return false;
3022 }
3023 Value = NewVal.getInt();
3024 return true;
3025 }
3026 bool found(APFloat &Value, QualType SubobjType) {
3027 if (!checkConst(SubobjType))
3028 return false;
3029 Value = NewVal.getFloat();
3030 return true;
3031 }
3032 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3033 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
3034 }
3035};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003036} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003037
Richard Smith3229b742013-05-05 21:17:10 +00003038const AccessKinds ModifySubobjectHandler::AccessKind;
3039
Richard Smith3da88fa2013-04-26 14:36:30 +00003040/// Update the designated sub-object of an rvalue to the given value.
3041static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003042 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003043 const SubobjectDesignator &Sub,
3044 APValue &NewVal) {
3045 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003046 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003047}
3048
Richard Smith84f6dcf2012-02-02 01:16:57 +00003049/// Find the position where two subobject designators diverge, or equivalently
3050/// the length of the common initial subsequence.
3051static unsigned FindDesignatorMismatch(QualType ObjType,
3052 const SubobjectDesignator &A,
3053 const SubobjectDesignator &B,
3054 bool &WasArrayIndex) {
3055 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3056 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003057 if (!ObjType.isNull() &&
3058 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003059 // Next subobject is an array element.
3060 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3061 WasArrayIndex = true;
3062 return I;
3063 }
Richard Smith66c96992012-02-18 22:04:06 +00003064 if (ObjType->isAnyComplexType())
3065 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3066 else
3067 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003068 } else {
3069 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3070 WasArrayIndex = false;
3071 return I;
3072 }
3073 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3074 // Next subobject is a field.
3075 ObjType = FD->getType();
3076 else
3077 // Next subobject is a base class.
3078 ObjType = QualType();
3079 }
3080 }
3081 WasArrayIndex = false;
3082 return I;
3083}
3084
3085/// Determine whether the given subobject designators refer to elements of the
3086/// same array object.
3087static bool AreElementsOfSameArray(QualType ObjType,
3088 const SubobjectDesignator &A,
3089 const SubobjectDesignator &B) {
3090 if (A.Entries.size() != B.Entries.size())
3091 return false;
3092
George Burgess IVa51c4072015-10-16 01:49:01 +00003093 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003094 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3095 // A is a subobject of the array element.
3096 return false;
3097
3098 // If A (and B) designates an array element, the last entry will be the array
3099 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3100 // of length 1' case, and the entire path must match.
3101 bool WasArrayIndex;
3102 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3103 return CommonLength >= A.Entries.size() - IsArray;
3104}
3105
Richard Smith3229b742013-05-05 21:17:10 +00003106/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003107static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3108 AccessKinds AK, const LValue &LVal,
3109 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003110 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003111 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003112 return CompleteObject();
3113 }
3114
Craig Topper36250ad2014-05-12 05:36:57 +00003115 CallStackFrame *Frame = nullptr;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003116 if (LVal.getLValueCallIndex()) {
3117 Frame = Info.getCallFrame(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003118 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003119 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003120 << AK << LVal.Base.is<const ValueDecl*>();
3121 NoteLValueLocation(Info, LVal.Base);
3122 return CompleteObject();
3123 }
Richard Smith3229b742013-05-05 21:17:10 +00003124 }
3125
3126 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3127 // is not a constant expression (even if the object is non-volatile). We also
3128 // apply this rule to C++98, in order to conform to the expected 'volatile'
3129 // semantics.
3130 if (LValType.isVolatileQualified()) {
3131 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003132 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003133 << AK << LValType;
3134 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003135 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003136 return CompleteObject();
3137 }
3138
3139 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003140 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003141 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003142 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003143
3144 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3145 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3146 // In C++11, constexpr, non-volatile variables initialized with constant
3147 // expressions are constant expressions too. Inside constexpr functions,
3148 // parameters are constant expressions even if they're non-const.
3149 // In C++1y, objects local to a constant expression (those with a Frame) are
3150 // both readable and writable inside constant expressions.
3151 // In C, such things can also be folded, although they are not ICEs.
3152 const VarDecl *VD = dyn_cast<VarDecl>(D);
3153 if (VD) {
3154 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3155 VD = VDef;
3156 }
3157 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003158 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003159 return CompleteObject();
3160 }
3161
3162 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003163 if (BaseType.isVolatileQualified()) {
3164 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003165 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003166 << AK << 1 << VD;
3167 Info.Note(VD->getLocation(), diag::note_declared_at);
3168 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003169 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003170 }
3171 return CompleteObject();
3172 }
3173
3174 // Unless we're looking at a local variable or argument in a constexpr call,
3175 // the variable we're reading must be const.
3176 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003177 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003178 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3179 // OK, we can read and modify an object if we're in the process of
3180 // evaluating its initializer, because its lifetime began in this
3181 // evaluation.
3182 } else if (AK != AK_Read) {
3183 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003184 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003185 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003186 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003187 // OK, we can read this variable.
3188 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003189 // In OpenCL if a variable is in constant address space it is a const value.
3190 if (!(BaseType.isConstQualified() ||
3191 (Info.getLangOpts().OpenCL &&
3192 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003193 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003194 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003195 Info.Note(VD->getLocation(), diag::note_declared_at);
3196 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003197 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003198 }
3199 return CompleteObject();
3200 }
3201 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3202 // We support folding of const floating-point types, in order to make
3203 // static const data members of such types (supported as an extension)
3204 // more useful.
3205 if (Info.getLangOpts().CPlusPlus11) {
3206 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3207 Info.Note(VD->getLocation(), diag::note_declared_at);
3208 } else {
3209 Info.CCEDiag(E);
3210 }
George Burgess IVb5316982016-12-27 05:33:20 +00003211 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3212 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3213 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003214 } else {
3215 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003216 if (Info.checkingPotentialConstantExpression() &&
3217 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3218 // The definition of this variable could be constexpr. We can't
3219 // access it right now, but may be able to in future.
3220 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003221 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003222 Info.Note(VD->getLocation(), diag::note_declared_at);
3223 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003224 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003225 }
3226 return CompleteObject();
3227 }
3228 }
3229
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003230 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003231 return CompleteObject();
3232 } else {
3233 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3234
3235 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003236 if (const MaterializeTemporaryExpr *MTE =
3237 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3238 assert(MTE->getStorageDuration() == SD_Static &&
3239 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003240
Richard Smithe6c01442013-06-05 00:46:14 +00003241 // Per C++1y [expr.const]p2:
3242 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3243 // - a [...] glvalue of integral or enumeration type that refers to
3244 // a non-volatile const object [...]
3245 // [...]
3246 // - a [...] glvalue of literal type that refers to a non-volatile
3247 // object whose lifetime began within the evaluation of e.
3248 //
3249 // C++11 misses the 'began within the evaluation of e' check and
3250 // instead allows all temporaries, including things like:
3251 // int &&r = 1;
3252 // int x = ++r;
3253 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003254 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003255 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3256 const ValueDecl *ED = MTE->getExtendingDecl();
3257 if (!(BaseType.isConstQualified() &&
3258 BaseType->isIntegralOrEnumerationType()) &&
3259 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003260 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003261 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3262 return CompleteObject();
3263 }
3264
3265 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3266 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003267 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003268 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003269 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003270 return CompleteObject();
3271 }
3272 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003273 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003274 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003275 }
Richard Smith3229b742013-05-05 21:17:10 +00003276
3277 // Volatile temporary objects cannot be accessed in constant expressions.
3278 if (BaseType.isVolatileQualified()) {
3279 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003280 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003281 << AK << 0;
3282 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3283 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003284 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003285 }
3286 return CompleteObject();
3287 }
3288 }
3289
Richard Smith7525ff62013-05-09 07:14:00 +00003290 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003291 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003292 // object under construction.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003293 if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3294 LVal.getLValueCallIndex(),
3295 LVal.getLValueVersion())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003296 BaseType = Info.Ctx.getCanonicalType(BaseType);
3297 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003298 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003299 }
3300
Richard Smith9defb7d2018-02-21 03:38:30 +00003301 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003302 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003303 //
3304 // FIXME: Not all local state is mutable. Allow local constant subobjects
3305 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003306 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3307 Info.EvalStatus.HasSideEffects) ||
3308 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003309 return CompleteObject();
3310
Richard Smith9defb7d2018-02-21 03:38:30 +00003311 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003312}
3313
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003314/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003315/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3316/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003317///
3318/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003319/// \param Conv - The expression for which we are performing the conversion.
3320/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003321/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3322/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003323/// \param LVal - The glvalue on which we are attempting to perform this action.
3324/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003325static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003326 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003327 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003328 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003329 return false;
3330
Richard Smith3229b742013-05-05 21:17:10 +00003331 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003332 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003333 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003334 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3335 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3336 // initializer until now for such expressions. Such an expression can't be
3337 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003338 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003339 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003340 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003341 }
Richard Smith3229b742013-05-05 21:17:10 +00003342 APValue Lit;
3343 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3344 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003345 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003346 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003347 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003348 // We represent a string literal array as an lvalue pointing at the
3349 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003350 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003351 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smith9defb7d2018-02-21 03:38:30 +00003352 CompleteObject StrObj(&Str, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003353 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003354 }
Richard Smith11562c52011-10-28 17:51:58 +00003355 }
3356
Richard Smith3229b742013-05-05 21:17:10 +00003357 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3358 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003359}
3360
3361/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003362static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003363 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003364 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003365 return false;
3366
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003367 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003368 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003369 return false;
3370 }
3371
Richard Smith3229b742013-05-05 21:17:10 +00003372 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003373 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3374}
3375
3376namespace {
3377struct CompoundAssignSubobjectHandler {
3378 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003379 const Expr *E;
3380 QualType PromotedLHSType;
3381 BinaryOperatorKind Opcode;
3382 const APValue &RHS;
3383
3384 static const AccessKinds AccessKind = AK_Assign;
3385
3386 typedef bool result_type;
3387
3388 bool checkConst(QualType QT) {
3389 // Assigning to a const object has undefined behavior.
3390 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003391 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003392 return false;
3393 }
3394 return true;
3395 }
3396
3397 bool failed() { return false; }
3398 bool found(APValue &Subobj, QualType SubobjType) {
3399 switch (Subobj.getKind()) {
3400 case APValue::Int:
3401 return found(Subobj.getInt(), SubobjType);
3402 case APValue::Float:
3403 return found(Subobj.getFloat(), SubobjType);
3404 case APValue::ComplexInt:
3405 case APValue::ComplexFloat:
3406 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003407 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003408 return false;
3409 case APValue::LValue:
3410 return foundPointer(Subobj, SubobjType);
3411 default:
3412 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003413 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003414 return false;
3415 }
3416 }
3417 bool found(APSInt &Value, QualType SubobjType) {
3418 if (!checkConst(SubobjType))
3419 return false;
3420
3421 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3422 // We don't support compound assignment on integer-cast-to-pointer
3423 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003424 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003425 return false;
3426 }
3427
3428 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3429 SubobjType, Value);
3430 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3431 return false;
3432 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3433 return true;
3434 }
3435 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003436 return checkConst(SubobjType) &&
3437 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3438 Value) &&
3439 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3440 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003441 }
3442 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3443 if (!checkConst(SubobjType))
3444 return false;
3445
3446 QualType PointeeType;
3447 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3448 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003449
3450 if (PointeeType.isNull() || !RHS.isInt() ||
3451 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003452 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003453 return false;
3454 }
3455
Richard Smithd6cc1982017-01-31 02:23:02 +00003456 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003457 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003458 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003459
3460 LValue LVal;
3461 LVal.setFrom(Info.Ctx, Subobj);
3462 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3463 return false;
3464 LVal.moveInto(Subobj);
3465 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003466 }
3467 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3468 llvm_unreachable("shouldn't encounter string elements here");
3469 }
3470};
3471} // end anonymous namespace
3472
3473const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3474
3475/// Perform a compound assignment of LVal <op>= RVal.
3476static bool handleCompoundAssignment(
3477 EvalInfo &Info, const Expr *E,
3478 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3479 BinaryOperatorKind Opcode, const APValue &RVal) {
3480 if (LVal.Designator.Invalid)
3481 return false;
3482
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003483 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003484 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003485 return false;
3486 }
3487
3488 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3489 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3490 RVal };
3491 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3492}
3493
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003494namespace {
3495struct IncDecSubobjectHandler {
3496 EvalInfo &Info;
3497 const UnaryOperator *E;
3498 AccessKinds AccessKind;
3499 APValue *Old;
3500
Richard Smith243ef902013-05-05 23:31:59 +00003501 typedef bool result_type;
3502
3503 bool checkConst(QualType QT) {
3504 // Assigning to a const object has undefined behavior.
3505 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003506 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003507 return false;
3508 }
3509 return true;
3510 }
3511
3512 bool failed() { return false; }
3513 bool found(APValue &Subobj, QualType SubobjType) {
3514 // Stash the old value. Also clear Old, so we don't clobber it later
3515 // if we're post-incrementing a complex.
3516 if (Old) {
3517 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003518 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003519 }
3520
3521 switch (Subobj.getKind()) {
3522 case APValue::Int:
3523 return found(Subobj.getInt(), SubobjType);
3524 case APValue::Float:
3525 return found(Subobj.getFloat(), SubobjType);
3526 case APValue::ComplexInt:
3527 return found(Subobj.getComplexIntReal(),
3528 SubobjType->castAs<ComplexType>()->getElementType()
3529 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3530 case APValue::ComplexFloat:
3531 return found(Subobj.getComplexFloatReal(),
3532 SubobjType->castAs<ComplexType>()->getElementType()
3533 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3534 case APValue::LValue:
3535 return foundPointer(Subobj, SubobjType);
3536 default:
3537 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003538 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003539 return false;
3540 }
3541 }
3542 bool found(APSInt &Value, QualType SubobjType) {
3543 if (!checkConst(SubobjType))
3544 return false;
3545
3546 if (!SubobjType->isIntegerType()) {
3547 // We don't support increment / decrement on integer-cast-to-pointer
3548 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003549 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003550 return false;
3551 }
3552
3553 if (Old) *Old = APValue(Value);
3554
3555 // bool arithmetic promotes to int, and the conversion back to bool
3556 // doesn't reduce mod 2^n, so special-case it.
3557 if (SubobjType->isBooleanType()) {
3558 if (AccessKind == AK_Increment)
3559 Value = 1;
3560 else
3561 Value = !Value;
3562 return true;
3563 }
3564
3565 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003566 if (AccessKind == AK_Increment) {
3567 ++Value;
3568
3569 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3570 APSInt ActualValue(Value, /*IsUnsigned*/true);
3571 return HandleOverflow(Info, E, ActualValue, SubobjType);
3572 }
3573 } else {
3574 --Value;
3575
3576 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3577 unsigned BitWidth = Value.getBitWidth();
3578 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3579 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003580 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003581 }
3582 }
3583 return true;
3584 }
3585 bool found(APFloat &Value, QualType SubobjType) {
3586 if (!checkConst(SubobjType))
3587 return false;
3588
3589 if (Old) *Old = APValue(Value);
3590
3591 APFloat One(Value.getSemantics(), 1);
3592 if (AccessKind == AK_Increment)
3593 Value.add(One, APFloat::rmNearestTiesToEven);
3594 else
3595 Value.subtract(One, APFloat::rmNearestTiesToEven);
3596 return true;
3597 }
3598 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3599 if (!checkConst(SubobjType))
3600 return false;
3601
3602 QualType PointeeType;
3603 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3604 PointeeType = PT->getPointeeType();
3605 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003606 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003607 return false;
3608 }
3609
3610 LValue LVal;
3611 LVal.setFrom(Info.Ctx, Subobj);
3612 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3613 AccessKind == AK_Increment ? 1 : -1))
3614 return false;
3615 LVal.moveInto(Subobj);
3616 return true;
3617 }
3618 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3619 llvm_unreachable("shouldn't encounter string elements here");
3620 }
3621};
3622} // end anonymous namespace
3623
3624/// Perform an increment or decrement on LVal.
3625static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3626 QualType LValType, bool IsIncrement, APValue *Old) {
3627 if (LVal.Designator.Invalid)
3628 return false;
3629
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003630 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003631 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003632 return false;
3633 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003634
3635 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3636 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3637 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3638 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3639}
3640
Richard Smithe97cbd72011-11-11 04:05:33 +00003641/// Build an lvalue for the object argument of a member function call.
3642static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3643 LValue &This) {
3644 if (Object->getType()->isPointerType())
3645 return EvaluatePointer(Object, This, Info);
3646
3647 if (Object->isGLValue())
3648 return EvaluateLValue(Object, This, Info);
3649
Richard Smithd9f663b2013-04-22 15:31:51 +00003650 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003651 return EvaluateTemporary(Object, This, Info);
3652
Faisal Valie690b7a2016-07-02 22:34:24 +00003653 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003654 return false;
3655}
3656
3657/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3658/// lvalue referring to the result.
3659///
3660/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003661/// \param LV - An lvalue referring to the base of the member pointer.
3662/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003663/// \param IncludeMember - Specifies whether the member itself is included in
3664/// the resulting LValue subobject designator. This is not possible when
3665/// creating a bound member function.
3666/// \return The field or method declaration to which the member pointer refers,
3667/// or 0 if evaluation fails.
3668static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003669 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003670 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003671 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003672 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003673 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003674 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003675 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003676
3677 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3678 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003679 if (!MemPtr.getDecl()) {
3680 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003681 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003682 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003683 }
Richard Smith253c2a32012-01-27 01:14:48 +00003684
Richard Smith027bf112011-11-17 22:56:20 +00003685 if (MemPtr.isDerivedMember()) {
3686 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003687 // The end of the derived-to-base path for the base object must match the
3688 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003689 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003690 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003691 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003692 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003693 }
Richard Smith027bf112011-11-17 22:56:20 +00003694 unsigned PathLengthToMember =
3695 LV.Designator.Entries.size() - MemPtr.Path.size();
3696 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3697 const CXXRecordDecl *LVDecl = getAsBaseClass(
3698 LV.Designator.Entries[PathLengthToMember + I]);
3699 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003700 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003701 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003702 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003703 }
Richard Smith027bf112011-11-17 22:56:20 +00003704 }
3705
3706 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003707 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003708 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003709 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003710 } else if (!MemPtr.Path.empty()) {
3711 // Extend the LValue path with the member pointer's path.
3712 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3713 MemPtr.Path.size() + IncludeMember);
3714
3715 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003716 if (const PointerType *PT = LVType->getAs<PointerType>())
3717 LVType = PT->getPointeeType();
3718 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3719 assert(RD && "member pointer access on non-class-type expression");
3720 // The first class in the path is that of the lvalue.
3721 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3722 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003723 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003724 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003725 RD = Base;
3726 }
3727 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003728 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3729 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003730 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003731 }
3732
3733 // Add the member. Note that we cannot build bound member functions here.
3734 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003735 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003736 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003737 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003738 } else if (const IndirectFieldDecl *IFD =
3739 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003740 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003741 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003742 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003743 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003744 }
Richard Smith027bf112011-11-17 22:56:20 +00003745 }
3746
3747 return MemPtr.getDecl();
3748}
3749
Richard Smith84401042013-06-03 05:03:02 +00003750static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3751 const BinaryOperator *BO,
3752 LValue &LV,
3753 bool IncludeMember = true) {
3754 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3755
3756 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003757 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003758 MemberPtr MemPtr;
3759 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3760 }
Craig Topper36250ad2014-05-12 05:36:57 +00003761 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003762 }
3763
3764 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3765 BO->getRHS(), IncludeMember);
3766}
3767
Richard Smith027bf112011-11-17 22:56:20 +00003768/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3769/// the provided lvalue, which currently refers to the base object.
3770static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3771 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003772 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003773 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003774 return false;
3775
Richard Smitha8105bc2012-01-06 16:39:00 +00003776 QualType TargetQT = E->getType();
3777 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3778 TargetQT = PT->getPointeeType();
3779
3780 // Check this cast lands within the final derived-to-base subobject path.
3781 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003782 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003783 << D.MostDerivedType << TargetQT;
3784 return false;
3785 }
3786
Richard Smith027bf112011-11-17 22:56:20 +00003787 // Check the type of the final cast. We don't need to check the path,
3788 // since a cast can only be formed if the path is unique.
3789 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003790 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3791 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003792 if (NewEntriesSize == D.MostDerivedPathLength)
3793 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3794 else
Richard Smith027bf112011-11-17 22:56:20 +00003795 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003796 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003797 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003798 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003799 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003800 }
Richard Smith027bf112011-11-17 22:56:20 +00003801
3802 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003803 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003804}
3805
Mike Stump876387b2009-10-27 22:09:17 +00003806namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003807enum EvalStmtResult {
3808 /// Evaluation failed.
3809 ESR_Failed,
3810 /// Hit a 'return' statement.
3811 ESR_Returned,
3812 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003813 ESR_Succeeded,
3814 /// Hit a 'continue' statement.
3815 ESR_Continue,
3816 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003817 ESR_Break,
3818 /// Still scanning for 'case' or 'default' statement.
3819 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003820};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003821}
Richard Smith254a73d2011-10-28 22:34:42 +00003822
Richard Smith97fcf4b2016-08-14 23:15:52 +00003823static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3824 // We don't need to evaluate the initializer for a static local.
3825 if (!VD->hasLocalStorage())
3826 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003827
Richard Smith97fcf4b2016-08-14 23:15:52 +00003828 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003829 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00003830
Richard Smith97fcf4b2016-08-14 23:15:52 +00003831 const Expr *InitE = VD->getInit();
3832 if (!InitE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003833 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
3834 << false << VD->getType();
Richard Smith97fcf4b2016-08-14 23:15:52 +00003835 Val = APValue();
3836 return false;
3837 }
Richard Smith51f03172013-06-20 03:00:05 +00003838
Richard Smith97fcf4b2016-08-14 23:15:52 +00003839 if (InitE->isValueDependent())
3840 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003841
Richard Smith97fcf4b2016-08-14 23:15:52 +00003842 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3843 // Wipe out any partially-computed value, to allow tracking that this
3844 // evaluation failed.
3845 Val = APValue();
3846 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003847 }
3848
3849 return true;
3850}
3851
Richard Smith97fcf4b2016-08-14 23:15:52 +00003852static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3853 bool OK = true;
3854
3855 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3856 OK &= EvaluateVarDecl(Info, VD);
3857
3858 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3859 for (auto *BD : DD->bindings())
3860 if (auto *VD = BD->getHoldingVar())
3861 OK &= EvaluateDecl(Info, VD);
3862
3863 return OK;
3864}
3865
3866
Richard Smith4e18ca52013-05-06 05:56:11 +00003867/// Evaluate a condition (either a variable declaration or an expression).
3868static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3869 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003870 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003871 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3872 return false;
3873 return EvaluateAsBooleanCondition(Cond, Result, Info);
3874}
3875
Richard Smith89210072016-04-04 23:29:43 +00003876namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003877/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00003878/// statement should be stored.
3879struct StmtResult {
3880 /// The APValue that should be filled in with the returned value.
3881 APValue &Value;
3882 /// The location containing the result, if any (used to support RVO).
3883 const LValue *Slot;
3884};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003885
3886struct TempVersionRAII {
3887 CallStackFrame &Frame;
3888
3889 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3890 Frame.pushTempVersion();
3891 }
3892
3893 ~TempVersionRAII() {
3894 Frame.popTempVersion();
3895 }
3896};
3897
Richard Smith89210072016-04-04 23:29:43 +00003898}
Richard Smith52a980a2015-08-28 02:43:42 +00003899
3900static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003901 const Stmt *S,
3902 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003903
3904/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003905static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003906 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003907 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003908 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003909 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003910 case ESR_Break:
3911 return ESR_Succeeded;
3912 case ESR_Succeeded:
3913 case ESR_Continue:
3914 return ESR_Continue;
3915 case ESR_Failed:
3916 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003917 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003918 return ESR;
3919 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003920 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003921}
3922
Richard Smith496ddcf2013-05-12 17:32:42 +00003923/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003924static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003925 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003926 BlockScopeRAII Scope(Info);
3927
Richard Smith496ddcf2013-05-12 17:32:42 +00003928 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003929 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003930 {
3931 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003932 if (const Stmt *Init = SS->getInit()) {
3933 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3934 if (ESR != ESR_Succeeded)
3935 return ESR;
3936 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003937 if (SS->getConditionVariable() &&
3938 !EvaluateDecl(Info, SS->getConditionVariable()))
3939 return ESR_Failed;
3940 if (!EvaluateInteger(SS->getCond(), Value, Info))
3941 return ESR_Failed;
3942 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003943
3944 // Find the switch case corresponding to the value of the condition.
3945 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003946 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003947 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3948 SC = SC->getNextSwitchCase()) {
3949 if (isa<DefaultStmt>(SC)) {
3950 Found = SC;
3951 continue;
3952 }
3953
3954 const CaseStmt *CS = cast<CaseStmt>(SC);
3955 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3956 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3957 : LHS;
3958 if (LHS <= Value && Value <= RHS) {
3959 Found = SC;
3960 break;
3961 }
3962 }
3963
3964 if (!Found)
3965 return ESR_Succeeded;
3966
3967 // Search the switch body for the switch case and evaluate it from there.
3968 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3969 case ESR_Break:
3970 return ESR_Succeeded;
3971 case ESR_Succeeded:
3972 case ESR_Continue:
3973 case ESR_Failed:
3974 case ESR_Returned:
3975 return ESR;
3976 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003977 // This can only happen if the switch case is nested within a statement
3978 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003979 Info.FFDiag(Found->getBeginLoc(),
3980 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003981 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003982 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003983 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003984}
3985
Richard Smith254a73d2011-10-28 22:34:42 +00003986// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003987static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003988 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003989 if (!Info.nextStep(S))
3990 return ESR_Failed;
3991
Richard Smith496ddcf2013-05-12 17:32:42 +00003992 // If we're hunting down a 'case' or 'default' label, recurse through
3993 // substatements until we hit the label.
3994 if (Case) {
3995 // FIXME: We don't start the lifetime of objects whose initialization we
3996 // jump over. However, such objects must be of class type with a trivial
3997 // default constructor that initialize all subobjects, so must be empty,
3998 // so this almost never matters.
3999 switch (S->getStmtClass()) {
4000 case Stmt::CompoundStmtClass:
4001 // FIXME: Precompute which substatement of a compound statement we
4002 // would jump to, and go straight there rather than performing a
4003 // linear scan each time.
4004 case Stmt::LabelStmtClass:
4005 case Stmt::AttributedStmtClass:
4006 case Stmt::DoStmtClass:
4007 break;
4008
4009 case Stmt::CaseStmtClass:
4010 case Stmt::DefaultStmtClass:
4011 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004012 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004013 break;
4014
4015 case Stmt::IfStmtClass: {
4016 // FIXME: Precompute which side of an 'if' we would jump to, and go
4017 // straight there rather than scanning both sides.
4018 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004019
4020 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4021 // preceded by our switch label.
4022 BlockScopeRAII Scope(Info);
4023
Richard Smith496ddcf2013-05-12 17:32:42 +00004024 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4025 if (ESR != ESR_CaseNotFound || !IS->getElse())
4026 return ESR;
4027 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4028 }
4029
4030 case Stmt::WhileStmtClass: {
4031 EvalStmtResult ESR =
4032 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4033 if (ESR != ESR_Continue)
4034 return ESR;
4035 break;
4036 }
4037
4038 case Stmt::ForStmtClass: {
4039 const ForStmt *FS = cast<ForStmt>(S);
4040 EvalStmtResult ESR =
4041 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4042 if (ESR != ESR_Continue)
4043 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004044 if (FS->getInc()) {
4045 FullExpressionRAII IncScope(Info);
4046 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4047 return ESR_Failed;
4048 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004049 break;
4050 }
4051
4052 case Stmt::DeclStmtClass:
4053 // FIXME: If the variable has initialization that can't be jumped over,
4054 // bail out of any immediately-surrounding compound-statement too.
4055 default:
4056 return ESR_CaseNotFound;
4057 }
4058 }
4059
Richard Smith254a73d2011-10-28 22:34:42 +00004060 switch (S->getStmtClass()) {
4061 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004062 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004063 // Don't bother evaluating beyond an expression-statement which couldn't
4064 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004065 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004066 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004067 return ESR_Failed;
4068 return ESR_Succeeded;
4069 }
4070
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004071 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004072 return ESR_Failed;
4073
4074 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004075 return ESR_Succeeded;
4076
Richard Smithd9f663b2013-04-22 15:31:51 +00004077 case Stmt::DeclStmtClass: {
4078 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004079 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004080 // Each declaration initialization is its own full-expression.
4081 // FIXME: This isn't quite right; if we're performing aggregate
4082 // initialization, each braced subexpression is its own full-expression.
4083 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004084 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004085 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004086 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004087 return ESR_Succeeded;
4088 }
4089
Richard Smith357362d2011-12-13 06:39:58 +00004090 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004091 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004092 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004093 if (RetExpr &&
4094 !(Result.Slot
4095 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4096 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004097 return ESR_Failed;
4098 return ESR_Returned;
4099 }
Richard Smith254a73d2011-10-28 22:34:42 +00004100
4101 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004102 BlockScopeRAII Scope(Info);
4103
Richard Smith254a73d2011-10-28 22:34:42 +00004104 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004105 for (const auto *BI : CS->body()) {
4106 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004107 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004108 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004109 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004110 return ESR;
4111 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004112 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004113 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004114
4115 case Stmt::IfStmtClass: {
4116 const IfStmt *IS = cast<IfStmt>(S);
4117
4118 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004119 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004120 if (const Stmt *Init = IS->getInit()) {
4121 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4122 if (ESR != ESR_Succeeded)
4123 return ESR;
4124 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004125 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004126 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004127 return ESR_Failed;
4128
4129 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4130 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4131 if (ESR != ESR_Succeeded)
4132 return ESR;
4133 }
4134 return ESR_Succeeded;
4135 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004136
4137 case Stmt::WhileStmtClass: {
4138 const WhileStmt *WS = cast<WhileStmt>(S);
4139 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004140 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004141 bool Continue;
4142 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4143 Continue))
4144 return ESR_Failed;
4145 if (!Continue)
4146 break;
4147
4148 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4149 if (ESR != ESR_Continue)
4150 return ESR;
4151 }
4152 return ESR_Succeeded;
4153 }
4154
4155 case Stmt::DoStmtClass: {
4156 const DoStmt *DS = cast<DoStmt>(S);
4157 bool Continue;
4158 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004159 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004160 if (ESR != ESR_Continue)
4161 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004162 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004163
Richard Smith08d6a2c2013-07-24 07:11:57 +00004164 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004165 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4166 return ESR_Failed;
4167 } while (Continue);
4168 return ESR_Succeeded;
4169 }
4170
4171 case Stmt::ForStmtClass: {
4172 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004173 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004174 if (FS->getInit()) {
4175 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4176 if (ESR != ESR_Succeeded)
4177 return ESR;
4178 }
4179 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004180 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004181 bool Continue = true;
4182 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4183 FS->getCond(), Continue))
4184 return ESR_Failed;
4185 if (!Continue)
4186 break;
4187
4188 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4189 if (ESR != ESR_Continue)
4190 return ESR;
4191
Richard Smith08d6a2c2013-07-24 07:11:57 +00004192 if (FS->getInc()) {
4193 FullExpressionRAII IncScope(Info);
4194 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4195 return ESR_Failed;
4196 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004197 }
4198 return ESR_Succeeded;
4199 }
4200
Richard Smith896e0d72013-05-06 06:51:17 +00004201 case Stmt::CXXForRangeStmtClass: {
4202 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004203 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004204
Richard Smith8baa5002018-09-28 18:44:09 +00004205 // Evaluate the init-statement if present.
4206 if (FS->getInit()) {
4207 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4208 if (ESR != ESR_Succeeded)
4209 return ESR;
4210 }
4211
Richard Smith896e0d72013-05-06 06:51:17 +00004212 // Initialize the __range variable.
4213 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4214 if (ESR != ESR_Succeeded)
4215 return ESR;
4216
4217 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004218 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4219 if (ESR != ESR_Succeeded)
4220 return ESR;
4221 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004222 if (ESR != ESR_Succeeded)
4223 return ESR;
4224
4225 while (true) {
4226 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004227 {
4228 bool Continue = true;
4229 FullExpressionRAII CondExpr(Info);
4230 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4231 return ESR_Failed;
4232 if (!Continue)
4233 break;
4234 }
Richard Smith896e0d72013-05-06 06:51:17 +00004235
4236 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004237 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004238 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4239 if (ESR != ESR_Succeeded)
4240 return ESR;
4241
4242 // Loop body.
4243 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4244 if (ESR != ESR_Continue)
4245 return ESR;
4246
4247 // Increment: ++__begin
4248 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4249 return ESR_Failed;
4250 }
4251
4252 return ESR_Succeeded;
4253 }
4254
Richard Smith496ddcf2013-05-12 17:32:42 +00004255 case Stmt::SwitchStmtClass:
4256 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4257
Richard Smith4e18ca52013-05-06 05:56:11 +00004258 case Stmt::ContinueStmtClass:
4259 return ESR_Continue;
4260
4261 case Stmt::BreakStmtClass:
4262 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004263
4264 case Stmt::LabelStmtClass:
4265 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4266
4267 case Stmt::AttributedStmtClass:
4268 // As a general principle, C++11 attributes can be ignored without
4269 // any semantic impact.
4270 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4271 Case);
4272
4273 case Stmt::CaseStmtClass:
4274 case Stmt::DefaultStmtClass:
4275 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004276 }
4277}
4278
Richard Smithcc36f692011-12-22 02:22:31 +00004279/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4280/// default constructor. If so, we'll fold it whether or not it's marked as
4281/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4282/// so we need special handling.
4283static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004284 const CXXConstructorDecl *CD,
4285 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004286 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4287 return false;
4288
Richard Smith66e05fe2012-01-18 05:21:49 +00004289 // Value-initialization does not call a trivial default constructor, so such a
4290 // call is a core constant expression whether or not the constructor is
4291 // constexpr.
4292 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004293 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004294 // FIXME: If DiagDecl is an implicitly-declared special member function,
4295 // we should be much more explicit about why it's not constexpr.
4296 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4297 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4298 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004299 } else {
4300 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4301 }
4302 }
4303 return true;
4304}
4305
Richard Smith357362d2011-12-13 06:39:58 +00004306/// CheckConstexprFunction - Check that a function can be called in a constant
4307/// expression.
4308static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4309 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004310 const FunctionDecl *Definition,
4311 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004312 // Potential constant expressions can contain calls to declared, but not yet
4313 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004314 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004315 Declaration->isConstexpr())
4316 return false;
4317
James Y Knightc7d3e602018-10-05 17:49:48 +00004318 // Bail out if the function declaration itself is invalid. We will
4319 // have produced a relevant diagnostic while parsing it, so just
4320 // note the problematic sub-expression.
4321 if (Declaration->isInvalidDecl()) {
4322 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004323 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004324 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004325
Richard Smith357362d2011-12-13 06:39:58 +00004326 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004327 if (Definition && Definition->isConstexpr() &&
4328 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004329 return true;
4330
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004331 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004332 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004333
Richard Smith5179eb72016-06-28 19:03:57 +00004334 // If this function is not constexpr because it is an inherited
4335 // non-constexpr constructor, diagnose that directly.
4336 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4337 if (CD && CD->isInheritingConstructor()) {
4338 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004339 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004340 DiagDecl = CD = Inherited;
4341 }
4342
4343 // FIXME: If DiagDecl is an implicitly-declared special member function
4344 // or an inheriting constructor, we should be much more explicit about why
4345 // it's not constexpr.
4346 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004347 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004348 << CD->getInheritedConstructor().getConstructor()->getParent();
4349 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004350 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004351 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004352 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4353 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004354 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004355 }
4356 return false;
4357}
4358
Richard Smithbe6dd812014-11-19 21:27:17 +00004359/// Determine if a class has any fields that might need to be copied by a
4360/// trivial copy or move operation.
4361static bool hasFields(const CXXRecordDecl *RD) {
4362 if (!RD || RD->isEmpty())
4363 return false;
4364 for (auto *FD : RD->fields()) {
4365 if (FD->isUnnamedBitfield())
4366 continue;
4367 return true;
4368 }
4369 for (auto &Base : RD->bases())
4370 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4371 return true;
4372 return false;
4373}
4374
Richard Smithd62306a2011-11-10 06:34:14 +00004375namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004376typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004377}
4378
4379/// EvaluateArgs - Evaluate the arguments to a function call.
4380static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4381 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004382 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004383 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004384 I != E; ++I) {
4385 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4386 // If we're checking for a potential constant expression, evaluate all
4387 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004388 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004389 return false;
4390 Success = false;
4391 }
4392 }
4393 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004394}
4395
Richard Smith254a73d2011-10-28 22:34:42 +00004396/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004397static bool HandleFunctionCall(SourceLocation CallLoc,
4398 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004399 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004400 EvalInfo &Info, APValue &Result,
4401 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004402 ArgVector ArgValues(Args.size());
4403 if (!EvaluateArgs(Args, ArgValues, Info))
4404 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004405
Richard Smith253c2a32012-01-27 01:14:48 +00004406 if (!Info.CheckCallLimit(CallLoc))
4407 return false;
4408
4409 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004410
4411 // For a trivial copy or move assignment, perform an APValue copy. This is
4412 // essential for unions, where the operations performed by the assignment
4413 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004414 //
4415 // Skip this for non-union classes with no fields; in that case, the defaulted
4416 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004417 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004418 if (MD && MD->isDefaulted() &&
4419 (MD->getParent()->isUnion() ||
4420 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004421 assert(This &&
4422 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4423 LValue RHS;
4424 RHS.setFrom(Info.Ctx, ArgValues[0]);
4425 APValue RHSValue;
4426 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4427 RHS, RHSValue))
4428 return false;
4429 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4430 RHSValue))
4431 return false;
4432 This->moveInto(Result);
4433 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004434 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00004435 // We're in a lambda; determine the lambda capture field maps unless we're
4436 // just constexpr checking a lambda's call operator. constexpr checking is
4437 // done before the captures have been added to the closure object (unless
4438 // we're inferring constexpr-ness), so we don't have access to them in this
4439 // case. But since we don't need the captures to constexpr check, we can
4440 // just ignore them.
4441 if (!Info.checkingPotentialConstantExpression())
4442 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4443 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004444 }
4445
Richard Smith52a980a2015-08-28 02:43:42 +00004446 StmtResult Ret = {Result, ResultSlot};
4447 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004448 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004449 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004450 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004451 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004452 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004453 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004454}
4455
Richard Smithd62306a2011-11-10 06:34:14 +00004456/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004457static bool HandleConstructorCall(const Expr *E, const LValue &This,
4458 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004459 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004460 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004461 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004462 if (!Info.CheckCallLimit(CallLoc))
4463 return false;
4464
Richard Smith3607ffe2012-02-13 03:54:03 +00004465 const CXXRecordDecl *RD = Definition->getParent();
4466 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004467 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004468 return false;
4469 }
4470
Erik Pilkington42925492017-10-04 00:18:55 +00004471 EvalInfo::EvaluatingConstructorRAII EvalObj(
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004472 Info, {This.getLValueBase(),
4473 {This.getLValueCallIndex(), This.getLValueVersion()}});
Richard Smith5179eb72016-06-28 19:03:57 +00004474 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004475
Richard Smith52a980a2015-08-28 02:43:42 +00004476 // FIXME: Creating an APValue just to hold a nonexistent return value is
4477 // wasteful.
4478 APValue RetVal;
4479 StmtResult Ret = {RetVal, nullptr};
4480
Richard Smith5179eb72016-06-28 19:03:57 +00004481 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004482 if (Definition->isDelegatingConstructor()) {
4483 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004484 {
4485 FullExpressionRAII InitScope(Info);
4486 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4487 return false;
4488 }
Richard Smith52a980a2015-08-28 02:43:42 +00004489 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004490 }
4491
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004492 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004493 // essential for unions (or classes with anonymous union members), where the
4494 // operations performed by the constructor cannot be represented by
4495 // ctor-initializers.
4496 //
4497 // Skip this for empty non-union classes; we should not perform an
4498 // lvalue-to-rvalue conversion on them because their copy constructor does not
4499 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004500 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004501 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004502 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004503 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004504 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004505 return handleLValueToRValueConversion(
4506 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4507 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004508 }
4509
4510 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004511 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004512 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004513 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004514
John McCalld7bca762012-05-01 00:38:49 +00004515 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004516 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4517
Richard Smith08d6a2c2013-07-24 07:11:57 +00004518 // A scope for temporaries lifetime-extended by reference members.
4519 BlockScopeRAII LifetimeExtendedScope(Info);
4520
Richard Smith253c2a32012-01-27 01:14:48 +00004521 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004522 unsigned BasesSeen = 0;
4523#ifndef NDEBUG
4524 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4525#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004526 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004527 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004528 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004529 APValue *Value = &Result;
4530
4531 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004532 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004533 if (I->isBaseInitializer()) {
4534 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004535#ifndef NDEBUG
4536 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004537 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004538 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4539 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4540 "base class initializers not in expected order");
4541 ++BaseIt;
4542#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004543 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004544 BaseType->getAsCXXRecordDecl(), &Layout))
4545 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004546 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004547 } else if ((FD = I->getMember())) {
4548 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004549 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004550 if (RD->isUnion()) {
4551 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004552 Value = &Result.getUnionValue();
4553 } else {
4554 Value = &Result.getStructField(FD->getFieldIndex());
4555 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004556 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004557 // Walk the indirect field decl's chain to find the object to initialize,
4558 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004559 auto IndirectFieldChain = IFD->chain();
4560 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004561 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004562 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4563 // Switch the union field if it differs. This happens if we had
4564 // preceding zero-initialization, and we're now initializing a union
4565 // subobject other than the first.
4566 // FIXME: In this case, the values of the other subobjects are
4567 // specified, since zero-initialization sets all padding bits to zero.
4568 if (Value->isUninit() ||
4569 (Value->isUnion() && Value->getUnionField() != FD)) {
4570 if (CD->isUnion())
4571 *Value = APValue(FD);
4572 else
4573 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004574 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004575 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004576 // Store Subobject as its parent before updating it for the last element
4577 // in the chain.
4578 if (C == IndirectFieldChain.back())
4579 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004580 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004581 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004582 if (CD->isUnion())
4583 Value = &Value->getUnionValue();
4584 else
4585 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004586 }
Richard Smithd62306a2011-11-10 06:34:14 +00004587 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004588 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004589 }
Richard Smith253c2a32012-01-27 01:14:48 +00004590
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004591 // Need to override This for implicit field initializers as in this case
4592 // This refers to innermost anonymous struct/union containing initializer,
4593 // not to currently constructed class.
4594 const Expr *Init = I->getInit();
4595 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4596 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004597 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004598 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4599 (FD && FD->isBitField() &&
4600 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004601 // If we're checking for a potential constant expression, evaluate all
4602 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004603 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004604 return false;
4605 Success = false;
4606 }
Richard Smithd62306a2011-11-10 06:34:14 +00004607 }
4608
Richard Smithd9f663b2013-04-22 15:31:51 +00004609 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004610 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004611}
4612
Richard Smith5179eb72016-06-28 19:03:57 +00004613static bool HandleConstructorCall(const Expr *E, const LValue &This,
4614 ArrayRef<const Expr*> Args,
4615 const CXXConstructorDecl *Definition,
4616 EvalInfo &Info, APValue &Result) {
4617 ArgVector ArgValues(Args.size());
4618 if (!EvaluateArgs(Args, ArgValues, Info))
4619 return false;
4620
4621 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4622 Info, Result);
4623}
4624
Eli Friedman9a156e52008-11-12 09:44:48 +00004625//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004626// Generic Evaluation
4627//===----------------------------------------------------------------------===//
4628namespace {
4629
Aaron Ballman68af21c2014-01-03 19:26:43 +00004630template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004631class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004632 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004633private:
Richard Smith52a980a2015-08-28 02:43:42 +00004634 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004635 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004636 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004637 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004638 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004639 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004640 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004641
Richard Smith17100ba2012-02-16 02:46:34 +00004642 // Check whether a conditional operator with a non-constant condition is a
4643 // potential constant expression. If neither arm is a potential constant
4644 // expression, then the conditional operator is not either.
4645 template<typename ConditionalOperator>
4646 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004647 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004648
4649 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004650 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004651 {
Richard Smith17100ba2012-02-16 02:46:34 +00004652 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004653 StmtVisitorTy::Visit(E->getFalseExpr());
4654 if (Diag.empty())
4655 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004656 }
Richard Smith17100ba2012-02-16 02:46:34 +00004657
George Burgess IV8c892b52016-05-25 22:31:54 +00004658 {
4659 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004660 Diag.clear();
4661 StmtVisitorTy::Visit(E->getTrueExpr());
4662 if (Diag.empty())
4663 return;
4664 }
4665
4666 Error(E, diag::note_constexpr_conditional_never_const);
4667 }
4668
4669
4670 template<typename ConditionalOperator>
4671 bool HandleConditionalOperator(const ConditionalOperator *E) {
4672 bool BoolResult;
4673 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004674 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004675 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004676 return false;
4677 }
4678 if (Info.noteFailure()) {
4679 StmtVisitorTy::Visit(E->getTrueExpr());
4680 StmtVisitorTy::Visit(E->getFalseExpr());
4681 }
Richard Smith17100ba2012-02-16 02:46:34 +00004682 return false;
4683 }
4684
4685 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4686 return StmtVisitorTy::Visit(EvalExpr);
4687 }
4688
Peter Collingbournee9200682011-05-13 03:29:01 +00004689protected:
4690 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004691 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004692 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4693
Richard Smith92b1ce02011-12-12 09:28:41 +00004694 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004695 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004696 }
4697
Aaron Ballman68af21c2014-01-03 19:26:43 +00004698 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004699
4700public:
4701 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4702
4703 EvalInfo &getEvalInfo() { return Info; }
4704
Richard Smithf57d8cb2011-12-09 22:58:01 +00004705 /// Report an evaluation error. This should only be called when an error is
4706 /// first discovered. When propagating an error, just return false.
4707 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004708 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004709 return false;
4710 }
4711 bool Error(const Expr *E) {
4712 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4713 }
4714
Aaron Ballman68af21c2014-01-03 19:26:43 +00004715 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004716 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004717 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004718 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004719 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004720 }
4721
Aaron Ballman68af21c2014-01-03 19:26:43 +00004722 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004723 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004724 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004725 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004726 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004727 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004728 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004729 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004730 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004731 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004732 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004733 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004734 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4735 TempVersionRAII RAII(*Info.CurrentCall);
4736 return StmtVisitorTy::Visit(E->getExpr());
4737 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004738 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004739 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00004740 // The initializer may not have been parsed yet, or might be erroneous.
4741 if (!E->getExpr())
4742 return Error(E);
4743 return StmtVisitorTy::Visit(E->getExpr());
4744 }
Richard Smith5894a912011-12-19 22:12:41 +00004745 // We cannot create any objects for which cleanups are required, so there is
4746 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004747 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004748 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004749
Aaron Ballman68af21c2014-01-03 19:26:43 +00004750 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004751 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4752 return static_cast<Derived*>(this)->VisitCastExpr(E);
4753 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004754 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004755 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4756 return static_cast<Derived*>(this)->VisitCastExpr(E);
4757 }
4758
Aaron Ballman68af21c2014-01-03 19:26:43 +00004759 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004760 switch (E->getOpcode()) {
4761 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004762 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004763
4764 case BO_Comma:
4765 VisitIgnoredValue(E->getLHS());
4766 return StmtVisitorTy::Visit(E->getRHS());
4767
4768 case BO_PtrMemD:
4769 case BO_PtrMemI: {
4770 LValue Obj;
4771 if (!HandleMemberPointerAccess(Info, E, Obj))
4772 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004773 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004774 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004775 return false;
4776 return DerivedSuccess(Result, E);
4777 }
4778 }
4779 }
4780
Aaron Ballman68af21c2014-01-03 19:26:43 +00004781 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004782 // Evaluate and cache the common expression. We treat it as a temporary,
4783 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004784 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004785 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004786 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004787
Richard Smith17100ba2012-02-16 02:46:34 +00004788 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004789 }
4790
Aaron Ballman68af21c2014-01-03 19:26:43 +00004791 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004792 bool IsBcpCall = false;
4793 // If the condition (ignoring parens) is a __builtin_constant_p call,
4794 // the result is a constant expression if it can be folded without
4795 // side-effects. This is an important GNU extension. See GCC PR38377
4796 // for discussion.
4797 if (const CallExpr *CallCE =
4798 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004799 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004800 IsBcpCall = true;
4801
4802 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4803 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004804 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004805 return false;
4806
Richard Smith6d4c6582013-11-05 22:18:15 +00004807 FoldConstant Fold(Info, IsBcpCall);
4808 if (!HandleConditionalOperator(E)) {
4809 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004810 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004811 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004812
4813 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004814 }
4815
Aaron Ballman68af21c2014-01-03 19:26:43 +00004816 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004817 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00004818 return DerivedSuccess(*Value, E);
4819
4820 const Expr *Source = E->getSourceExpr();
4821 if (!Source)
4822 return Error(E);
4823 if (Source == E) { // sanity checking.
4824 assert(0 && "OpaqueValueExpr recursively refers to itself");
4825 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004826 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004827 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004828 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004829
Aaron Ballman68af21c2014-01-03 19:26:43 +00004830 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004831 APValue Result;
4832 if (!handleCallExpr(E, Result, nullptr))
4833 return false;
4834 return DerivedSuccess(Result, E);
4835 }
4836
4837 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004838 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004839 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004840 QualType CalleeType = Callee->getType();
4841
Craig Topper36250ad2014-05-12 05:36:57 +00004842 const FunctionDecl *FD = nullptr;
4843 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004844 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004845 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004846
Richard Smithe97cbd72011-11-11 04:05:33 +00004847 // Extract function decl and 'this' pointer from the callee.
4848 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004849 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004850 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4851 // Explicit bound member calls, such as x.f() or p->g();
4852 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004853 return false;
4854 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004855 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004856 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004857 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4858 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004859 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4860 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004861 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004862 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004863 return Error(Callee);
4864
4865 FD = dyn_cast<FunctionDecl>(Member);
4866 if (!FD)
4867 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004868 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004869 LValue Call;
4870 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004871 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004872
Richard Smitha8105bc2012-01-06 16:39:00 +00004873 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004874 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004875 FD = dyn_cast_or_null<FunctionDecl>(
4876 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004877 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004878 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004879 // Don't call function pointers which have been cast to some other type.
4880 // Per DR (no number yet), the caller and callee can differ in noexcept.
4881 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4882 CalleeType->getPointeeType(), FD->getType())) {
4883 return Error(E);
4884 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004885
4886 // Overloaded operator calls to member functions are represented as normal
4887 // calls with '*this' as the first argument.
4888 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4889 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004890 // FIXME: When selecting an implicit conversion for an overloaded
4891 // operator delete, we sometimes try to evaluate calls to conversion
4892 // operators without a 'this' parameter!
4893 if (Args.empty())
4894 return Error(E);
4895
Nick Lewycky13073a62017-06-12 21:15:44 +00004896 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004897 return false;
4898 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004899 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00004900 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004901 // Map the static invoker for the lambda back to the call operator.
4902 // Conveniently, we don't have to slice out the 'this' argument (as is
4903 // being done for the non-static case), since a static member function
4904 // doesn't have an implicit argument passed in.
4905 const CXXRecordDecl *ClosureClass = MD->getParent();
4906 assert(
4907 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4908 "Number of captures must be zero for conversion to function-ptr");
4909
4910 const CXXMethodDecl *LambdaCallOp =
4911 ClosureClass->getLambdaCallOperator();
4912
4913 // Set 'FD', the function that will be called below, to the call
4914 // operator. If the closure object represents a generic lambda, find
4915 // the corresponding specialization of the call operator.
4916
4917 if (ClosureClass->isGenericLambda()) {
4918 assert(MD->isFunctionTemplateSpecialization() &&
4919 "A generic lambda's static-invoker function must be a "
4920 "template specialization");
4921 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4922 FunctionTemplateDecl *CallOpTemplate =
4923 LambdaCallOp->getDescribedFunctionTemplate();
4924 void *InsertPos = nullptr;
4925 FunctionDecl *CorrespondingCallOpSpecialization =
4926 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4927 assert(CorrespondingCallOpSpecialization &&
4928 "We must always have a function call operator specialization "
4929 "that corresponds to our static invoker specialization");
4930 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4931 } else
4932 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004933 }
4934
Fangrui Song6907ce22018-07-30 19:24:48 +00004935
Richard Smithe97cbd72011-11-11 04:05:33 +00004936 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004937 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004938
Richard Smith47b34932012-02-01 02:39:43 +00004939 if (This && !This->checkSubobject(Info, E, CSK_This))
4940 return false;
4941
Richard Smith3607ffe2012-02-13 03:54:03 +00004942 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4943 // calls to such functions in constant expressions.
4944 if (This && !HasQualifier &&
4945 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4946 return Error(E, diag::note_constexpr_virtual_call);
4947
Craig Topper36250ad2014-05-12 05:36:57 +00004948 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004949 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004950
Nick Lewycky13073a62017-06-12 21:15:44 +00004951 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4952 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004953 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004954 return false;
4955
Richard Smith52a980a2015-08-28 02:43:42 +00004956 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004957 }
4958
Aaron Ballman68af21c2014-01-03 19:26:43 +00004959 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004960 return StmtVisitorTy::Visit(E->getInitializer());
4961 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004962 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004963 if (E->getNumInits() == 0)
4964 return DerivedZeroInitialization(E);
4965 if (E->getNumInits() == 1)
4966 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004967 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004968 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004969 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004970 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004971 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004972 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004973 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004974 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004975 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004976 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004977 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004978
Richard Smithd62306a2011-11-10 06:34:14 +00004979 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004980 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004981 assert(!E->isArrow() && "missing call to bound member function?");
4982
Richard Smith2e312c82012-03-03 22:46:17 +00004983 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004984 if (!Evaluate(Val, Info, E->getBase()))
4985 return false;
4986
4987 QualType BaseTy = E->getBase()->getType();
4988
4989 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004990 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004991 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004992 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004993 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4994
Richard Smith9defb7d2018-02-21 03:38:30 +00004995 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00004996 SubobjectDesignator Designator(BaseTy);
4997 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004998
Richard Smith3229b742013-05-05 21:17:10 +00004999 APValue Result;
5000 return extractSubobject(Info, E, Obj, Designator, Result) &&
5001 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00005002 }
5003
Aaron Ballman68af21c2014-01-03 19:26:43 +00005004 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005005 switch (E->getCastKind()) {
5006 default:
5007 break;
5008
Richard Smitha23ab512013-05-23 00:30:41 +00005009 case CK_AtomicToNonAtomic: {
5010 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00005011 // This does not need to be done in place even for class/array types:
5012 // atomic-to-non-atomic conversion implies copying the object
5013 // representation.
5014 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00005015 return false;
5016 return DerivedSuccess(AtomicVal, E);
5017 }
5018
Richard Smith11562c52011-10-28 17:51:58 +00005019 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00005020 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00005021 return StmtVisitorTy::Visit(E->getSubExpr());
5022
5023 case CK_LValueToRValue: {
5024 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005025 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5026 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005027 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00005028 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00005029 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00005030 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005031 return false;
5032 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00005033 }
5034 }
5035
Richard Smithf57d8cb2011-12-09 22:58:01 +00005036 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005037 }
5038
Aaron Ballman68af21c2014-01-03 19:26:43 +00005039 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005040 return VisitUnaryPostIncDec(UO);
5041 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005042 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005043 return VisitUnaryPostIncDec(UO);
5044 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005045 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005046 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005047 return Error(UO);
5048
5049 LValue LVal;
5050 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5051 return false;
5052 APValue RVal;
5053 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5054 UO->isIncrementOp(), &RVal))
5055 return false;
5056 return DerivedSuccess(RVal, UO);
5057 }
5058
Aaron Ballman68af21c2014-01-03 19:26:43 +00005059 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00005060 // We will have checked the full-expressions inside the statement expression
5061 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00005062 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00005063 return Error(E);
5064
Richard Smith08d6a2c2013-07-24 07:11:57 +00005065 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00005066 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005067 if (CS->body_empty())
5068 return true;
5069
Richard Smith51f03172013-06-20 03:00:05 +00005070 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5071 BE = CS->body_end();
5072 /**/; ++BI) {
5073 if (BI + 1 == BE) {
5074 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5075 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005076 Info.FFDiag((*BI)->getBeginLoc(),
5077 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005078 return false;
5079 }
5080 return this->Visit(FinalExpr);
5081 }
5082
5083 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00005084 StmtResult Result = { ReturnValue, nullptr };
5085 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00005086 if (ESR != ESR_Succeeded) {
5087 // FIXME: If the statement-expression terminated due to 'return',
5088 // 'break', or 'continue', it would be nice to propagate that to
5089 // the outer statement evaluation rather than bailing out.
5090 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005091 Info.FFDiag((*BI)->getBeginLoc(),
5092 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005093 return false;
5094 }
5095 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005096
5097 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00005098 }
5099
Richard Smith4a678122011-10-24 18:44:57 +00005100 /// Visit a value which is evaluated, but whose value is ignored.
5101 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00005102 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00005103 }
David Majnemere9807b22016-02-26 04:23:19 +00005104
5105 /// Potentially visit a MemberExpr's base expression.
5106 void VisitIgnoredBaseExpression(const Expr *E) {
5107 // While MSVC doesn't evaluate the base expression, it does diagnose the
5108 // presence of side-effecting behavior.
5109 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5110 return;
5111 VisitIgnoredValue(E);
5112 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005113};
5114
Eric Fiselier0683c0e2018-05-07 21:07:10 +00005115} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00005116
5117//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005118// Common base class for lvalue and temporary evaluation.
5119//===----------------------------------------------------------------------===//
5120namespace {
5121template<class Derived>
5122class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005123 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00005124protected:
5125 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005126 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005127 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005128 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005129
5130 bool Success(APValue::LValueBase B) {
5131 Result.set(B);
5132 return true;
5133 }
5134
George Burgess IVf9013bf2017-02-10 22:52:29 +00005135 bool evaluatePointer(const Expr *E, LValue &Result) {
5136 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5137 }
5138
Richard Smith027bf112011-11-17 22:56:20 +00005139public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005140 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5141 : ExprEvaluatorBaseTy(Info), Result(Result),
5142 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005143
Richard Smith2e312c82012-03-03 22:46:17 +00005144 bool Success(const APValue &V, const Expr *E) {
5145 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005146 return true;
5147 }
Richard Smith027bf112011-11-17 22:56:20 +00005148
Richard Smith027bf112011-11-17 22:56:20 +00005149 bool VisitMemberExpr(const MemberExpr *E) {
5150 // Handle non-static data members.
5151 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005152 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005153 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005154 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005155 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005156 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005157 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005158 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005159 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005160 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005161 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005162 BaseTy = E->getBase()->getType();
5163 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005164 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005165 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005166 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005167 Result.setInvalid(E);
5168 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005169 }
Richard Smith027bf112011-11-17 22:56:20 +00005170
Richard Smith1b78b3d2012-01-25 22:15:11 +00005171 const ValueDecl *MD = E->getMemberDecl();
5172 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5173 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5174 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5175 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005176 if (!HandleLValueMember(this->Info, E, Result, FD))
5177 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005178 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005179 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5180 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005181 } else
5182 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005183
Richard Smith1b78b3d2012-01-25 22:15:11 +00005184 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005185 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005186 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005187 RefValue))
5188 return false;
5189 return Success(RefValue, E);
5190 }
5191 return true;
5192 }
5193
5194 bool VisitBinaryOperator(const BinaryOperator *E) {
5195 switch (E->getOpcode()) {
5196 default:
5197 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5198
5199 case BO_PtrMemD:
5200 case BO_PtrMemI:
5201 return HandleMemberPointerAccess(this->Info, E, Result);
5202 }
5203 }
5204
5205 bool VisitCastExpr(const CastExpr *E) {
5206 switch (E->getCastKind()) {
5207 default:
5208 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5209
5210 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005211 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005212 if (!this->Visit(E->getSubExpr()))
5213 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005214
5215 // Now figure out the necessary offset to add to the base LV to get from
5216 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005217 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5218 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005219 }
5220 }
5221};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005222}
Richard Smith027bf112011-11-17 22:56:20 +00005223
5224//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005225// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005226//
5227// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5228// function designators (in C), decl references to void objects (in C), and
5229// temporaries (if building with -Wno-address-of-temporary).
5230//
5231// LValue evaluation produces values comprising a base expression of one of the
5232// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005233// - Declarations
5234// * VarDecl
5235// * FunctionDecl
5236// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005237// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005238// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005239// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005240// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005241// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005242// * ObjCEncodeExpr
5243// * AddrLabelExpr
5244// * BlockExpr
5245// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005246// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005247// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005248// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005249// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5250// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005251// * A MaterializeTemporaryExpr that has static storage duration, with no
5252// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005253// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005254//===----------------------------------------------------------------------===//
5255namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005256class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005257 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005258public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005259 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5260 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005261
Richard Smith11562c52011-10-28 17:51:58 +00005262 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005263 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005264
Peter Collingbournee9200682011-05-13 03:29:01 +00005265 bool VisitDeclRefExpr(const DeclRefExpr *E);
5266 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005267 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005268 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5269 bool VisitMemberExpr(const MemberExpr *E);
5270 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5271 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005272 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005273 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005274 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5275 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005276 bool VisitUnaryReal(const UnaryOperator *E);
5277 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005278 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5279 return VisitUnaryPreIncDec(UO);
5280 }
5281 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5282 return VisitUnaryPreIncDec(UO);
5283 }
Richard Smith3229b742013-05-05 21:17:10 +00005284 bool VisitBinAssign(const BinaryOperator *BO);
5285 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005286
Peter Collingbournee9200682011-05-13 03:29:01 +00005287 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005288 switch (E->getCastKind()) {
5289 default:
Richard Smith027bf112011-11-17 22:56:20 +00005290 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005291
Eli Friedmance3e02a2011-10-11 00:13:24 +00005292 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005293 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005294 if (!Visit(E->getSubExpr()))
5295 return false;
5296 Result.Designator.setInvalid();
5297 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005298
Richard Smith027bf112011-11-17 22:56:20 +00005299 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005300 if (!Visit(E->getSubExpr()))
5301 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005302 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005303 }
5304 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005305};
5306} // end anonymous namespace
5307
Richard Smith11562c52011-10-28 17:51:58 +00005308/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005309/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005310/// * function designators in C, and
5311/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005312/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005313static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5314 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005315 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005316 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005317 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005318}
5319
Peter Collingbournee9200682011-05-13 03:29:01 +00005320bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005321 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005322 return Success(FD);
5323 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005324 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005325 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005326 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005327 return Error(E);
5328}
Richard Smith733237d2011-10-24 23:14:33 +00005329
Faisal Vali0528a312016-11-13 06:09:16 +00005330
Richard Smith11562c52011-10-28 17:51:58 +00005331bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005332
5333 // If we are within a lambda's call operator, check whether the 'VD' referred
5334 // to within 'E' actually represents a lambda-capture that maps to a
5335 // data-member/field within the closure object, and if so, evaluate to the
5336 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00005337 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5338 isa<DeclRefExpr>(E) &&
5339 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5340 // We don't always have a complete capture-map when checking or inferring if
5341 // the function call operator meets the requirements of a constexpr function
5342 // - but we don't need to evaluate the captures to determine constexprness
5343 // (dcl.constexpr C++17).
5344 if (Info.checkingPotentialConstantExpression())
5345 return false;
5346
Faisal Vali051e3a22017-02-16 04:12:21 +00005347 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005348 // Start with 'Result' referring to the complete closure object...
5349 Result = *Info.CurrentCall->This;
5350 // ... then update it to refer to the field of the closure object
5351 // that represents the capture.
5352 if (!HandleLValueMember(Info, E, Result, FD))
5353 return false;
5354 // And if the field is of reference type, update 'Result' to refer to what
5355 // the field refers to.
5356 if (FD->getType()->isReferenceType()) {
5357 APValue RVal;
5358 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5359 RVal))
5360 return false;
5361 Result.setFrom(Info.Ctx, RVal);
5362 }
5363 return true;
5364 }
5365 }
Craig Topper36250ad2014-05-12 05:36:57 +00005366 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005367 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5368 // Only if a local variable was declared in the function currently being
5369 // evaluated, do we expect to be able to find its value in the current
5370 // frame. (Otherwise it was likely declared in an enclosing context and
5371 // could either have a valid evaluatable value (for e.g. a constexpr
5372 // variable) or be ill-formed (and trigger an appropriate evaluation
5373 // diagnostic)).
5374 if (Info.CurrentCall->Callee &&
5375 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5376 Frame = Info.CurrentCall;
5377 }
5378 }
Richard Smith3229b742013-05-05 21:17:10 +00005379
Richard Smithfec09922011-11-01 16:57:24 +00005380 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005381 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005382 Result.set({VD, Frame->Index,
5383 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00005384 return true;
5385 }
Richard Smithce40ad62011-11-12 22:28:03 +00005386 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005387 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005388
Richard Smith3229b742013-05-05 21:17:10 +00005389 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005390 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005391 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005392 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005393 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005394 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005395 return false;
5396 }
Richard Smith3229b742013-05-05 21:17:10 +00005397 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005398}
5399
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005400bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5401 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005402 // Walk through the expression to find the materialized temporary itself.
5403 SmallVector<const Expr *, 2> CommaLHSs;
5404 SmallVector<SubobjectAdjustment, 2> Adjustments;
5405 const Expr *Inner = E->GetTemporaryExpr()->
5406 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005407
Richard Smith84401042013-06-03 05:03:02 +00005408 // If we passed any comma operators, evaluate their LHSs.
5409 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5410 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5411 return false;
5412
Richard Smithe6c01442013-06-05 00:46:14 +00005413 // A materialized temporary with static storage duration can appear within the
5414 // result of a constant expression evaluation, so we need to preserve its
5415 // value for use outside this evaluation.
5416 APValue *Value;
5417 if (E->getStorageDuration() == SD_Static) {
5418 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005419 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005420 Result.set(E);
5421 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005422 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5423 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00005424 }
5425
Richard Smithea4ad5d2013-06-06 08:19:16 +00005426 QualType Type = Inner->getType();
5427
Richard Smith84401042013-06-03 05:03:02 +00005428 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005429 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5430 (E->getStorageDuration() == SD_Static &&
5431 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5432 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005433 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005434 }
Richard Smith84401042013-06-03 05:03:02 +00005435
5436 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005437 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5438 --I;
5439 switch (Adjustments[I].Kind) {
5440 case SubobjectAdjustment::DerivedToBaseAdjustment:
5441 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5442 Type, Result))
5443 return false;
5444 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5445 break;
5446
5447 case SubobjectAdjustment::FieldAdjustment:
5448 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5449 return false;
5450 Type = Adjustments[I].Field->getType();
5451 break;
5452
5453 case SubobjectAdjustment::MemberPointerAdjustment:
5454 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5455 Adjustments[I].Ptr.RHS))
5456 return false;
5457 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5458 break;
5459 }
5460 }
5461
5462 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005463}
5464
Peter Collingbournee9200682011-05-13 03:29:01 +00005465bool
5466LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005467 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5468 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005469 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5470 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005471 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005472}
5473
Richard Smith6e525142011-12-27 12:18:28 +00005474bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005475 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005476 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005477
Faisal Valie690b7a2016-07-02 22:34:24 +00005478 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005479 << E->getExprOperand()->getType()
5480 << E->getExprOperand()->getSourceRange();
5481 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005482}
5483
Francois Pichet0066db92012-04-16 04:08:35 +00005484bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5485 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005486}
Francois Pichet0066db92012-04-16 04:08:35 +00005487
Peter Collingbournee9200682011-05-13 03:29:01 +00005488bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005489 // Handle static data members.
5490 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005491 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005492 return VisitVarDecl(E, VD);
5493 }
5494
Richard Smith254a73d2011-10-28 22:34:42 +00005495 // Handle static member functions.
5496 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5497 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005498 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005499 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005500 }
5501 }
5502
Richard Smithd62306a2011-11-10 06:34:14 +00005503 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005504 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005505}
5506
Peter Collingbournee9200682011-05-13 03:29:01 +00005507bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005508 // FIXME: Deal with vectors as array subscript bases.
5509 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005510 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005511
Nick Lewyckyad888682017-04-27 07:27:36 +00005512 bool Success = true;
5513 if (!evaluatePointer(E->getBase(), Result)) {
5514 if (!Info.noteFailure())
5515 return false;
5516 Success = false;
5517 }
Mike Stump11289f42009-09-09 15:08:12 +00005518
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005519 APSInt Index;
5520 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005521 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005522
Nick Lewyckyad888682017-04-27 07:27:36 +00005523 return Success &&
5524 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005525}
Eli Friedman9a156e52008-11-12 09:44:48 +00005526
Peter Collingbournee9200682011-05-13 03:29:01 +00005527bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005528 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005529}
5530
Richard Smith66c96992012-02-18 22:04:06 +00005531bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5532 if (!Visit(E->getSubExpr()))
5533 return false;
5534 // __real is a no-op on scalar lvalues.
5535 if (E->getSubExpr()->getType()->isAnyComplexType())
5536 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5537 return true;
5538}
5539
5540bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5541 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5542 "lvalue __imag__ on scalar?");
5543 if (!Visit(E->getSubExpr()))
5544 return false;
5545 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5546 return true;
5547}
5548
Richard Smith243ef902013-05-05 23:31:59 +00005549bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005550 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005551 return Error(UO);
5552
5553 if (!this->Visit(UO->getSubExpr()))
5554 return false;
5555
Richard Smith243ef902013-05-05 23:31:59 +00005556 return handleIncDec(
5557 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005558 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005559}
5560
5561bool LValueExprEvaluator::VisitCompoundAssignOperator(
5562 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005563 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005564 return Error(CAO);
5565
Richard Smith3229b742013-05-05 21:17:10 +00005566 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005567
5568 // The overall lvalue result is the result of evaluating the LHS.
5569 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005570 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005571 Evaluate(RHS, this->Info, CAO->getRHS());
5572 return false;
5573 }
5574
Richard Smith3229b742013-05-05 21:17:10 +00005575 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5576 return false;
5577
Richard Smith43e77732013-05-07 04:50:00 +00005578 return handleCompoundAssignment(
5579 this->Info, CAO,
5580 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5581 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005582}
5583
5584bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005585 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005586 return Error(E);
5587
Richard Smith3229b742013-05-05 21:17:10 +00005588 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005589
5590 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005591 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005592 Evaluate(NewVal, this->Info, E->getRHS());
5593 return false;
5594 }
5595
Richard Smith3229b742013-05-05 21:17:10 +00005596 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5597 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005598
5599 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005600 NewVal);
5601}
5602
Eli Friedman9a156e52008-11-12 09:44:48 +00005603//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005604// Pointer Evaluation
5605//===----------------------------------------------------------------------===//
5606
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005607/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00005608/// returned by a function with the alloc_size attribute. Returns true if we
5609/// were successful. Places an unsigned number into `Result`.
5610///
5611/// This expects the given CallExpr to be a call to a function with an
5612/// alloc_size attribute.
5613static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5614 const CallExpr *Call,
5615 llvm::APInt &Result) {
5616 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5617
Joel E. Denny81508102018-03-13 14:51:22 +00005618 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5619 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005620 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5621 if (Call->getNumArgs() <= SizeArgNo)
5622 return false;
5623
5624 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5625 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5626 return false;
5627 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5628 return false;
5629 Into = Into.zextOrSelf(BitsInSizeT);
5630 return true;
5631 };
5632
5633 APSInt SizeOfElem;
5634 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5635 return false;
5636
Joel E. Denny81508102018-03-13 14:51:22 +00005637 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005638 Result = std::move(SizeOfElem);
5639 return true;
5640 }
5641
5642 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00005643 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005644 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5645 return false;
5646
5647 bool Overflow;
5648 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5649 if (Overflow)
5650 return false;
5651
5652 Result = std::move(BytesAvailable);
5653 return true;
5654}
5655
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005656/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00005657/// function.
5658static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5659 const LValue &LVal,
5660 llvm::APInt &Result) {
5661 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5662 "Can't get the size of a non alloc_size function");
5663 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5664 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5665 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5666}
5667
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005668/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00005669/// a function with the alloc_size attribute. If it was possible to do so, this
5670/// function will return true, make Result's Base point to said function call,
5671/// and mark Result's Base as invalid.
5672static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5673 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005674 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005675 return false;
5676
5677 // Because we do no form of static analysis, we only support const variables.
5678 //
5679 // Additionally, we can't support parameters, nor can we support static
5680 // variables (in the latter case, use-before-assign isn't UB; in the former,
5681 // we have no clue what they'll be assigned to).
5682 const auto *VD =
5683 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5684 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5685 return false;
5686
5687 const Expr *Init = VD->getAnyInitializer();
5688 if (!Init)
5689 return false;
5690
5691 const Expr *E = Init->IgnoreParens();
5692 if (!tryUnwrapAllocSizeCall(E))
5693 return false;
5694
5695 // Store E instead of E unwrapped so that the type of the LValue's base is
5696 // what the user wanted.
5697 Result.setInvalid(E);
5698
5699 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005700 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005701 return true;
5702}
5703
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005704namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005705class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005706 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005707 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005708 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005709
Peter Collingbournee9200682011-05-13 03:29:01 +00005710 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005711 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005712 return true;
5713 }
George Burgess IVe3763372016-12-22 02:50:20 +00005714
George Burgess IVf9013bf2017-02-10 22:52:29 +00005715 bool evaluateLValue(const Expr *E, LValue &Result) {
5716 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5717 }
5718
5719 bool evaluatePointer(const Expr *E, LValue &Result) {
5720 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5721 }
5722
George Burgess IVe3763372016-12-22 02:50:20 +00005723 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005724public:
Mike Stump11289f42009-09-09 15:08:12 +00005725
George Burgess IVf9013bf2017-02-10 22:52:29 +00005726 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5727 : ExprEvaluatorBaseTy(info), Result(Result),
5728 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005729
Richard Smith2e312c82012-03-03 22:46:17 +00005730 bool Success(const APValue &V, const Expr *E) {
5731 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005732 return true;
5733 }
Richard Smithfddd3842011-12-30 21:15:51 +00005734 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005735 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5736 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005737 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005738 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005739
John McCall45d55e42010-05-07 21:00:08 +00005740 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005741 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005742 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005743 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005744 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005745 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5746 if (Info.noteFailure())
5747 EvaluateIgnoredValue(Info, E->getSubExpr());
5748 return Error(E);
5749 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005750 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005751 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005752 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005753 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005754 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005755 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005756 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005757 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005758 }
Richard Smithd62306a2011-11-10 06:34:14 +00005759 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005760 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005761 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005762 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005763 if (!Info.CurrentCall->This) {
5764 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005765 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005766 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005767 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005768 return false;
5769 }
Richard Smithd62306a2011-11-10 06:34:14 +00005770 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005771 // If we are inside a lambda's call operator, the 'this' expression refers
5772 // to the enclosing '*this' object (either by value or reference) which is
5773 // either copied into the closure object's field that represents the '*this'
5774 // or refers to '*this'.
5775 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5776 // Update 'Result' to refer to the data member/field of the closure object
5777 // that represents the '*this' capture.
5778 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00005779 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005780 return false;
5781 // If we captured '*this' by reference, replace the field with its referent.
5782 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5783 ->isPointerType()) {
5784 APValue RVal;
5785 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5786 RVal))
5787 return false;
5788
5789 Result.setFrom(Info.Ctx, RVal);
5790 }
5791 }
Richard Smithd62306a2011-11-10 06:34:14 +00005792 return true;
5793 }
John McCallc07a0c72011-02-17 10:25:35 +00005794
Eli Friedman449fe542009-03-23 04:56:01 +00005795 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005796};
Chris Lattner05706e882008-07-11 18:11:29 +00005797} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005798
George Burgess IVf9013bf2017-02-10 22:52:29 +00005799static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5800 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005801 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005802 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005803}
5804
John McCall45d55e42010-05-07 21:00:08 +00005805bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005806 if (E->getOpcode() != BO_Add &&
5807 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005808 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005809
Chris Lattner05706e882008-07-11 18:11:29 +00005810 const Expr *PExp = E->getLHS();
5811 const Expr *IExp = E->getRHS();
5812 if (IExp->getType()->isPointerType())
5813 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005814
George Burgess IVf9013bf2017-02-10 22:52:29 +00005815 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005816 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005817 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005818
John McCall45d55e42010-05-07 21:00:08 +00005819 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005820 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005821 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005822
Richard Smith96e0c102011-11-04 02:25:55 +00005823 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005824 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005825
Ted Kremenek28831752012-08-23 20:46:57 +00005826 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005827 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005828}
Eli Friedman9a156e52008-11-12 09:44:48 +00005829
John McCall45d55e42010-05-07 21:00:08 +00005830bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005831 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005832}
Mike Stump11289f42009-09-09 15:08:12 +00005833
Richard Smith81dfef92018-07-11 00:29:05 +00005834bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5835 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005836
Eli Friedman847a2bc2009-12-27 05:43:15 +00005837 switch (E->getCastKind()) {
5838 default:
5839 break;
5840
John McCalle3027922010-08-25 11:45:40 +00005841 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005842 case CK_CPointerToObjCPointerCast:
5843 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005844 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005845 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005846 if (!Visit(SubExpr))
5847 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005848 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5849 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5850 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005851 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00005852 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005853 if (SubExpr->getType()->isVoidPointerType())
5854 CCEDiag(E, diag::note_constexpr_invalid_cast)
5855 << 3 << SubExpr->getType();
5856 else
5857 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5858 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005859 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5860 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005861 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005862
Anders Carlsson18275092010-10-31 20:41:46 +00005863 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005864 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005865 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005866 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005867 if (!Result.Base && Result.Offset.isZero())
5868 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005869
Richard Smithd62306a2011-11-10 06:34:14 +00005870 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005871 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005872 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5873 castAs<PointerType>()->getPointeeType(),
5874 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005875
Richard Smith027bf112011-11-17 22:56:20 +00005876 case CK_BaseToDerived:
5877 if (!Visit(E->getSubExpr()))
5878 return false;
5879 if (!Result.Base && Result.Offset.isZero())
5880 return true;
5881 return HandleBaseToDerivedCast(Info, E, Result);
5882
Richard Smith0b0a0b62011-10-29 20:57:55 +00005883 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005884 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005885 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005886
John McCalle3027922010-08-25 11:45:40 +00005887 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005888 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5889
Richard Smith2e312c82012-03-03 22:46:17 +00005890 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005891 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005892 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005893
John McCall45d55e42010-05-07 21:00:08 +00005894 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005895 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5896 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005897 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005898 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005899 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00005900 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005901 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005902 return true;
5903 } else {
5904 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005905 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005906 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005907 }
5908 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005909
5910 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005911 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005912 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005913 return false;
5914 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005915 APValue &Value = createTemporary(SubExpr, false, Result,
5916 *Info.CurrentCall);
5917 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005918 return false;
5919 }
Richard Smith96e0c102011-11-04 02:25:55 +00005920 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005921 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5922 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005923 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005924 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005925 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005926 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005927 }
Richard Smithdd785442011-10-31 20:57:44 +00005928
John McCalle3027922010-08-25 11:45:40 +00005929 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005930 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005931
5932 case CK_LValueToRValue: {
5933 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005934 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005935 return false;
5936
5937 APValue RVal;
5938 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5939 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5940 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005941 return InvalidBaseOK &&
5942 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005943 return Success(RVal, E);
5944 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005945 }
5946
Richard Smith11562c52011-10-28 17:51:58 +00005947 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005948}
Chris Lattner05706e882008-07-11 18:11:29 +00005949
Richard Smith6822bd72018-10-26 19:26:45 +00005950static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
5951 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005952 // C++ [expr.alignof]p3:
5953 // When alignof is applied to a reference type, the result is the
5954 // alignment of the referenced type.
5955 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5956 T = Ref->getPointeeType();
5957
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005958 if (T.getQualifiers().hasUnaligned())
5959 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00005960
5961 const bool AlignOfReturnsPreferred =
5962 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
5963
5964 // __alignof is defined to return the preferred alignment.
5965 // Before 8, clang returned the preferred alignment for alignof and _Alignof
5966 // as well.
5967 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
5968 return Info.Ctx.toCharUnitsFromBits(
5969 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5970 // alignof and _Alignof are defined to return the ABI alignment.
5971 else if (ExprKind == UETT_AlignOf)
5972 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
5973 else
5974 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00005975}
5976
Richard Smith6822bd72018-10-26 19:26:45 +00005977static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
5978 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005979 E = E->IgnoreParens();
5980
5981 // The kinds of expressions that we have special-case logic here for
5982 // should be kept up to date with the special checks for those
5983 // expressions in Sema.
5984
5985 // alignof decl is always accepted, even if it doesn't make sense: we default
5986 // to 1 in those cases.
5987 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5988 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5989 /*RefAsPointee*/true);
5990
5991 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5992 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5993 /*RefAsPointee*/true);
5994
Richard Smith6822bd72018-10-26 19:26:45 +00005995 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005996}
5997
George Burgess IVe3763372016-12-22 02:50:20 +00005998// To be clear: this happily visits unsupported builtins. Better name welcomed.
5999bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6000 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6001 return true;
6002
George Burgess IVf9013bf2017-02-10 22:52:29 +00006003 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00006004 return false;
6005
6006 Result.setInvalid(E);
6007 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006008 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00006009 return true;
6010}
6011
Peter Collingbournee9200682011-05-13 03:29:01 +00006012bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006013 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00006014 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00006015
Richard Smith6328cbd2016-11-16 00:57:23 +00006016 if (unsigned BuiltinOp = E->getBuiltinCallee())
6017 return VisitBuiltinCallExpr(E, BuiltinOp);
6018
George Burgess IVe3763372016-12-22 02:50:20 +00006019 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006020}
6021
6022bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6023 unsigned BuiltinOp) {
6024 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00006025 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006026 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006027 case Builtin::BI__builtin_assume_aligned: {
6028 // We need to be very careful here because: if the pointer does not have the
6029 // asserted alignment, then the behavior is undefined, and undefined
6030 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00006031 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00006032 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00006033
Hal Finkel0dd05d42014-10-03 17:18:37 +00006034 LValue OffsetResult(Result);
6035 APSInt Alignment;
6036 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6037 return false;
Richard Smith642a2362017-01-30 23:30:26 +00006038 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00006039
6040 if (E->getNumArgs() > 2) {
6041 APSInt Offset;
6042 if (!EvaluateInteger(E->getArg(2), Offset, Info))
6043 return false;
6044
Richard Smith642a2362017-01-30 23:30:26 +00006045 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006046 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6047 }
6048
6049 // If there is a base object, then it must have the correct alignment.
6050 if (OffsetResult.Base) {
6051 CharUnits BaseAlignment;
6052 if (const ValueDecl *VD =
6053 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6054 BaseAlignment = Info.Ctx.getDeclAlign(VD);
6055 } else {
Richard Smith6822bd72018-10-26 19:26:45 +00006056 BaseAlignment = GetAlignOfExpr(
6057 Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006058 }
6059
6060 if (BaseAlignment < Align) {
6061 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00006062 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00006063 CCEDiag(E->getArg(0),
6064 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00006065 << (unsigned)BaseAlignment.getQuantity()
6066 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006067 return false;
6068 }
6069 }
6070
6071 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006072 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006073 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006074
Richard Smith642a2362017-01-30 23:30:26 +00006075 (OffsetResult.Base
6076 ? CCEDiag(E->getArg(0),
6077 diag::note_constexpr_baa_insufficient_alignment) << 1
6078 : CCEDiag(E->getArg(0),
6079 diag::note_constexpr_baa_value_insufficient_alignment))
6080 << (int)OffsetResult.Offset.getQuantity()
6081 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006082 return false;
6083 }
6084
6085 return true;
6086 }
Richard Smithe9507952016-11-12 01:39:56 +00006087
6088 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006089 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00006090 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006091 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00006092 if (Info.getLangOpts().CPlusPlus11)
6093 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6094 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00006095 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00006096 else
6097 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006098 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00006099 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006100 case Builtin::BI__builtin_wcschr:
6101 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006102 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006103 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00006104 if (!Visit(E->getArg(0)))
6105 return false;
6106 APSInt Desired;
6107 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6108 return false;
6109 uint64_t MaxLength = uint64_t(-1);
6110 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00006111 BuiltinOp != Builtin::BIwcschr &&
6112 BuiltinOp != Builtin::BI__builtin_strchr &&
6113 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00006114 APSInt N;
6115 if (!EvaluateInteger(E->getArg(2), N, Info))
6116 return false;
6117 MaxLength = N.getExtValue();
6118 }
6119
Richard Smith8110c9d2016-11-29 19:45:17 +00006120 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00006121
Richard Smith8110c9d2016-11-29 19:45:17 +00006122 // Figure out what value we're actually looking for (after converting to
6123 // the corresponding unsigned type if necessary).
6124 uint64_t DesiredVal;
6125 bool StopAtNull = false;
6126 switch (BuiltinOp) {
6127 case Builtin::BIstrchr:
6128 case Builtin::BI__builtin_strchr:
6129 // strchr compares directly to the passed integer, and therefore
6130 // always fails if given an int that is not a char.
6131 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6132 E->getArg(1)->getType(),
6133 Desired),
6134 Desired))
6135 return ZeroInitialization(E);
6136 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006137 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006138 case Builtin::BImemchr:
6139 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006140 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006141 // memchr compares by converting both sides to unsigned char. That's also
6142 // correct for strchr if we get this far (to cope with plain char being
6143 // unsigned in the strchr case).
6144 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6145 break;
Richard Smithe9507952016-11-12 01:39:56 +00006146
Richard Smith8110c9d2016-11-29 19:45:17 +00006147 case Builtin::BIwcschr:
6148 case Builtin::BI__builtin_wcschr:
6149 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006150 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006151 case Builtin::BIwmemchr:
6152 case Builtin::BI__builtin_wmemchr:
6153 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6154 DesiredVal = Desired.getZExtValue();
6155 break;
6156 }
Richard Smithe9507952016-11-12 01:39:56 +00006157
6158 for (; MaxLength; --MaxLength) {
6159 APValue Char;
6160 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6161 !Char.isInt())
6162 return false;
6163 if (Char.getInt().getZExtValue() == DesiredVal)
6164 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006165 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006166 break;
6167 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6168 return false;
6169 }
6170 // Not found: return nullptr.
6171 return ZeroInitialization(E);
6172 }
6173
Richard Smith06f71b52018-08-04 00:57:17 +00006174 case Builtin::BImemcpy:
6175 case Builtin::BImemmove:
6176 case Builtin::BIwmemcpy:
6177 case Builtin::BIwmemmove:
6178 if (Info.getLangOpts().CPlusPlus11)
6179 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6180 << /*isConstexpr*/0 << /*isConstructor*/0
6181 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6182 else
6183 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6184 LLVM_FALLTHROUGH;
6185 case Builtin::BI__builtin_memcpy:
6186 case Builtin::BI__builtin_memmove:
6187 case Builtin::BI__builtin_wmemcpy:
6188 case Builtin::BI__builtin_wmemmove: {
6189 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6190 BuiltinOp == Builtin::BIwmemmove ||
6191 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6192 BuiltinOp == Builtin::BI__builtin_wmemmove;
6193 bool Move = BuiltinOp == Builtin::BImemmove ||
6194 BuiltinOp == Builtin::BIwmemmove ||
6195 BuiltinOp == Builtin::BI__builtin_memmove ||
6196 BuiltinOp == Builtin::BI__builtin_wmemmove;
6197
6198 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00006199 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00006200 return false;
6201 LValue Dest = Result;
6202
6203 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00006204 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00006205 return false;
6206
6207 APSInt N;
6208 if (!EvaluateInteger(E->getArg(2), N, Info))
6209 return false;
6210 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6211
6212 // If the size is zero, we treat this as always being a valid no-op.
6213 // (Even if one of the src and dest pointers is null.)
6214 if (!N)
6215 return true;
6216
Richard Smith128719c2018-09-13 22:47:33 +00006217 // Otherwise, if either of the operands is null, we can't proceed. Don't
6218 // try to determine the type of the copied objects, because there aren't
6219 // any.
6220 if (!Src.Base || !Dest.Base) {
6221 APValue Val;
6222 (!Src.Base ? Src : Dest).moveInto(Val);
6223 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6224 << Move << WChar << !!Src.Base
6225 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6226 return false;
6227 }
6228 if (Src.Designator.Invalid || Dest.Designator.Invalid)
6229 return false;
6230
Richard Smith06f71b52018-08-04 00:57:17 +00006231 // We require that Src and Dest are both pointers to arrays of
6232 // trivially-copyable type. (For the wide version, the designator will be
6233 // invalid if the designated object is not a wchar_t.)
6234 QualType T = Dest.Designator.getType(Info.Ctx);
6235 QualType SrcT = Src.Designator.getType(Info.Ctx);
6236 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6237 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6238 return false;
6239 }
Petr Pavlued083f22018-10-04 09:25:44 +00006240 if (T->isIncompleteType()) {
6241 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6242 return false;
6243 }
Richard Smith06f71b52018-08-04 00:57:17 +00006244 if (!T.isTriviallyCopyableType(Info.Ctx)) {
6245 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6246 return false;
6247 }
6248
6249 // Figure out how many T's we're copying.
6250 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6251 if (!WChar) {
6252 uint64_t Remainder;
6253 llvm::APInt OrigN = N;
6254 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6255 if (Remainder) {
6256 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6257 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6258 << (unsigned)TSize;
6259 return false;
6260 }
6261 }
6262
6263 // Check that the copying will remain within the arrays, just so that we
6264 // can give a more meaningful diagnostic. This implicitly also checks that
6265 // N fits into 64 bits.
6266 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6267 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6268 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6269 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6270 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6271 << N.toString(10, /*Signed*/false);
6272 return false;
6273 }
6274 uint64_t NElems = N.getZExtValue();
6275 uint64_t NBytes = NElems * TSize;
6276
6277 // Check for overlap.
6278 int Direction = 1;
6279 if (HasSameBase(Src, Dest)) {
6280 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6281 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6282 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6283 // Dest is inside the source region.
6284 if (!Move) {
6285 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6286 return false;
6287 }
6288 // For memmove and friends, copy backwards.
6289 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6290 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6291 return false;
6292 Direction = -1;
6293 } else if (!Move && SrcOffset >= DestOffset &&
6294 SrcOffset - DestOffset < NBytes) {
6295 // Src is inside the destination region for memcpy: invalid.
6296 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6297 return false;
6298 }
6299 }
6300
6301 while (true) {
6302 APValue Val;
6303 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6304 !handleAssignment(Info, E, Dest, T, Val))
6305 return false;
6306 // Do not iterate past the last element; if we're copying backwards, that
6307 // might take us off the start of the array.
6308 if (--NElems == 0)
6309 return true;
6310 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6311 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6312 return false;
6313 }
6314 }
6315
Richard Smith6cbd65d2013-07-11 02:27:57 +00006316 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006317 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006318 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006319}
Chris Lattner05706e882008-07-11 18:11:29 +00006320
6321//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006322// Member Pointer Evaluation
6323//===----------------------------------------------------------------------===//
6324
6325namespace {
6326class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006327 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006328 MemberPtr &Result;
6329
6330 bool Success(const ValueDecl *D) {
6331 Result = MemberPtr(D);
6332 return true;
6333 }
6334public:
6335
6336 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6337 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6338
Richard Smith2e312c82012-03-03 22:46:17 +00006339 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006340 Result.setFrom(V);
6341 return true;
6342 }
Richard Smithfddd3842011-12-30 21:15:51 +00006343 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006344 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006345 }
6346
6347 bool VisitCastExpr(const CastExpr *E);
6348 bool VisitUnaryAddrOf(const UnaryOperator *E);
6349};
6350} // end anonymous namespace
6351
6352static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6353 EvalInfo &Info) {
6354 assert(E->isRValue() && E->getType()->isMemberPointerType());
6355 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6356}
6357
6358bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6359 switch (E->getCastKind()) {
6360 default:
6361 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6362
6363 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006364 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006365 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006366
6367 case CK_BaseToDerivedMemberPointer: {
6368 if (!Visit(E->getSubExpr()))
6369 return false;
6370 if (E->path_empty())
6371 return true;
6372 // Base-to-derived member pointer casts store the path in derived-to-base
6373 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6374 // the wrong end of the derived->base arc, so stagger the path by one class.
6375 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6376 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6377 PathI != PathE; ++PathI) {
6378 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6379 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6380 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006381 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006382 }
6383 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6384 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006385 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006386 return true;
6387 }
6388
6389 case CK_DerivedToBaseMemberPointer:
6390 if (!Visit(E->getSubExpr()))
6391 return false;
6392 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6393 PathE = E->path_end(); PathI != PathE; ++PathI) {
6394 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6395 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6396 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006397 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006398 }
6399 return true;
6400 }
6401}
6402
6403bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6404 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6405 // member can be formed.
6406 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6407}
6408
6409//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006410// Record Evaluation
6411//===----------------------------------------------------------------------===//
6412
6413namespace {
6414 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006415 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006416 const LValue &This;
6417 APValue &Result;
6418 public:
6419
6420 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6421 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6422
Richard Smith2e312c82012-03-03 22:46:17 +00006423 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006424 Result = V;
6425 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006426 }
Richard Smithb8348f52016-05-12 22:16:28 +00006427 bool ZeroInitialization(const Expr *E) {
6428 return ZeroInitialization(E, E->getType());
6429 }
6430 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006431
Richard Smith52a980a2015-08-28 02:43:42 +00006432 bool VisitCallExpr(const CallExpr *E) {
6433 return handleCallExpr(E, Result, &This);
6434 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006435 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006436 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006437 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6438 return VisitCXXConstructExpr(E, E->getType());
6439 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006440 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006441 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006442 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006443 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006444
6445 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006446 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006447}
Richard Smithd62306a2011-11-10 06:34:14 +00006448
Richard Smithfddd3842011-12-30 21:15:51 +00006449/// Perform zero-initialization on an object of non-union class type.
6450/// C++11 [dcl.init]p5:
6451/// To zero-initialize an object or reference of type T means:
6452/// [...]
6453/// -- if T is a (possibly cv-qualified) non-union class type,
6454/// each non-static data member and each base-class subobject is
6455/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006456static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6457 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006458 const LValue &This, APValue &Result) {
6459 assert(!RD->isUnion() && "Expected non-union class type");
6460 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6461 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006462 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006463
John McCalld7bca762012-05-01 00:38:49 +00006464 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006465 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6466
6467 if (CD) {
6468 unsigned Index = 0;
6469 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006470 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006471 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6472 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006473 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6474 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006475 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006476 Result.getStructBase(Index)))
6477 return false;
6478 }
6479 }
6480
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006481 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006482 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006483 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006484 continue;
6485
6486 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006487 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006488 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006489
David Blaikie2d7c57e2012-04-30 02:36:29 +00006490 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006491 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006492 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006493 return false;
6494 }
6495
6496 return true;
6497}
6498
Richard Smithb8348f52016-05-12 22:16:28 +00006499bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6500 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006501 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006502 if (RD->isUnion()) {
6503 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6504 // object's first non-static named data member is zero-initialized
6505 RecordDecl::field_iterator I = RD->field_begin();
6506 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006507 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006508 return true;
6509 }
6510
6511 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006512 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006513 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006514 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006515 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006516 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006517 }
6518
Richard Smith5d108602012-02-17 00:44:16 +00006519 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006520 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006521 return false;
6522 }
6523
Richard Smitha8105bc2012-01-06 16:39:00 +00006524 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006525}
6526
Richard Smithe97cbd72011-11-11 04:05:33 +00006527bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6528 switch (E->getCastKind()) {
6529 default:
6530 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6531
6532 case CK_ConstructorConversion:
6533 return Visit(E->getSubExpr());
6534
6535 case CK_DerivedToBase:
6536 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006537 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006538 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006539 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006540 if (!DerivedObject.isStruct())
6541 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006542
6543 // Derived-to-base rvalue conversion: just slice off the derived part.
6544 APValue *Value = &DerivedObject;
6545 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6546 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6547 PathE = E->path_end(); PathI != PathE; ++PathI) {
6548 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6549 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6550 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6551 RD = Base;
6552 }
6553 Result = *Value;
6554 return true;
6555 }
6556 }
6557}
6558
Richard Smithd62306a2011-11-10 06:34:14 +00006559bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006560 if (E->isTransparent())
6561 return Visit(E->getInit(0));
6562
Richard Smithd62306a2011-11-10 06:34:14 +00006563 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006564 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006565 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6566
6567 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006568 const FieldDecl *Field = E->getInitializedFieldInUnion();
6569 Result = APValue(Field);
6570 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006571 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006572
6573 // If the initializer list for a union does not contain any elements, the
6574 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006575 // FIXME: The element should be initialized from an initializer list.
6576 // Is this difference ever observable for initializer lists which
6577 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006578 ImplicitValueInitExpr VIE(Field->getType());
6579 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6580
Richard Smithd62306a2011-11-10 06:34:14 +00006581 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006582 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6583 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006584
6585 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6586 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6587 isa<CXXDefaultInitExpr>(InitExpr));
6588
Richard Smithb228a862012-02-15 02:18:13 +00006589 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006590 }
6591
Richard Smith872307e2016-03-08 22:17:41 +00006592 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006593 if (Result.isUninit())
6594 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6595 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006596 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006597 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006598
6599 // Initialize base classes.
6600 if (CXXRD) {
6601 for (const auto &Base : CXXRD->bases()) {
6602 assert(ElementNo < E->getNumInits() && "missing init for base class");
6603 const Expr *Init = E->getInit(ElementNo);
6604
6605 LValue Subobject = This;
6606 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6607 return false;
6608
6609 APValue &FieldVal = Result.getStructBase(ElementNo);
6610 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006611 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006612 return false;
6613 Success = false;
6614 }
6615 ++ElementNo;
6616 }
6617 }
6618
6619 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006620 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006621 // Anonymous bit-fields are not considered members of the class for
6622 // purposes of aggregate initialization.
6623 if (Field->isUnnamedBitfield())
6624 continue;
6625
6626 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006627
Richard Smith253c2a32012-01-27 01:14:48 +00006628 bool HaveInit = ElementNo < E->getNumInits();
6629
6630 // FIXME: Diagnostics here should point to the end of the initializer
6631 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006632 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006633 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006634 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006635
6636 // Perform an implicit value-initialization for members beyond the end of
6637 // the initializer list.
6638 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006639 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006640
Richard Smith852c9db2013-04-20 22:23:05 +00006641 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6642 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6643 isa<CXXDefaultInitExpr>(Init));
6644
Richard Smith49ca8aa2013-08-06 07:09:20 +00006645 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6646 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6647 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006648 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006649 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006650 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006651 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006652 }
6653 }
6654
Richard Smith253c2a32012-01-27 01:14:48 +00006655 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006656}
6657
Richard Smithb8348f52016-05-12 22:16:28 +00006658bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6659 QualType T) {
6660 // Note that E's type is not necessarily the type of our class here; we might
6661 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006662 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006663 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6664
Richard Smithfddd3842011-12-30 21:15:51 +00006665 bool ZeroInit = E->requiresZeroInitialization();
6666 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006667 // If we've already performed zero-initialization, we're already done.
6668 if (!Result.isUninit())
6669 return true;
6670
Richard Smithda3f4fd2014-03-05 23:32:50 +00006671 // We can get here in two different ways:
6672 // 1) We're performing value-initialization, and should zero-initialize
6673 // the object, or
6674 // 2) We're performing default-initialization of an object with a trivial
6675 // constexpr default constructor, in which case we should start the
6676 // lifetimes of all the base subobjects (there can be no data member
6677 // subobjects in this case) per [basic.life]p1.
6678 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006679 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006680 }
6681
Craig Topper36250ad2014-05-12 05:36:57 +00006682 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006683 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006684
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006685 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006686 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006687
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006688 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006689 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006690 if (const MaterializeTemporaryExpr *ME
6691 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6692 return Visit(ME->GetTemporaryExpr());
6693
Richard Smithb8348f52016-05-12 22:16:28 +00006694 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006695 return false;
6696
Craig Topper5fc8fc22014-08-27 06:28:36 +00006697 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006698 return HandleConstructorCall(E, This, Args,
6699 cast<CXXConstructorDecl>(Definition), Info,
6700 Result);
6701}
6702
6703bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6704 const CXXInheritedCtorInitExpr *E) {
6705 if (!Info.CurrentCall) {
6706 assert(Info.checkingPotentialConstantExpression());
6707 return false;
6708 }
6709
6710 const CXXConstructorDecl *FD = E->getConstructor();
6711 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6712 return false;
6713
6714 const FunctionDecl *Definition = nullptr;
6715 auto Body = FD->getBody(Definition);
6716
6717 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6718 return false;
6719
6720 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006721 cast<CXXConstructorDecl>(Definition), Info,
6722 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006723}
6724
Richard Smithcc1b96d2013-06-12 22:31:48 +00006725bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6726 const CXXStdInitializerListExpr *E) {
6727 const ConstantArrayType *ArrayType =
6728 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6729
6730 LValue Array;
6731 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6732 return false;
6733
6734 // Get a pointer to the first element of the array.
6735 Array.addArray(Info, E, ArrayType);
6736
6737 // FIXME: Perform the checks on the field types in SemaInit.
6738 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6739 RecordDecl::field_iterator Field = Record->field_begin();
6740 if (Field == Record->field_end())
6741 return Error(E);
6742
6743 // Start pointer.
6744 if (!Field->getType()->isPointerType() ||
6745 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6746 ArrayType->getElementType()))
6747 return Error(E);
6748
6749 // FIXME: What if the initializer_list type has base classes, etc?
6750 Result = APValue(APValue::UninitStruct(), 0, 2);
6751 Array.moveInto(Result.getStructField(0));
6752
6753 if (++Field == Record->field_end())
6754 return Error(E);
6755
6756 if (Field->getType()->isPointerType() &&
6757 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6758 ArrayType->getElementType())) {
6759 // End pointer.
6760 if (!HandleLValueArrayAdjustment(Info, E, Array,
6761 ArrayType->getElementType(),
6762 ArrayType->getSize().getZExtValue()))
6763 return false;
6764 Array.moveInto(Result.getStructField(1));
6765 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6766 // Length.
6767 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6768 else
6769 return Error(E);
6770
6771 if (++Field != Record->field_end())
6772 return Error(E);
6773
6774 return true;
6775}
6776
Faisal Valic72a08c2017-01-09 03:02:53 +00006777bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6778 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6779 if (ClosureClass->isInvalidDecl()) return false;
6780
6781 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00006782
Faisal Vali051e3a22017-02-16 04:12:21 +00006783 const size_t NumFields =
6784 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006785
6786 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6787 E->capture_init_end()) &&
6788 "The number of lambda capture initializers should equal the number of "
6789 "fields within the closure type");
6790
Faisal Vali051e3a22017-02-16 04:12:21 +00006791 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6792 // Iterate through all the lambda's closure object's fields and initialize
6793 // them.
6794 auto *CaptureInitIt = E->capture_init_begin();
6795 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6796 bool Success = true;
6797 for (const auto *Field : ClosureClass->fields()) {
6798 assert(CaptureInitIt != E->capture_init_end());
6799 // Get the initializer for this field
6800 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00006801
Faisal Vali051e3a22017-02-16 04:12:21 +00006802 // If there is no initializer, either this is a VLA or an error has
6803 // occurred.
6804 if (!CurFieldInit)
6805 return Error(E);
6806
6807 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6808 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6809 if (!Info.keepEvaluatingAfterFailure())
6810 return false;
6811 Success = false;
6812 }
6813 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006814 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006815 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006816}
6817
Richard Smithd62306a2011-11-10 06:34:14 +00006818static bool EvaluateRecord(const Expr *E, const LValue &This,
6819 APValue &Result, EvalInfo &Info) {
6820 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006821 "can't evaluate expression as a record rvalue");
6822 return RecordExprEvaluator(Info, This, Result).Visit(E);
6823}
6824
6825//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006826// Temporary Evaluation
6827//
6828// Temporaries are represented in the AST as rvalues, but generally behave like
6829// lvalues. The full-object of which the temporary is a subobject is implicitly
6830// materialized so that a reference can bind to it.
6831//===----------------------------------------------------------------------===//
6832namespace {
6833class TemporaryExprEvaluator
6834 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6835public:
6836 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006837 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006838
6839 /// Visit an expression which constructs the value of this temporary.
6840 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006841 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6842 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006843 }
6844
6845 bool VisitCastExpr(const CastExpr *E) {
6846 switch (E->getCastKind()) {
6847 default:
6848 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6849
6850 case CK_ConstructorConversion:
6851 return VisitConstructExpr(E->getSubExpr());
6852 }
6853 }
6854 bool VisitInitListExpr(const InitListExpr *E) {
6855 return VisitConstructExpr(E);
6856 }
6857 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6858 return VisitConstructExpr(E);
6859 }
6860 bool VisitCallExpr(const CallExpr *E) {
6861 return VisitConstructExpr(E);
6862 }
Richard Smith513955c2014-12-17 19:24:30 +00006863 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6864 return VisitConstructExpr(E);
6865 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006866 bool VisitLambdaExpr(const LambdaExpr *E) {
6867 return VisitConstructExpr(E);
6868 }
Richard Smith027bf112011-11-17 22:56:20 +00006869};
6870} // end anonymous namespace
6871
6872/// Evaluate an expression of record type as a temporary.
6873static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006874 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006875 return TemporaryExprEvaluator(Info, Result).Visit(E);
6876}
6877
6878//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006879// Vector Evaluation
6880//===----------------------------------------------------------------------===//
6881
6882namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006883 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006884 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006885 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006886 public:
Mike Stump11289f42009-09-09 15:08:12 +00006887
Richard Smith2d406342011-10-22 21:10:00 +00006888 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6889 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006890
Craig Topper9798b932015-09-29 04:30:05 +00006891 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006892 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6893 // FIXME: remove this APValue copy.
6894 Result = APValue(V.data(), V.size());
6895 return true;
6896 }
Richard Smith2e312c82012-03-03 22:46:17 +00006897 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006898 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006899 Result = V;
6900 return true;
6901 }
Richard Smithfddd3842011-12-30 21:15:51 +00006902 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006903
Richard Smith2d406342011-10-22 21:10:00 +00006904 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006905 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006906 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006907 bool VisitInitListExpr(const InitListExpr *E);
6908 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006909 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006910 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006911 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006912 };
6913} // end anonymous namespace
6914
6915static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006916 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006917 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006918}
6919
George Burgess IV533ff002015-12-11 00:23:35 +00006920bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006921 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006922 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006923
Richard Smith161f09a2011-12-06 22:44:34 +00006924 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006925 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006926
Eli Friedmanc757de22011-03-25 00:43:55 +00006927 switch (E->getCastKind()) {
6928 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006929 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006930 if (SETy->isIntegerType()) {
6931 APSInt IntResult;
6932 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006933 return false;
6934 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006935 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006936 APFloat FloatResult(0.0);
6937 if (!EvaluateFloat(SE, FloatResult, Info))
6938 return false;
6939 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006940 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006941 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006942 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006943
6944 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006945 SmallVector<APValue, 4> Elts(NElts, Val);
6946 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006947 }
Eli Friedman803acb32011-12-22 03:51:45 +00006948 case CK_BitCast: {
6949 // Evaluate the operand into an APInt we can extract from.
6950 llvm::APInt SValInt;
6951 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6952 return false;
6953 // Extract the elements
6954 QualType EltTy = VTy->getElementType();
6955 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6956 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6957 SmallVector<APValue, 4> Elts;
6958 if (EltTy->isRealFloatingType()) {
6959 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006960 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006961 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006962 FloatEltSize = 80;
6963 for (unsigned i = 0; i < NElts; i++) {
6964 llvm::APInt Elt;
6965 if (BigEndian)
6966 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6967 else
6968 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006969 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006970 }
6971 } else if (EltTy->isIntegerType()) {
6972 for (unsigned i = 0; i < NElts; i++) {
6973 llvm::APInt Elt;
6974 if (BigEndian)
6975 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6976 else
6977 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6978 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6979 }
6980 } else {
6981 return Error(E);
6982 }
6983 return Success(Elts, E);
6984 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006985 default:
Richard Smith11562c52011-10-28 17:51:58 +00006986 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006987 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006988}
6989
Richard Smith2d406342011-10-22 21:10:00 +00006990bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006991VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006992 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006993 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006994 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006995
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006996 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006997 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006998
Eli Friedmanb9c71292012-01-03 23:24:20 +00006999 // The number of initializers can be less than the number of
7000 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00007001 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00007002 // should be initialized with zeroes.
7003 unsigned CountInits = 0, CountElts = 0;
7004 while (CountElts < NumElements) {
7005 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00007006 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00007007 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00007008 APValue v;
7009 if (!EvaluateVector(E->getInit(CountInits), v, Info))
7010 return Error(E);
7011 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00007012 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00007013 Elements.push_back(v.getVectorElt(j));
7014 CountElts += vlen;
7015 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007016 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007017 if (CountInits < NumInits) {
7018 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007019 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007020 } else // trailing integer zero.
7021 sInt = Info.Ctx.MakeIntValue(0, EltTy);
7022 Elements.push_back(APValue(sInt));
7023 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007024 } else {
7025 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007026 if (CountInits < NumInits) {
7027 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007028 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007029 } else // trailing float zero.
7030 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7031 Elements.push_back(APValue(f));
7032 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00007033 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00007034 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007035 }
Richard Smith2d406342011-10-22 21:10:00 +00007036 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007037}
7038
Richard Smith2d406342011-10-22 21:10:00 +00007039bool
Richard Smithfddd3842011-12-30 21:15:51 +00007040VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007041 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00007042 QualType EltTy = VT->getElementType();
7043 APValue ZeroElement;
7044 if (EltTy->isIntegerType())
7045 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7046 else
7047 ZeroElement =
7048 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7049
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007050 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00007051 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007052}
7053
Richard Smith2d406342011-10-22 21:10:00 +00007054bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00007055 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007056 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007057}
7058
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007059//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00007060// Array Evaluation
7061//===----------------------------------------------------------------------===//
7062
7063namespace {
7064 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007065 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007066 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00007067 APValue &Result;
7068 public:
7069
Richard Smithd62306a2011-11-10 06:34:14 +00007070 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7071 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00007072
7073 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00007074 assert((V.isArray() || V.isLValue()) &&
7075 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00007076 Result = V;
7077 return true;
7078 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007079
Richard Smithfddd3842011-12-30 21:15:51 +00007080 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007081 const ConstantArrayType *CAT =
7082 Info.Ctx.getAsConstantArrayType(E->getType());
7083 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007084 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007085
7086 Result = APValue(APValue::UninitArray(), 0,
7087 CAT->getSize().getZExtValue());
7088 if (!Result.hasArrayFiller()) return true;
7089
Richard Smithfddd3842011-12-30 21:15:51 +00007090 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00007091 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007092 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00007093 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00007094 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00007095 }
7096
Richard Smith52a980a2015-08-28 02:43:42 +00007097 bool VisitCallExpr(const CallExpr *E) {
7098 return handleCallExpr(E, Result, &This);
7099 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007100 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00007101 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00007102 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00007103 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7104 const LValue &Subobject,
7105 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00007106 };
7107} // end anonymous namespace
7108
Richard Smithd62306a2011-11-10 06:34:14 +00007109static bool EvaluateArray(const Expr *E, const LValue &This,
7110 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00007111 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00007112 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007113}
7114
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007115// Return true iff the given array filler may depend on the element index.
7116static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7117 // For now, just whitelist non-class value-initialization and initialization
7118 // lists comprised of them.
7119 if (isa<ImplicitValueInitExpr>(FillerExpr))
7120 return false;
7121 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7122 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7123 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7124 return true;
7125 }
7126 return false;
7127 }
7128 return true;
7129}
7130
Richard Smithf3e9e432011-11-07 09:22:26 +00007131bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7132 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7133 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007134 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007135
Richard Smithca2cfbf2011-12-22 01:07:19 +00007136 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7137 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00007138 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00007139 LValue LV;
7140 if (!EvaluateLValue(E->getInit(0), LV, Info))
7141 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007142 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00007143 LV.moveInto(Val);
7144 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00007145 }
7146
Richard Smith253c2a32012-01-27 01:14:48 +00007147 bool Success = true;
7148
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007149 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7150 "zero-initialized array shouldn't have any initialized elts");
7151 APValue Filler;
7152 if (Result.isArray() && Result.hasArrayFiller())
7153 Filler = Result.getArrayFiller();
7154
Richard Smith9543c5e2013-04-22 14:44:29 +00007155 unsigned NumEltsToInit = E->getNumInits();
7156 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007157 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00007158
7159 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007160 // array element.
7161 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00007162 NumEltsToInit = NumElts;
7163
Nicola Zaghen3538b392018-05-15 13:30:56 +00007164 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7165 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007166
Richard Smith9543c5e2013-04-22 14:44:29 +00007167 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007168
7169 // If the array was previously zero-initialized, preserve the
7170 // zero-initialized values.
7171 if (!Filler.isUninit()) {
7172 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7173 Result.getArrayInitializedElt(I) = Filler;
7174 if (Result.hasArrayFiller())
7175 Result.getArrayFiller() = Filler;
7176 }
7177
Richard Smithd62306a2011-11-10 06:34:14 +00007178 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007179 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00007180 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7181 const Expr *Init =
7182 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00007183 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00007184 Info, Subobject, Init) ||
7185 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00007186 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007187 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00007188 return false;
7189 Success = false;
7190 }
Richard Smithd62306a2011-11-10 06:34:14 +00007191 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007192
Richard Smith9543c5e2013-04-22 14:44:29 +00007193 if (!Result.hasArrayFiller())
7194 return Success;
7195
7196 // If we get here, we have a trivial filler, which we can just evaluate
7197 // once and splat over the rest of the array elements.
7198 assert(FillerExpr && "no array filler for incomplete init list");
7199 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7200 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00007201}
7202
Richard Smith410306b2016-12-12 02:53:20 +00007203bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7204 if (E->getCommonExpr() &&
7205 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7206 Info, E->getCommonExpr()->getSourceExpr()))
7207 return false;
7208
7209 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7210
7211 uint64_t Elements = CAT->getSize().getZExtValue();
7212 Result = APValue(APValue::UninitArray(), Elements, Elements);
7213
7214 LValue Subobject = This;
7215 Subobject.addArray(Info, E, CAT);
7216
7217 bool Success = true;
7218 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7219 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7220 Info, Subobject, E->getSubExpr()) ||
7221 !HandleLValueArrayAdjustment(Info, E, Subobject,
7222 CAT->getElementType(), 1)) {
7223 if (!Info.noteFailure())
7224 return false;
7225 Success = false;
7226 }
7227 }
7228
7229 return Success;
7230}
7231
Richard Smith027bf112011-11-17 22:56:20 +00007232bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00007233 return VisitCXXConstructExpr(E, This, &Result, E->getType());
7234}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007235
Richard Smith9543c5e2013-04-22 14:44:29 +00007236bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7237 const LValue &Subobject,
7238 APValue *Value,
7239 QualType Type) {
7240 bool HadZeroInit = !Value->isUninit();
7241
7242 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7243 unsigned N = CAT->getSize().getZExtValue();
7244
7245 // Preserve the array filler if we had prior zero-initialization.
7246 APValue Filler =
7247 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7248 : APValue();
7249
7250 *Value = APValue(APValue::UninitArray(), N, N);
7251
7252 if (HadZeroInit)
7253 for (unsigned I = 0; I != N; ++I)
7254 Value->getArrayInitializedElt(I) = Filler;
7255
7256 // Initialize the elements.
7257 LValue ArrayElt = Subobject;
7258 ArrayElt.addArray(Info, E, CAT);
7259 for (unsigned I = 0; I != N; ++I)
7260 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7261 CAT->getElementType()) ||
7262 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7263 CAT->getElementType(), 1))
7264 return false;
7265
7266 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007267 }
Richard Smith027bf112011-11-17 22:56:20 +00007268
Richard Smith9543c5e2013-04-22 14:44:29 +00007269 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00007270 return Error(E);
7271
Richard Smithb8348f52016-05-12 22:16:28 +00007272 return RecordExprEvaluator(Info, Subobject, *Value)
7273 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00007274}
7275
Richard Smithf3e9e432011-11-07 09:22:26 +00007276//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007277// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007278//
7279// As a GNU extension, we support casting pointers to sufficiently-wide integer
7280// types and back in constant folding. Integer values are thus represented
7281// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00007282//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007283
7284namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007285class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007286 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00007287 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007288public:
Richard Smith2e312c82012-03-03 22:46:17 +00007289 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007290 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007291
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007292 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007293 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007294 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007295 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007296 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007297 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007298 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007299 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007300 return true;
7301 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007302 bool Success(const llvm::APSInt &SI, const Expr *E) {
7303 return Success(SI, E, Result);
7304 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007305
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007306 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007307 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007308 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007309 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007310 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007311 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007312 Result.getInt().setIsUnsigned(
7313 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007314 return true;
7315 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007316 bool Success(const llvm::APInt &I, const Expr *E) {
7317 return Success(I, E, Result);
7318 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007319
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007320 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007321 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007322 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007323 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007324 return true;
7325 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007326 bool Success(uint64_t Value, const Expr *E) {
7327 return Success(Value, E, Result);
7328 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007329
Ken Dyckdbc01912011-03-11 02:13:43 +00007330 bool Success(CharUnits Size, const Expr *E) {
7331 return Success(Size.getQuantity(), E);
7332 }
7333
Richard Smith2e312c82012-03-03 22:46:17 +00007334 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007335 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007336 Result = V;
7337 return true;
7338 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007339 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007340 }
Mike Stump11289f42009-09-09 15:08:12 +00007341
Richard Smithfddd3842011-12-30 21:15:51 +00007342 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007343
Peter Collingbournee9200682011-05-13 03:29:01 +00007344 //===--------------------------------------------------------------------===//
7345 // Visitor Methods
7346 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007347
Chris Lattner7174bf32008-07-12 00:38:25 +00007348 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007349 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007350 }
7351 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007352 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007353 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007354
7355 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7356 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007357 if (CheckReferencedDecl(E, E->getDecl()))
7358 return true;
7359
7360 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007361 }
7362 bool VisitMemberExpr(const MemberExpr *E) {
7363 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007364 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007365 return true;
7366 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007367
7368 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007369 }
7370
Peter Collingbournee9200682011-05-13 03:29:01 +00007371 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007372 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007373 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007374 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007375 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007376
Peter Collingbournee9200682011-05-13 03:29:01 +00007377 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007378 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007379
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007380 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007381 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007382 }
Mike Stump11289f42009-09-09 15:08:12 +00007383
Ted Kremeneke65b0862012-03-06 20:05:56 +00007384 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7385 return Success(E->getValue(), E);
7386 }
Richard Smith410306b2016-12-12 02:53:20 +00007387
7388 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7389 if (Info.ArrayInitIndex == uint64_t(-1)) {
7390 // We were asked to evaluate this subexpression independent of the
7391 // enclosing ArrayInitLoopExpr. We can't do that.
7392 Info.FFDiag(E);
7393 return false;
7394 }
7395 return Success(Info.ArrayInitIndex, E);
7396 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007397
Richard Smith4ce706a2011-10-11 21:43:33 +00007398 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007399 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007400 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007401 }
7402
Douglas Gregor29c42f22012-02-24 07:38:34 +00007403 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7404 return Success(E->getValue(), E);
7405 }
7406
John Wiegley6242b6a2011-04-28 00:16:57 +00007407 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7408 return Success(E->getValue(), E);
7409 }
7410
John Wiegleyf9f65842011-04-25 06:54:41 +00007411 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7412 return Success(E->getValue(), E);
7413 }
7414
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007415 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007416 bool VisitUnaryImag(const UnaryOperator *E);
7417
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007418 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007419 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007420
Eli Friedman4e7a2412009-02-27 04:45:43 +00007421 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007422};
Leonard Chandb01c3a2018-06-20 17:19:40 +00007423
7424class FixedPointExprEvaluator
7425 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
7426 APValue &Result;
7427
7428 public:
7429 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
7430 : ExprEvaluatorBaseTy(info), Result(result) {}
7431
7432 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7433 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7434 assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
7435 "Invalid evaluation result.");
7436 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7437 "Invalid evaluation result.");
7438 Result = APValue(SI);
7439 return true;
7440 }
7441 bool Success(const llvm::APSInt &SI, const Expr *E) {
7442 return Success(SI, E, Result);
7443 }
7444
7445 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7446 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7447 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7448 "Invalid evaluation result.");
7449 Result = APValue(APSInt(I));
7450 Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
7451 return true;
7452 }
7453 bool Success(const llvm::APInt &I, const Expr *E) {
7454 return Success(I, E, Result);
7455 }
7456
7457 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7458 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7459 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7460 return true;
7461 }
7462 bool Success(uint64_t Value, const Expr *E) {
7463 return Success(Value, E, Result);
7464 }
7465
7466 bool Success(CharUnits Size, const Expr *E) {
7467 return Success(Size.getQuantity(), E);
7468 }
7469
7470 bool Success(const APValue &V, const Expr *E) {
7471 if (V.isLValue() || V.isAddrLabelDiff()) {
7472 Result = V;
7473 return true;
7474 }
7475 return Success(V.getInt(), E);
7476 }
7477
7478 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7479
7480 //===--------------------------------------------------------------------===//
7481 // Visitor Methods
7482 //===--------------------------------------------------------------------===//
7483
7484 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
7485 return Success(E->getValue(), E);
7486 }
7487
7488 bool VisitUnaryOperator(const UnaryOperator *E);
7489};
Chris Lattner05706e882008-07-11 18:11:29 +00007490} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007491
Richard Smith11562c52011-10-28 17:51:58 +00007492/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7493/// produce either the integer value or a pointer.
7494///
7495/// GCC has a heinous extension which folds casts between pointer types and
7496/// pointer-sized integral types. We support this by allowing the evaluation of
7497/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7498/// Some simple arithmetic on such values is supported (they are treated much
7499/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007500static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007501 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007502 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007503 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007504}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007505
Richard Smithf57d8cb2011-12-09 22:58:01 +00007506static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007507 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007508 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007509 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007510 if (!Val.isInt()) {
7511 // FIXME: It would be better to produce the diagnostic for casting
7512 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007513 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007514 return false;
7515 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007516 Result = Val.getInt();
7517 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007518}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007519
Richard Smithf57d8cb2011-12-09 22:58:01 +00007520/// Check whether the given declaration can be directly converted to an integral
7521/// rvalue. If not, no diagnostic is produced; there are other things we can
7522/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007523bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007524 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007525 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007526 // Check for signedness/width mismatches between E type and ECD value.
7527 bool SameSign = (ECD->getInitVal().isSigned()
7528 == E->getType()->isSignedIntegerOrEnumerationType());
7529 bool SameWidth = (ECD->getInitVal().getBitWidth()
7530 == Info.Ctx.getIntWidth(E->getType()));
7531 if (SameSign && SameWidth)
7532 return Success(ECD->getInitVal(), E);
7533 else {
7534 // Get rid of mismatch (otherwise Success assertions will fail)
7535 // by computing a new value matching the type of E.
7536 llvm::APSInt Val = ECD->getInitVal();
7537 if (!SameSign)
7538 Val.setIsSigned(!ECD->getInitVal().isSigned());
7539 if (!SameWidth)
7540 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7541 return Success(Val, E);
7542 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007543 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007544 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007545}
7546
Richard Smith08b682b2018-05-23 21:18:00 +00007547/// Values returned by __builtin_classify_type, chosen to match the values
7548/// produced by GCC's builtin.
7549enum class GCCTypeClass {
7550 None = -1,
7551 Void = 0,
7552 Integer = 1,
7553 // GCC reserves 2 for character types, but instead classifies them as
7554 // integers.
7555 Enum = 3,
7556 Bool = 4,
7557 Pointer = 5,
7558 // GCC reserves 6 for references, but appears to never use it (because
7559 // expressions never have reference type, presumably).
7560 PointerToDataMember = 7,
7561 RealFloat = 8,
7562 Complex = 9,
7563 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7564 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7565 // GCC claims to reserve 11 for pointers to member functions, but *actually*
7566 // uses 12 for that purpose, same as for a class or struct. Maybe it
7567 // internally implements a pointer to member as a struct? Who knows.
7568 PointerToMemberFunction = 12, // Not a bug, see above.
7569 ClassOrStruct = 12,
7570 Union = 13,
7571 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7572 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7573 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7574 // literals.
7575};
7576
Chris Lattner86ee2862008-10-06 06:40:35 +00007577/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7578/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00007579static GCCTypeClass
7580EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7581 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00007582
Richard Smith08b682b2018-05-23 21:18:00 +00007583 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007584 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7585
7586 switch (CanTy->getTypeClass()) {
7587#define TYPE(ID, BASE)
7588#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7589#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7590#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7591#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00007592 case Type::Auto:
7593 case Type::DeducedTemplateSpecialization:
7594 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007595
7596 case Type::Builtin:
7597 switch (BT->getKind()) {
7598#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00007599#define SIGNED_TYPE(ID, SINGLETON_ID) \
7600 case BuiltinType::ID: return GCCTypeClass::Integer;
7601#define FLOATING_TYPE(ID, SINGLETON_ID) \
7602 case BuiltinType::ID: return GCCTypeClass::RealFloat;
7603#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7604 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007605#include "clang/AST/BuiltinTypes.def"
7606 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00007607 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007608
7609 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00007610 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007611
Richard Smith08b682b2018-05-23 21:18:00 +00007612 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007613 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00007614 case BuiltinType::WChar_U:
7615 case BuiltinType::Char8:
7616 case BuiltinType::Char16:
7617 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007618 case BuiltinType::UShort:
7619 case BuiltinType::UInt:
7620 case BuiltinType::ULong:
7621 case BuiltinType::ULongLong:
7622 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00007623 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007624
Leonard Chanf921d852018-06-04 16:07:52 +00007625 case BuiltinType::UShortAccum:
7626 case BuiltinType::UAccum:
7627 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00007628 case BuiltinType::UShortFract:
7629 case BuiltinType::UFract:
7630 case BuiltinType::ULongFract:
7631 case BuiltinType::SatUShortAccum:
7632 case BuiltinType::SatUAccum:
7633 case BuiltinType::SatULongAccum:
7634 case BuiltinType::SatUShortFract:
7635 case BuiltinType::SatUFract:
7636 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00007637 return GCCTypeClass::None;
7638
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007639 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007640
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007641 case BuiltinType::ObjCId:
7642 case BuiltinType::ObjCClass:
7643 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007644#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7645 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007646#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007647 case BuiltinType::OCLSampler:
7648 case BuiltinType::OCLEvent:
7649 case BuiltinType::OCLClkEvent:
7650 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007651 case BuiltinType::OCLReserveID:
Richard Smith08b682b2018-05-23 21:18:00 +00007652 return GCCTypeClass::None;
7653
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007654 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00007655 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007656 };
Richard Smith08b682b2018-05-23 21:18:00 +00007657 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007658
7659 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00007660 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007661
7662 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007663 case Type::ConstantArray:
7664 case Type::VariableArray:
7665 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00007666 case Type::FunctionNoProto:
7667 case Type::FunctionProto:
7668 return GCCTypeClass::Pointer;
7669
7670 case Type::MemberPointer:
7671 return CanTy->isMemberDataPointerType()
7672 ? GCCTypeClass::PointerToDataMember
7673 : GCCTypeClass::PointerToMemberFunction;
7674
7675 case Type::Complex:
7676 return GCCTypeClass::Complex;
7677
7678 case Type::Record:
7679 return CanTy->isUnionType() ? GCCTypeClass::Union
7680 : GCCTypeClass::ClassOrStruct;
7681
7682 case Type::Atomic:
7683 // GCC classifies _Atomic T the same as T.
7684 return EvaluateBuiltinClassifyType(
7685 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007686
7687 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007688 case Type::Vector:
7689 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007690 case Type::ObjCObject:
7691 case Type::ObjCInterface:
7692 case Type::ObjCObjectPointer:
7693 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00007694 // GCC classifies vectors as None. We follow its lead and classify all
7695 // other types that don't fit into the regular classification the same way.
7696 return GCCTypeClass::None;
7697
7698 case Type::LValueReference:
7699 case Type::RValueReference:
7700 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007701 }
7702
Richard Smith08b682b2018-05-23 21:18:00 +00007703 llvm_unreachable("unexpected type class");
7704}
7705
7706/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7707/// as GCC.
7708static GCCTypeClass
7709EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7710 // If no argument was supplied, default to None. This isn't
7711 // ideal, however it is what gcc does.
7712 if (E->getNumArgs() == 0)
7713 return GCCTypeClass::None;
7714
7715 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7716 // being an ICE, but still folds it to a constant using the type of the first
7717 // argument.
7718 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00007719}
7720
Richard Smith5fab0c92011-12-28 19:48:30 +00007721/// EvaluateBuiltinConstantPForLValue - Determine the result of
7722/// __builtin_constant_p when applied to the given lvalue.
7723///
7724/// An lvalue is only "constant" if it is a pointer or reference to the first
7725/// character of a string literal.
7726template<typename LValue>
7727static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007728 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007729 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7730}
7731
7732/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7733/// GCC as we can manage.
7734static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7735 QualType ArgType = Arg->getType();
7736
7737 // __builtin_constant_p always has one operand. The rules which gcc follows
7738 // are not precisely documented, but are as follows:
7739 //
7740 // - If the operand is of integral, floating, complex or enumeration type,
7741 // and can be folded to a known value of that type, it returns 1.
7742 // - If the operand and can be folded to a pointer to the first character
7743 // of a string literal (or such a pointer cast to an integral type), it
7744 // returns 1.
7745 //
7746 // Otherwise, it returns 0.
7747 //
7748 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7749 // its support for this does not currently work.
7750 if (ArgType->isIntegralOrEnumerationType()) {
7751 Expr::EvalResult Result;
7752 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7753 return false;
7754
7755 APValue &V = Result.Val;
7756 if (V.getKind() == APValue::Int)
7757 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007758 if (V.getKind() == APValue::LValue)
7759 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007760 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7761 return Arg->isEvaluatable(Ctx);
7762 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7763 LValue LV;
7764 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007765 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007766 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7767 : EvaluatePointer(Arg, LV, Info)) &&
7768 !Status.HasSideEffects)
7769 return EvaluateBuiltinConstantPForLValue(LV);
7770 }
7771
7772 // Anything else isn't considered to be sufficiently constant.
7773 return false;
7774}
7775
John McCall95007602010-05-10 23:27:23 +00007776/// Retrieves the "underlying object type" of the given expression,
7777/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007778static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007779 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7780 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007781 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007782 } else if (const Expr *E = B.get<const Expr*>()) {
7783 if (isa<CompoundLiteralExpr>(E))
7784 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007785 }
7786
7787 return QualType();
7788}
7789
George Burgess IV3a03fab2015-09-04 21:28:13 +00007790/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007791/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007792/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007793/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7794///
7795/// Always returns an RValue with a pointer representation.
7796static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7797 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7798
7799 auto *NoParens = E->IgnoreParens();
7800 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007801 if (Cast == nullptr)
7802 return NoParens;
7803
7804 // We only conservatively allow a few kinds of casts, because this code is
7805 // inherently a simple solution that seeks to support the common case.
7806 auto CastKind = Cast->getCastKind();
7807 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7808 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007809 return NoParens;
7810
7811 auto *SubExpr = Cast->getSubExpr();
7812 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7813 return NoParens;
7814 return ignorePointerCastsAndParens(SubExpr);
7815}
7816
George Burgess IVa51c4072015-10-16 01:49:01 +00007817/// Checks to see if the given LValue's Designator is at the end of the LValue's
7818/// record layout. e.g.
7819/// struct { struct { int a, b; } fst, snd; } obj;
7820/// obj.fst // no
7821/// obj.snd // yes
7822/// obj.fst.a // no
7823/// obj.fst.b // no
7824/// obj.snd.a // no
7825/// obj.snd.b // yes
7826///
7827/// Please note: this function is specialized for how __builtin_object_size
7828/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007829///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007830/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7831/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007832static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7833 assert(!LVal.Designator.Invalid);
7834
George Burgess IV4168d752016-06-27 19:40:41 +00007835 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7836 const RecordDecl *Parent = FD->getParent();
7837 Invalid = Parent->isInvalidDecl();
7838 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007839 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007840 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007841 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7842 };
7843
7844 auto &Base = LVal.getLValueBase();
7845 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7846 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007847 bool Invalid;
7848 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7849 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007850 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007851 for (auto *FD : IFD->chain()) {
7852 bool Invalid;
7853 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7854 return Invalid;
7855 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007856 }
7857 }
7858
George Burgess IVe3763372016-12-22 02:50:20 +00007859 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007860 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007861 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007862 // If we don't know the array bound, conservatively assume we're looking at
7863 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007864 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007865 if (BaseType->isIncompleteArrayType())
7866 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7867 else
7868 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007869 }
7870
7871 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7872 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007873 if (BaseType->isArrayType()) {
7874 // Because __builtin_object_size treats arrays as objects, we can ignore
7875 // the index iff this is the last array in the Designator.
7876 if (I + 1 == E)
7877 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007878 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7879 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007880 if (Index + 1 != CAT->getSize())
7881 return false;
7882 BaseType = CAT->getElementType();
7883 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007884 const auto *CT = BaseType->castAs<ComplexType>();
7885 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007886 if (Index != 1)
7887 return false;
7888 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007889 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007890 bool Invalid;
7891 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7892 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007893 BaseType = FD->getType();
7894 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007895 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007896 return false;
7897 }
7898 }
7899 return true;
7900}
7901
George Burgess IVe3763372016-12-22 02:50:20 +00007902/// Tests to see if the LValue has a user-specified designator (that isn't
7903/// necessarily valid). Note that this always returns 'true' if the LValue has
7904/// an unsized array as its first designator entry, because there's currently no
7905/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007906static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007907 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007908 return false;
7909
George Burgess IVe3763372016-12-22 02:50:20 +00007910 if (!LVal.Designator.Entries.empty())
7911 return LVal.Designator.isMostDerivedAnUnsizedArray();
7912
George Burgess IVa51c4072015-10-16 01:49:01 +00007913 if (!LVal.InvalidBase)
7914 return true;
7915
George Burgess IVe3763372016-12-22 02:50:20 +00007916 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7917 // the LValueBase.
7918 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7919 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007920}
7921
George Burgess IVe3763372016-12-22 02:50:20 +00007922/// Attempts to detect a user writing into a piece of memory that's impossible
7923/// to figure out the size of by just using types.
7924static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7925 const SubobjectDesignator &Designator = LVal.Designator;
7926 // Notes:
7927 // - Users can only write off of the end when we have an invalid base. Invalid
7928 // bases imply we don't know where the memory came from.
7929 // - We used to be a bit more aggressive here; we'd only be conservative if
7930 // the array at the end was flexible, or if it had 0 or 1 elements. This
7931 // broke some common standard library extensions (PR30346), but was
7932 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7933 // with some sort of whitelist. OTOH, it seems that GCC is always
7934 // conservative with the last element in structs (if it's an array), so our
7935 // current behavior is more compatible than a whitelisting approach would
7936 // be.
7937 return LVal.InvalidBase &&
7938 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7939 Designator.MostDerivedIsArrayElement &&
7940 isDesignatorAtObjectEnd(Ctx, LVal);
7941}
7942
7943/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7944/// Fails if the conversion would cause loss of precision.
7945static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7946 CharUnits &Result) {
7947 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7948 if (Int.ugt(CharUnitsMax))
7949 return false;
7950 Result = CharUnits::fromQuantity(Int.getZExtValue());
7951 return true;
7952}
7953
7954/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7955/// determine how many bytes exist from the beginning of the object to either
7956/// the end of the current subobject, or the end of the object itself, depending
7957/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007958///
George Burgess IVe3763372016-12-22 02:50:20 +00007959/// If this returns false, the value of Result is undefined.
7960static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7961 unsigned Type, const LValue &LVal,
7962 CharUnits &EndOffset) {
7963 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007964
George Burgess IV7fb7e362017-01-03 23:35:19 +00007965 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7966 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7967 return false;
7968 return HandleSizeof(Info, ExprLoc, Ty, Result);
7969 };
7970
George Burgess IVe3763372016-12-22 02:50:20 +00007971 // We want to evaluate the size of the entire object. This is a valid fallback
7972 // for when Type=1 and the designator is invalid, because we're asked for an
7973 // upper-bound.
7974 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7975 // Type=3 wants a lower bound, so we can't fall back to this.
7976 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007977 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007978
7979 llvm::APInt APEndOffset;
7980 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7981 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7982 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7983
7984 if (LVal.InvalidBase)
7985 return false;
7986
7987 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007988 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007989 }
7990
George Burgess IVe3763372016-12-22 02:50:20 +00007991 // We want to evaluate the size of a subobject.
7992 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007993
7994 // The following is a moderately common idiom in C:
7995 //
7996 // struct Foo { int a; char c[1]; };
7997 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7998 // strcpy(&F->c[0], Bar);
7999 //
George Burgess IVe3763372016-12-22 02:50:20 +00008000 // In order to not break too much legacy code, we need to support it.
8001 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8002 // If we can resolve this to an alloc_size call, we can hand that back,
8003 // because we know for certain how many bytes there are to write to.
8004 llvm::APInt APEndOffset;
8005 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8006 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8007 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8008
8009 // If we cannot determine the size of the initial allocation, then we can't
8010 // given an accurate upper-bound. However, we are still able to give
8011 // conservative lower-bounds for Type=3.
8012 if (Type == 1)
8013 return false;
8014 }
8015
8016 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00008017 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008018 return false;
8019
George Burgess IVe3763372016-12-22 02:50:20 +00008020 // According to the GCC documentation, we want the size of the subobject
8021 // denoted by the pointer. But that's not quite right -- what we actually
8022 // want is the size of the immediately-enclosing array, if there is one.
8023 int64_t ElemsRemaining;
8024 if (Designator.MostDerivedIsArrayElement &&
8025 Designator.Entries.size() == Designator.MostDerivedPathLength) {
8026 uint64_t ArraySize = Designator.getMostDerivedArraySize();
8027 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
8028 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8029 } else {
8030 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8031 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008032
George Burgess IVe3763372016-12-22 02:50:20 +00008033 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8034 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008035}
8036
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008037/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00008038/// returns true and stores the result in @p Size.
8039///
8040/// If @p WasError is non-null, this will report whether the failure to evaluate
8041/// is to be treated as an Error in IntExprEvaluator.
8042static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8043 EvalInfo &Info, uint64_t &Size) {
8044 // Determine the denoted object.
8045 LValue LVal;
8046 {
8047 // The operand of __builtin_object_size is never evaluated for side-effects.
8048 // If there are any, but we can determine the pointed-to object anyway, then
8049 // ignore the side-effects.
8050 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00008051 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00008052
8053 if (E->isGLValue()) {
8054 // It's possible for us to be given GLValues if we're called via
8055 // Expr::tryEvaluateObjectSize.
8056 APValue RVal;
8057 if (!EvaluateAsRValue(Info, E, RVal))
8058 return false;
8059 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00008060 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8061 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00008062 return false;
8063 }
8064
8065 // If we point to before the start of the object, there are no accessible
8066 // bytes.
8067 if (LVal.getLValueOffset().isNegative()) {
8068 Size = 0;
8069 return true;
8070 }
8071
8072 CharUnits EndOffset;
8073 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8074 return false;
8075
8076 // If we've fallen outside of the end offset, just pretend there's nothing to
8077 // write to/read from.
8078 if (EndOffset <= LVal.getLValueOffset())
8079 Size = 0;
8080 else
8081 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8082 return true;
John McCall95007602010-05-10 23:27:23 +00008083}
8084
Peter Collingbournee9200682011-05-13 03:29:01 +00008085bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00008086 if (unsigned BuiltinOp = E->getBuiltinCallee())
8087 return VisitBuiltinCallExpr(E, BuiltinOp);
8088
8089 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8090}
8091
8092bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8093 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00008094 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008095 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00008096 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00008097
8098 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00008099 // The type was checked when we built the expression.
8100 unsigned Type =
8101 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8102 assert(Type <= 3 && "unexpected type");
8103
George Burgess IVe3763372016-12-22 02:50:20 +00008104 uint64_t Size;
8105 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8106 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00008107
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008108 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00008109 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00008110
Richard Smith01ade172012-05-23 04:13:20 +00008111 // Expression had no side effects, but we couldn't statically determine the
8112 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008113 switch (Info.EvalMode) {
8114 case EvalInfo::EM_ConstantExpression:
8115 case EvalInfo::EM_PotentialConstantExpression:
8116 case EvalInfo::EM_ConstantFold:
8117 case EvalInfo::EM_EvaluateForOverflow:
8118 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008119 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008120 return Error(E);
8121 case EvalInfo::EM_ConstantExpressionUnevaluated:
8122 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008123 // Reduce it to a constant now.
8124 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008125 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00008126
8127 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00008128 }
8129
Tim Northover314fbfa2018-11-02 13:14:11 +00008130 case Builtin::BI__builtin_os_log_format_buffer_size: {
8131 analyze_os_log::OSLogBufferLayout Layout;
8132 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
8133 return Success(Layout.size().getQuantity(), E);
8134 }
8135
Benjamin Kramera801f4a2012-10-06 14:42:22 +00008136 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00008137 case Builtin::BI__builtin_bswap32:
8138 case Builtin::BI__builtin_bswap64: {
8139 APSInt Val;
8140 if (!EvaluateInteger(E->getArg(0), Val, Info))
8141 return false;
8142
8143 return Success(Val.byteSwap(), E);
8144 }
8145
Richard Smith8889a3d2013-06-13 06:26:32 +00008146 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00008147 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00008148
Craig Topperf95a6d92018-08-08 22:31:12 +00008149 case Builtin::BI__builtin_clrsb:
8150 case Builtin::BI__builtin_clrsbl:
8151 case Builtin::BI__builtin_clrsbll: {
8152 APSInt Val;
8153 if (!EvaluateInteger(E->getArg(0), Val, Info))
8154 return false;
8155
8156 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8157 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008158
Richard Smith80b3c8e2013-06-13 05:04:16 +00008159 case Builtin::BI__builtin_clz:
8160 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008161 case Builtin::BI__builtin_clzll:
8162 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008163 APSInt Val;
8164 if (!EvaluateInteger(E->getArg(0), Val, Info))
8165 return false;
8166 if (!Val)
8167 return Error(E);
8168
8169 return Success(Val.countLeadingZeros(), E);
8170 }
8171
Richard Smith8889a3d2013-06-13 06:26:32 +00008172 case Builtin::BI__builtin_constant_p:
8173 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
8174
Richard Smith80b3c8e2013-06-13 05:04:16 +00008175 case Builtin::BI__builtin_ctz:
8176 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008177 case Builtin::BI__builtin_ctzll:
8178 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008179 APSInt Val;
8180 if (!EvaluateInteger(E->getArg(0), Val, Info))
8181 return false;
8182 if (!Val)
8183 return Error(E);
8184
8185 return Success(Val.countTrailingZeros(), E);
8186 }
8187
Richard Smith8889a3d2013-06-13 06:26:32 +00008188 case Builtin::BI__builtin_eh_return_data_regno: {
8189 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8190 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8191 return Success(Operand, E);
8192 }
8193
8194 case Builtin::BI__builtin_expect:
8195 return Visit(E->getArg(0));
8196
8197 case Builtin::BI__builtin_ffs:
8198 case Builtin::BI__builtin_ffsl:
8199 case Builtin::BI__builtin_ffsll: {
8200 APSInt Val;
8201 if (!EvaluateInteger(E->getArg(0), Val, Info))
8202 return false;
8203
8204 unsigned N = Val.countTrailingZeros();
8205 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8206 }
8207
8208 case Builtin::BI__builtin_fpclassify: {
8209 APFloat Val(0.0);
8210 if (!EvaluateFloat(E->getArg(5), Val, Info))
8211 return false;
8212 unsigned Arg;
8213 switch (Val.getCategory()) {
8214 case APFloat::fcNaN: Arg = 0; break;
8215 case APFloat::fcInfinity: Arg = 1; break;
8216 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8217 case APFloat::fcZero: Arg = 4; break;
8218 }
8219 return Visit(E->getArg(Arg));
8220 }
8221
8222 case Builtin::BI__builtin_isinf_sign: {
8223 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00008224 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00008225 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8226 }
8227
Richard Smithea3019d2013-10-15 19:07:14 +00008228 case Builtin::BI__builtin_isinf: {
8229 APFloat Val(0.0);
8230 return EvaluateFloat(E->getArg(0), Val, Info) &&
8231 Success(Val.isInfinity() ? 1 : 0, E);
8232 }
8233
8234 case Builtin::BI__builtin_isfinite: {
8235 APFloat Val(0.0);
8236 return EvaluateFloat(E->getArg(0), Val, Info) &&
8237 Success(Val.isFinite() ? 1 : 0, E);
8238 }
8239
8240 case Builtin::BI__builtin_isnan: {
8241 APFloat Val(0.0);
8242 return EvaluateFloat(E->getArg(0), Val, Info) &&
8243 Success(Val.isNaN() ? 1 : 0, E);
8244 }
8245
8246 case Builtin::BI__builtin_isnormal: {
8247 APFloat Val(0.0);
8248 return EvaluateFloat(E->getArg(0), Val, Info) &&
8249 Success(Val.isNormal() ? 1 : 0, E);
8250 }
8251
Richard Smith8889a3d2013-06-13 06:26:32 +00008252 case Builtin::BI__builtin_parity:
8253 case Builtin::BI__builtin_parityl:
8254 case Builtin::BI__builtin_parityll: {
8255 APSInt Val;
8256 if (!EvaluateInteger(E->getArg(0), Val, Info))
8257 return false;
8258
8259 return Success(Val.countPopulation() % 2, E);
8260 }
8261
Richard Smith80b3c8e2013-06-13 05:04:16 +00008262 case Builtin::BI__builtin_popcount:
8263 case Builtin::BI__builtin_popcountl:
8264 case Builtin::BI__builtin_popcountll: {
8265 APSInt Val;
8266 if (!EvaluateInteger(E->getArg(0), Val, Info))
8267 return false;
8268
8269 return Success(Val.countPopulation(), E);
8270 }
8271
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008272 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00008273 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00008274 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008275 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008276 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00008277 << /*isConstexpr*/0 << /*isConstructor*/0
8278 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00008279 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00008280 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008281 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008282 case Builtin::BI__builtin_strlen:
8283 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00008284 // As an extension, we support __builtin_strlen() as a constant expression,
8285 // and support folding strlen() to a constant.
8286 LValue String;
8287 if (!EvaluatePointer(E->getArg(0), String, Info))
8288 return false;
8289
Richard Smith8110c9d2016-11-29 19:45:17 +00008290 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8291
Richard Smithe6c19f22013-11-15 02:10:04 +00008292 // Fast path: if it's a string literal, search the string value.
8293 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8294 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008295 // The string literal may have embedded null characters. Find the first
8296 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00008297 StringRef Str = S->getBytes();
8298 int64_t Off = String.Offset.getQuantity();
8299 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008300 S->getCharByteWidth() == 1 &&
8301 // FIXME: Add fast-path for wchar_t too.
8302 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00008303 Str = Str.substr(Off);
8304
8305 StringRef::size_type Pos = Str.find(0);
8306 if (Pos != StringRef::npos)
8307 Str = Str.substr(0, Pos);
8308
8309 return Success(Str.size(), E);
8310 }
8311
8312 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008313 }
Richard Smithe6c19f22013-11-15 02:10:04 +00008314
8315 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00008316 for (uint64_t Strlen = 0; /**/; ++Strlen) {
8317 APValue Char;
8318 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8319 !Char.isInt())
8320 return false;
8321 if (!Char.getInt())
8322 return Success(Strlen, E);
8323 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8324 return false;
8325 }
8326 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008327
Richard Smithe151bab2016-11-11 23:43:35 +00008328 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008329 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008330 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008331 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008332 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008333 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008334 // A call to strlen is not a constant expression.
8335 if (Info.getLangOpts().CPlusPlus11)
8336 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8337 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00008338 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00008339 else
8340 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008341 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00008342 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008343 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008344 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008345 case Builtin::BI__builtin_wcsncmp:
8346 case Builtin::BI__builtin_memcmp:
8347 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00008348 LValue String1, String2;
8349 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8350 !EvaluatePointer(E->getArg(1), String2, Info))
8351 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00008352
8353 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8354
Richard Smithe151bab2016-11-11 23:43:35 +00008355 uint64_t MaxLength = uint64_t(-1);
8356 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008357 BuiltinOp != Builtin::BIwcscmp &&
8358 BuiltinOp != Builtin::BI__builtin_strcmp &&
8359 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00008360 APSInt N;
8361 if (!EvaluateInteger(E->getArg(2), N, Info))
8362 return false;
8363 MaxLength = N.getExtValue();
8364 }
8365 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008366 BuiltinOp != Builtin::BIwmemcmp &&
8367 BuiltinOp != Builtin::BI__builtin_memcmp &&
8368 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00008369 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8370 BuiltinOp == Builtin::BIwcsncmp ||
8371 BuiltinOp == Builtin::BIwmemcmp ||
8372 BuiltinOp == Builtin::BI__builtin_wcscmp ||
8373 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8374 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Richard Smithe151bab2016-11-11 23:43:35 +00008375 for (; MaxLength; --MaxLength) {
8376 APValue Char1, Char2;
8377 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
8378 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
8379 !Char1.isInt() || !Char2.isInt())
8380 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00008381 if (Char1.getInt() != Char2.getInt()) {
8382 if (IsWide) // wmemcmp compares with wchar_t signedness.
8383 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8384 // memcmp always compares unsigned chars.
8385 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8386 }
Richard Smithe151bab2016-11-11 23:43:35 +00008387 if (StopAtNull && !Char1.getInt())
8388 return Success(0, E);
8389 assert(!(StopAtNull && !Char2.getInt()));
8390 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
8391 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
8392 return false;
8393 }
8394 // We hit the strncmp / memcmp limit.
8395 return Success(0, E);
8396 }
8397
Richard Smith01ba47d2012-04-13 00:45:38 +00008398 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00008399 case Builtin::BI__atomic_is_lock_free:
8400 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00008401 APSInt SizeVal;
8402 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8403 return false;
8404
8405 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8406 // of two less than the maximum inline atomic width, we know it is
8407 // lock-free. If the size isn't a power of two, or greater than the
8408 // maximum alignment where we promote atomics, we know it is not lock-free
8409 // (at least not in the sense of atomic_is_lock_free). Otherwise,
8410 // the answer can only be determined at runtime; for example, 16-byte
8411 // atomics have lock-free implementations on some, but not all,
8412 // x86-64 processors.
8413
8414 // Check power-of-two.
8415 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00008416 if (Size.isPowerOfTwo()) {
8417 // Check against inlining width.
8418 unsigned InlineWidthBits =
8419 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8420 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8421 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8422 Size == CharUnits::One() ||
8423 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8424 Expr::NPC_NeverValueDependent))
8425 // OK, we will inline appropriately-aligned operations of this size,
8426 // and _Atomic(T) is appropriately-aligned.
8427 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008428
Richard Smith01ba47d2012-04-13 00:45:38 +00008429 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8430 castAs<PointerType>()->getPointeeType();
8431 if (!PointeeType->isIncompleteType() &&
8432 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8433 // OK, we will inline operations on this object.
8434 return Success(1, E);
8435 }
8436 }
8437 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008438
Richard Smith01ba47d2012-04-13 00:45:38 +00008439 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8440 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008441 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008442 case Builtin::BIomp_is_initial_device:
8443 // We can decide statically which value the runtime would return if called.
8444 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00008445 case Builtin::BI__builtin_add_overflow:
8446 case Builtin::BI__builtin_sub_overflow:
8447 case Builtin::BI__builtin_mul_overflow:
8448 case Builtin::BI__builtin_sadd_overflow:
8449 case Builtin::BI__builtin_uadd_overflow:
8450 case Builtin::BI__builtin_uaddl_overflow:
8451 case Builtin::BI__builtin_uaddll_overflow:
8452 case Builtin::BI__builtin_usub_overflow:
8453 case Builtin::BI__builtin_usubl_overflow:
8454 case Builtin::BI__builtin_usubll_overflow:
8455 case Builtin::BI__builtin_umul_overflow:
8456 case Builtin::BI__builtin_umull_overflow:
8457 case Builtin::BI__builtin_umulll_overflow:
8458 case Builtin::BI__builtin_saddl_overflow:
8459 case Builtin::BI__builtin_saddll_overflow:
8460 case Builtin::BI__builtin_ssub_overflow:
8461 case Builtin::BI__builtin_ssubl_overflow:
8462 case Builtin::BI__builtin_ssubll_overflow:
8463 case Builtin::BI__builtin_smul_overflow:
8464 case Builtin::BI__builtin_smull_overflow:
8465 case Builtin::BI__builtin_smulll_overflow: {
8466 LValue ResultLValue;
8467 APSInt LHS, RHS;
8468
8469 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
8470 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
8471 !EvaluateInteger(E->getArg(1), RHS, Info) ||
8472 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
8473 return false;
8474
8475 APSInt Result;
8476 bool DidOverflow = false;
8477
8478 // If the types don't have to match, enlarge all 3 to the largest of them.
8479 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8480 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8481 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8482 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
8483 ResultType->isSignedIntegerOrEnumerationType();
8484 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
8485 ResultType->isSignedIntegerOrEnumerationType();
8486 uint64_t LHSSize = LHS.getBitWidth();
8487 uint64_t RHSSize = RHS.getBitWidth();
8488 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
8489 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
8490
8491 // Add an additional bit if the signedness isn't uniformly agreed to. We
8492 // could do this ONLY if there is a signed and an unsigned that both have
8493 // MaxBits, but the code to check that is pretty nasty. The issue will be
8494 // caught in the shrink-to-result later anyway.
8495 if (IsSigned && !AllSigned)
8496 ++MaxBits;
8497
8498 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
8499 !IsSigned);
8500 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
8501 !IsSigned);
8502 Result = APSInt(MaxBits, !IsSigned);
8503 }
8504
8505 // Find largest int.
8506 switch (BuiltinOp) {
8507 default:
8508 llvm_unreachable("Invalid value for BuiltinOp");
8509 case Builtin::BI__builtin_add_overflow:
8510 case Builtin::BI__builtin_sadd_overflow:
8511 case Builtin::BI__builtin_saddl_overflow:
8512 case Builtin::BI__builtin_saddll_overflow:
8513 case Builtin::BI__builtin_uadd_overflow:
8514 case Builtin::BI__builtin_uaddl_overflow:
8515 case Builtin::BI__builtin_uaddll_overflow:
8516 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
8517 : LHS.uadd_ov(RHS, DidOverflow);
8518 break;
8519 case Builtin::BI__builtin_sub_overflow:
8520 case Builtin::BI__builtin_ssub_overflow:
8521 case Builtin::BI__builtin_ssubl_overflow:
8522 case Builtin::BI__builtin_ssubll_overflow:
8523 case Builtin::BI__builtin_usub_overflow:
8524 case Builtin::BI__builtin_usubl_overflow:
8525 case Builtin::BI__builtin_usubll_overflow:
8526 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
8527 : LHS.usub_ov(RHS, DidOverflow);
8528 break;
8529 case Builtin::BI__builtin_mul_overflow:
8530 case Builtin::BI__builtin_smul_overflow:
8531 case Builtin::BI__builtin_smull_overflow:
8532 case Builtin::BI__builtin_smulll_overflow:
8533 case Builtin::BI__builtin_umul_overflow:
8534 case Builtin::BI__builtin_umull_overflow:
8535 case Builtin::BI__builtin_umulll_overflow:
8536 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
8537 : LHS.umul_ov(RHS, DidOverflow);
8538 break;
8539 }
8540
8541 // In the case where multiple sizes are allowed, truncate and see if
8542 // the values are the same.
8543 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8544 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8545 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8546 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
8547 // since it will give us the behavior of a TruncOrSelf in the case where
8548 // its parameter <= its size. We previously set Result to be at least the
8549 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
8550 // will work exactly like TruncOrSelf.
8551 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
8552 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
8553
8554 if (!APSInt::isSameValue(Temp, Result))
8555 DidOverflow = true;
8556 Result = Temp;
8557 }
8558
8559 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +00008560 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
8561 return false;
Erich Keane00958272018-06-13 20:43:27 +00008562 return Success(DidOverflow, E);
8563 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008564 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008565}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008566
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008567/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +00008568/// object referred to by the lvalue.
8569static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8570 const LValue &LV) {
8571 // A null pointer can be viewed as being "past the end" but we don't
8572 // choose to look at it that way here.
8573 if (!LV.getLValueBase())
8574 return false;
8575
8576 // If the designator is valid and refers to a subobject, we're not pointing
8577 // past the end.
8578 if (!LV.getLValueDesignator().Invalid &&
8579 !LV.getLValueDesignator().isOnePastTheEnd())
8580 return false;
8581
David Majnemerc378ca52015-08-29 08:32:55 +00008582 // A pointer to an incomplete type might be past-the-end if the type's size is
8583 // zero. We cannot tell because the type is incomplete.
8584 QualType Ty = getType(LV.getLValueBase());
8585 if (Ty->isIncompleteType())
8586 return true;
8587
Richard Smithd20f1e62014-10-21 23:01:04 +00008588 // We're a past-the-end pointer if we point to the byte after the object,
8589 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008590 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008591 return LV.getLValueOffset() == Size;
8592}
8593
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008594namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008595
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008596/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008597///
8598/// We use a data recursive algorithm for binary operators so that we are able
8599/// to handle extreme cases of chained binary operators without causing stack
8600/// overflow.
8601class DataRecursiveIntBinOpEvaluator {
8602 struct EvalResult {
8603 APValue Val;
8604 bool Failed;
8605
8606 EvalResult() : Failed(false) { }
8607
8608 void swap(EvalResult &RHS) {
8609 Val.swap(RHS.Val);
8610 Failed = RHS.Failed;
8611 RHS.Failed = false;
8612 }
8613 };
8614
8615 struct Job {
8616 const Expr *E;
8617 EvalResult LHSResult; // meaningful only for binary operator expression.
8618 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008619
David Blaikie73726062015-08-12 23:09:24 +00008620 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008621 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008622
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008623 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008624 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008625 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008626
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008627 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008628 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008629 };
8630
8631 SmallVector<Job, 16> Queue;
8632
8633 IntExprEvaluator &IntEval;
8634 EvalInfo &Info;
8635 APValue &FinalResult;
8636
8637public:
8638 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8639 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8640
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008641 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008642 /// data recursively.
8643 /// We handle binary operators that are comma, logical, or that have operands
8644 /// with integral or enumeration type.
8645 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008646 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8647 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +00008648 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008649 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008650 }
8651
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008652 bool Traverse(const BinaryOperator *E) {
8653 enqueue(E);
8654 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008655 while (!Queue.empty())
8656 process(PrevResult);
8657
8658 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008659
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008660 FinalResult.swap(PrevResult.Val);
8661 return true;
8662 }
8663
8664private:
8665 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8666 return IntEval.Success(Value, E, Result);
8667 }
8668 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8669 return IntEval.Success(Value, E, Result);
8670 }
8671 bool Error(const Expr *E) {
8672 return IntEval.Error(E);
8673 }
8674 bool Error(const Expr *E, diag::kind D) {
8675 return IntEval.Error(E, D);
8676 }
8677
8678 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8679 return Info.CCEDiag(E, D);
8680 }
8681
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008682 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008683 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008684 bool &SuppressRHSDiags);
8685
8686 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8687 const BinaryOperator *E, APValue &Result);
8688
8689 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8690 Result.Failed = !Evaluate(Result.Val, Info, E);
8691 if (Result.Failed)
8692 Result.Val = APValue();
8693 }
8694
Richard Trieuba4d0872012-03-21 23:30:30 +00008695 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008696
8697 void enqueue(const Expr *E) {
8698 E = E->IgnoreParens();
8699 Queue.resize(Queue.size()+1);
8700 Queue.back().E = E;
8701 Queue.back().Kind = Job::AnyExprKind;
8702 }
8703};
8704
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008705}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008706
8707bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008708 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008709 bool &SuppressRHSDiags) {
8710 if (E->getOpcode() == BO_Comma) {
8711 // Ignore LHS but note if we could not evaluate it.
8712 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008713 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008714 return true;
8715 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008716
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008717 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008718 bool LHSAsBool;
8719 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008720 // We were able to evaluate the LHS, see if we can get away with not
8721 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008722 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8723 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008724 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008725 }
8726 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008727 LHSResult.Failed = true;
8728
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008729 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008730 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008731 if (!Info.noteSideEffect())
8732 return false;
8733
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008734 // We can't evaluate the LHS; however, sometimes the result
8735 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8736 // Don't ignore RHS and suppress diagnostics from this arm.
8737 SuppressRHSDiags = true;
8738 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008739
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008740 return true;
8741 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008742
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008743 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8744 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008745
George Burgess IVa145e252016-05-25 22:38:36 +00008746 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008747 return false; // Ignore RHS;
8748
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008749 return true;
8750}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008751
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008752static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8753 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008754 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8755 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8756 // offsets.
8757 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8758 CharUnits &Offset = LVal.getLValueOffset();
8759 uint64_t Offset64 = Offset.getQuantity();
8760 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8761 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8762 : Offset64 + Index64);
8763}
8764
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008765bool DataRecursiveIntBinOpEvaluator::
8766 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8767 const BinaryOperator *E, APValue &Result) {
8768 if (E->getOpcode() == BO_Comma) {
8769 if (RHSResult.Failed)
8770 return false;
8771 Result = RHSResult.Val;
8772 return true;
8773 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008774
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008775 if (E->isLogicalOp()) {
8776 bool lhsResult, rhsResult;
8777 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8778 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +00008779
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008780 if (LHSIsOK) {
8781 if (RHSIsOK) {
8782 if (E->getOpcode() == BO_LOr)
8783 return Success(lhsResult || rhsResult, E, Result);
8784 else
8785 return Success(lhsResult && rhsResult, E, Result);
8786 }
8787 } else {
8788 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008789 // We can't evaluate the LHS; however, sometimes the result
8790 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8791 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008792 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008793 }
8794 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008795
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008796 return false;
8797 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008798
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008799 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8800 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +00008801
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008802 if (LHSResult.Failed || RHSResult.Failed)
8803 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008804
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008805 const APValue &LHSVal = LHSResult.Val;
8806 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +00008807
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008808 // Handle cases like (unsigned long)&a + 4.
8809 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8810 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008811 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008812 return true;
8813 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008814
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008815 // Handle cases like 4 + (unsigned long)&a
8816 if (E->getOpcode() == BO_Add &&
8817 RHSVal.isLValue() && LHSVal.isInt()) {
8818 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008819 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008820 return true;
8821 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008822
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008823 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8824 // Handle (intptr_t)&&A - (intptr_t)&&B.
8825 if (!LHSVal.getLValueOffset().isZero() ||
8826 !RHSVal.getLValueOffset().isZero())
8827 return false;
8828 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8829 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8830 if (!LHSExpr || !RHSExpr)
8831 return false;
8832 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8833 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8834 if (!LHSAddrExpr || !RHSAddrExpr)
8835 return false;
8836 // Make sure both labels come from the same function.
8837 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8838 RHSAddrExpr->getLabel()->getDeclContext())
8839 return false;
8840 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8841 return true;
8842 }
Richard Smith43e77732013-05-07 04:50:00 +00008843
8844 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008845 if (!LHSVal.isInt() || !RHSVal.isInt())
8846 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008847
8848 // Set up the width and signedness manually, in case it can't be deduced
8849 // from the operation we're performing.
8850 // FIXME: Don't do this in the cases where we can deduce it.
8851 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8852 E->getType()->isUnsignedIntegerOrEnumerationType());
8853 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8854 RHSVal.getInt(), Value))
8855 return false;
8856 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008857}
8858
Richard Trieuba4d0872012-03-21 23:30:30 +00008859void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008860 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +00008861
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008862 switch (job.Kind) {
8863 case Job::AnyExprKind: {
8864 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8865 if (shouldEnqueue(Bop)) {
8866 job.Kind = Job::BinOpKind;
8867 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008868 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008869 }
8870 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008871
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008872 EvaluateExpr(job.E, Result);
8873 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008874 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008875 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008876
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008877 case Job::BinOpKind: {
8878 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008879 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008880 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008881 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008882 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008883 }
8884 if (SuppressRHSDiags)
8885 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008886 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008887 job.Kind = Job::BinOpVisitedLHSKind;
8888 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008889 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008890 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008891
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008892 case Job::BinOpVisitedLHSKind: {
8893 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8894 EvalResult RHS;
8895 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008896 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008897 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008898 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008899 }
8900 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008901
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008902 llvm_unreachable("Invalid Job::Kind!");
8903}
8904
George Burgess IV8c892b52016-05-25 22:31:54 +00008905namespace {
8906/// Used when we determine that we should fail, but can keep evaluating prior to
8907/// noting that we had a failure.
8908class DelayedNoteFailureRAII {
8909 EvalInfo &Info;
8910 bool NoteFailure;
8911
8912public:
8913 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8914 : Info(Info), NoteFailure(NoteFailure) {}
8915 ~DelayedNoteFailureRAII() {
8916 if (NoteFailure) {
8917 bool ContinueAfterFailure = Info.noteFailure();
8918 (void)ContinueAfterFailure;
8919 assert(ContinueAfterFailure &&
8920 "Shouldn't have kept evaluating on failure.");
8921 }
8922 }
8923};
8924}
8925
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008926template <class SuccessCB, class AfterCB>
8927static bool
8928EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
8929 SuccessCB &&Success, AfterCB &&DoAfter) {
8930 assert(E->isComparisonOp() && "expected comparison operator");
8931 assert((E->getOpcode() == BO_Cmp ||
8932 E->getType()->isIntegralOrEnumerationType()) &&
8933 "unsupported binary expression evaluation");
8934 auto Error = [&](const Expr *E) {
8935 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8936 return false;
8937 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008938
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008939 using CCR = ComparisonCategoryResult;
8940 bool IsRelational = E->isRelationalOp();
8941 bool IsEquality = E->isEqualityOp();
8942 if (E->getOpcode() == BO_Cmp) {
8943 const ComparisonCategoryInfo &CmpInfo =
8944 Info.Ctx.CompCategories.getInfoForType(E->getType());
8945 IsRelational = CmpInfo.isOrdered();
8946 IsEquality = CmpInfo.isEquality();
8947 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00008948
Anders Carlssonacc79812008-11-16 07:17:21 +00008949 QualType LHSTy = E->getLHS()->getType();
8950 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008951
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008952 if (LHSTy->isIntegralOrEnumerationType() &&
8953 RHSTy->isIntegralOrEnumerationType()) {
8954 APSInt LHS, RHS;
8955 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
8956 if (!LHSOK && !Info.noteFailure())
8957 return false;
8958 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
8959 return false;
8960 if (LHS < RHS)
8961 return Success(CCR::Less, E);
8962 if (LHS > RHS)
8963 return Success(CCR::Greater, E);
8964 return Success(CCR::Equal, E);
8965 }
8966
Chandler Carruthb29a7432014-10-11 11:03:30 +00008967 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008968 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008969 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008970 if (E->isAssignmentOp()) {
8971 LValue LV;
8972 EvaluateLValue(E->getLHS(), LV, Info);
8973 LHSOK = false;
8974 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008975 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8976 if (LHSOK) {
8977 LHS.makeComplexFloat();
8978 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8979 }
8980 } else {
8981 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8982 }
George Burgess IVa145e252016-05-25 22:38:36 +00008983 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008984 return false;
8985
Chandler Carruthb29a7432014-10-11 11:03:30 +00008986 if (E->getRHS()->getType()->isRealFloatingType()) {
8987 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8988 return false;
8989 RHS.makeComplexFloat();
8990 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8991 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008992 return false;
8993
8994 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008995 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008996 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008997 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008998 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008999 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9000 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009001 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009002 assert(IsEquality && "invalid complex comparison");
9003 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
9004 LHS.getComplexIntImag() == RHS.getComplexIntImag();
9005 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009006 }
9007 }
Mike Stump11289f42009-09-09 15:08:12 +00009008
Anders Carlssonacc79812008-11-16 07:17:21 +00009009 if (LHSTy->isRealFloatingType() &&
9010 RHSTy->isRealFloatingType()) {
9011 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00009012
Richard Smith253c2a32012-01-27 01:14:48 +00009013 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009014 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00009015 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009016
Richard Smith253c2a32012-01-27 01:14:48 +00009017 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00009018 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009019
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009020 assert(E->isComparisonOp() && "Invalid binary operator!");
9021 auto GetCmpRes = [&]() {
9022 switch (LHS.compare(RHS)) {
9023 case APFloat::cmpEqual:
9024 return CCR::Equal;
9025 case APFloat::cmpLessThan:
9026 return CCR::Less;
9027 case APFloat::cmpGreaterThan:
9028 return CCR::Greater;
9029 case APFloat::cmpUnordered:
9030 return CCR::Unordered;
9031 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +00009032 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009033 };
9034 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +00009035 }
Mike Stump11289f42009-09-09 15:08:12 +00009036
Eli Friedmana38da572009-04-28 19:17:36 +00009037 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009038 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +00009039
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009040 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9041 if (!LHSOK && !Info.noteFailure())
9042 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009043
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009044 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9045 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009046
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009047 // Reject differing bases from the normal codepath; we special-case
9048 // comparisons to null.
9049 if (!HasSameBase(LHSValue, RHSValue)) {
9050 // Inequalities and subtractions between unrelated pointers have
9051 // unspecified or undefined behavior.
9052 if (!IsEquality)
9053 return Error(E);
9054 // A constant address may compare equal to the address of a symbol.
9055 // The one exception is that address of an object cannot compare equal
9056 // to a null pointer constant.
9057 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9058 (!RHSValue.Base && !RHSValue.Offset.isZero()))
9059 return Error(E);
9060 // It's implementation-defined whether distinct literals will have
9061 // distinct addresses. In clang, the result of such a comparison is
9062 // unspecified, so it is not a constant expression. However, we do know
9063 // that the address of a literal will be non-null.
9064 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9065 LHSValue.Base && RHSValue.Base)
9066 return Error(E);
9067 // We can't tell whether weak symbols will end up pointing to the same
9068 // object.
9069 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9070 return Error(E);
9071 // We can't compare the address of the start of one object with the
9072 // past-the-end address of another object, per C++ DR1652.
9073 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9074 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9075 (RHSValue.Base && RHSValue.Offset.isZero() &&
9076 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9077 return Error(E);
9078 // We can't tell whether an object is at the same address as another
9079 // zero sized object.
9080 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9081 (LHSValue.Base && isZeroSized(RHSValue)))
9082 return Error(E);
9083 return Success(CCR::Nonequal, E);
9084 }
Eli Friedman64004332009-03-23 04:38:34 +00009085
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009086 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9087 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +00009088
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009089 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9090 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +00009091
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009092 // C++11 [expr.rel]p3:
9093 // Pointers to void (after pointer conversions) can be compared, with a
9094 // result defined as follows: If both pointers represent the same
9095 // address or are both the null pointer value, the result is true if the
9096 // operator is <= or >= and false otherwise; otherwise the result is
9097 // unspecified.
9098 // We interpret this as applying to pointers to *cv* void.
9099 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9100 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +00009101
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009102 // C++11 [expr.rel]p2:
9103 // - If two pointers point to non-static data members of the same object,
9104 // or to subobjects or array elements fo such members, recursively, the
9105 // pointer to the later declared member compares greater provided the
9106 // two members have the same access control and provided their class is
9107 // not a union.
9108 // [...]
9109 // - Otherwise pointer comparisons are unspecified.
9110 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9111 bool WasArrayIndex;
9112 unsigned Mismatch = FindDesignatorMismatch(
9113 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9114 // At the point where the designators diverge, the comparison has a
9115 // specified value if:
9116 // - we are comparing array indices
9117 // - we are comparing fields of a union, or fields with the same access
9118 // Otherwise, the result is unspecified and thus the comparison is not a
9119 // constant expression.
9120 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9121 Mismatch < RHSDesignator.Entries.size()) {
9122 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9123 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9124 if (!LF && !RF)
9125 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9126 else if (!LF)
9127 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009128 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9129 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009130 else if (!RF)
9131 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009132 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9133 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009134 else if (!LF->getParent()->isUnion() &&
9135 LF->getAccess() != RF->getAccess())
9136 Info.CCEDiag(E,
9137 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009138 << LF << LF->getAccess() << RF << RF->getAccess()
9139 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +00009140 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009141 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009142
9143 // The comparison here must be unsigned, and performed with the same
9144 // width as the pointer.
9145 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9146 uint64_t CompareLHS = LHSOffset.getQuantity();
9147 uint64_t CompareRHS = RHSOffset.getQuantity();
9148 assert(PtrSize <= 64 && "Unexpected pointer width");
9149 uint64_t Mask = ~0ULL >> (64 - PtrSize);
9150 CompareLHS &= Mask;
9151 CompareRHS &= Mask;
9152
9153 // If there is a base and this is a relational operator, we can only
9154 // compare pointers within the object in question; otherwise, the result
9155 // depends on where the object is located in memory.
9156 if (!LHSValue.Base.isNull() && IsRelational) {
9157 QualType BaseTy = getType(LHSValue.Base);
9158 if (BaseTy->isIncompleteType())
9159 return Error(E);
9160 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9161 uint64_t OffsetLimit = Size.getQuantity();
9162 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9163 return Error(E);
9164 }
9165
9166 if (CompareLHS < CompareRHS)
9167 return Success(CCR::Less, E);
9168 if (CompareLHS > CompareRHS)
9169 return Success(CCR::Greater, E);
9170 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009171 }
Richard Smith7bb00672012-02-01 01:42:44 +00009172
9173 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009174 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +00009175 assert(RHSTy->isMemberPointerType() && "invalid comparison");
9176
9177 MemberPtr LHSValue, RHSValue;
9178
9179 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009180 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00009181 return false;
9182
9183 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9184 return false;
9185
9186 // C++11 [expr.eq]p2:
9187 // If both operands are null, they compare equal. Otherwise if only one is
9188 // null, they compare unequal.
9189 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9190 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009191 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009192 }
9193
9194 // Otherwise if either is a pointer to a virtual member function, the
9195 // result is unspecified.
9196 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9197 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009198 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009199 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9200 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009201 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009202
9203 // Otherwise they compare equal if and only if they would refer to the
9204 // same member of the same most derived object or the same subobject if
9205 // they were dereferenced with a hypothetical object of the associated
9206 // class type.
9207 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009208 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009209 }
9210
Richard Smithab44d9b2012-02-14 22:35:28 +00009211 if (LHSTy->isNullPtrType()) {
9212 assert(E->isComparisonOp() && "unexpected nullptr operation");
9213 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9214 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9215 // are compared, the result is true of the operator is <=, >= or ==, and
9216 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009217 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +00009218 }
9219
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009220 return DoAfter();
9221}
9222
9223bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
9224 if (!CheckLiteralType(Info, E))
9225 return false;
9226
9227 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9228 const BinaryOperator *E) {
9229 // Evaluation succeeded. Lookup the information for the comparison category
9230 // type and fetch the VarDecl for the result.
9231 const ComparisonCategoryInfo &CmpInfo =
9232 Info.Ctx.CompCategories.getInfoForType(E->getType());
9233 const VarDecl *VD =
9234 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
9235 // Check and evaluate the result as a constant expression.
9236 LValue LV;
9237 LV.set(VD);
9238 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9239 return false;
9240 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9241 };
9242 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9243 return ExprEvaluatorBaseTy::VisitBinCmp(E);
9244 });
9245}
9246
9247bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9248 // We don't call noteFailure immediately because the assignment happens after
9249 // we evaluate LHS and RHS.
9250 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
9251 return Error(E);
9252
9253 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
9254 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
9255 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
9256
9257 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
9258 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009259 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009260
9261 if (E->isComparisonOp()) {
9262 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
9263 // comparisons and then translating the result.
9264 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9265 const BinaryOperator *E) {
9266 using CCR = ComparisonCategoryResult;
9267 bool IsEqual = ResKind == CCR::Equal,
9268 IsLess = ResKind == CCR::Less,
9269 IsGreater = ResKind == CCR::Greater;
9270 auto Op = E->getOpcode();
9271 switch (Op) {
9272 default:
9273 llvm_unreachable("unsupported binary operator");
9274 case BO_EQ:
9275 case BO_NE:
9276 return Success(IsEqual == (Op == BO_EQ), E);
9277 case BO_LT: return Success(IsLess, E);
9278 case BO_GT: return Success(IsGreater, E);
9279 case BO_LE: return Success(IsEqual || IsLess, E);
9280 case BO_GE: return Success(IsEqual || IsGreater, E);
9281 }
9282 };
9283 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9284 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9285 });
9286 }
9287
9288 QualType LHSTy = E->getLHS()->getType();
9289 QualType RHSTy = E->getRHS()->getType();
9290
9291 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
9292 E->getOpcode() == BO_Sub) {
9293 LValue LHSValue, RHSValue;
9294
9295 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9296 if (!LHSOK && !Info.noteFailure())
9297 return false;
9298
9299 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9300 return false;
9301
9302 // Reject differing bases from the normal codepath; we special-case
9303 // comparisons to null.
9304 if (!HasSameBase(LHSValue, RHSValue)) {
9305 // Handle &&A - &&B.
9306 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
9307 return Error(E);
9308 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
9309 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
9310 if (!LHSExpr || !RHSExpr)
9311 return Error(E);
9312 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9313 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9314 if (!LHSAddrExpr || !RHSAddrExpr)
9315 return Error(E);
9316 // Make sure both labels come from the same function.
9317 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9318 RHSAddrExpr->getLabel()->getDeclContext())
9319 return Error(E);
9320 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
9321 }
9322 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9323 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9324
9325 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9326 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9327
9328 // C++11 [expr.add]p6:
9329 // Unless both pointers point to elements of the same array object, or
9330 // one past the last element of the array object, the behavior is
9331 // undefined.
9332 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
9333 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
9334 RHSDesignator))
9335 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
9336
9337 QualType Type = E->getLHS()->getType();
9338 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
9339
9340 CharUnits ElementSize;
9341 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
9342 return false;
9343
9344 // As an extension, a type may have zero size (empty struct or union in
9345 // C, array of zero length). Pointer subtraction in such cases has
9346 // undefined behavior, so is not constant.
9347 if (ElementSize.isZero()) {
9348 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
9349 << ElementType;
9350 return false;
9351 }
9352
9353 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
9354 // and produce incorrect results when it overflows. Such behavior
9355 // appears to be non-conforming, but is common, so perhaps we should
9356 // assume the standard intended for such cases to be undefined behavior
9357 // and check for them.
9358
9359 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
9360 // overflow in the final conversion to ptrdiff_t.
9361 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
9362 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
9363 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
9364 false);
9365 APSInt TrueResult = (LHS - RHS) / ElemSize;
9366 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
9367
9368 if (Result.extend(65) != TrueResult &&
9369 !HandleOverflow(Info, E, TrueResult, E->getType()))
9370 return false;
9371 return Success(Result, E);
9372 }
9373
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009374 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00009375}
9376
Peter Collingbournee190dee2011-03-11 19:24:49 +00009377/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
9378/// a result as the expression's type.
9379bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
9380 const UnaryExprOrTypeTraitExpr *E) {
9381 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +00009382 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +00009383 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00009384 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +00009385 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
9386 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009387 else
Richard Smith6822bd72018-10-26 19:26:45 +00009388 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
9389 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009390 }
Eli Friedman64004332009-03-23 04:38:34 +00009391
Peter Collingbournee190dee2011-03-11 19:24:49 +00009392 case UETT_VecStep: {
9393 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00009394
Peter Collingbournee190dee2011-03-11 19:24:49 +00009395 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00009396 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00009397
Peter Collingbournee190dee2011-03-11 19:24:49 +00009398 // The vec_step built-in functions that take a 3-component
9399 // vector return 4. (OpenCL 1.1 spec 6.11.12)
9400 if (n == 3)
9401 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00009402
Peter Collingbournee190dee2011-03-11 19:24:49 +00009403 return Success(n, E);
9404 } else
9405 return Success(1, E);
9406 }
9407
9408 case UETT_SizeOf: {
9409 QualType SrcTy = E->getTypeOfArgument();
9410 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9411 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00009412 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9413 SrcTy = Ref->getPointeeType();
9414
Richard Smithd62306a2011-11-10 06:34:14 +00009415 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00009416 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00009417 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00009418 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009419 }
Alexey Bataev00396512015-07-02 03:40:19 +00009420 case UETT_OpenMPRequiredSimdAlign:
9421 assert(E->isArgumentType());
9422 return Success(
9423 Info.Ctx.toCharUnitsFromBits(
9424 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9425 .getQuantity(),
9426 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009427 }
9428
9429 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00009430}
9431
Peter Collingbournee9200682011-05-13 03:29:01 +00009432bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009433 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00009434 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00009435 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009436 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00009437 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00009438 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00009439 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00009440 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00009441 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00009442 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00009443 APSInt IdxResult;
9444 if (!EvaluateInteger(Idx, IdxResult, Info))
9445 return false;
9446 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9447 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009448 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009449 CurrentType = AT->getElementType();
9450 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9451 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00009452 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00009453 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009454
James Y Knight7281c352015-12-29 22:31:18 +00009455 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00009456 FieldDecl *MemberDecl = ON.getField();
9457 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009458 if (!RT)
9459 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009460 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009461 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00009462 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00009463 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00009464 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00009465 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00009466 CurrentType = MemberDecl->getType().getNonReferenceType();
9467 break;
9468 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009469
James Y Knight7281c352015-12-29 22:31:18 +00009470 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00009471 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00009472
James Y Knight7281c352015-12-29 22:31:18 +00009473 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00009474 CXXBaseSpecifier *BaseSpec = ON.getBase();
9475 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00009476 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009477
9478 // Find the layout of the class whose base we are looking into.
9479 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009480 if (!RT)
9481 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009482 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009483 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00009484 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9485
9486 // Find the base class itself.
9487 CurrentType = BaseSpec->getType();
9488 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9489 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009490 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +00009491
Douglas Gregord1702062010-04-29 00:18:15 +00009492 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00009493 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00009494 break;
9495 }
Douglas Gregor882211c2010-04-28 22:16:22 +00009496 }
9497 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009498 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009499}
9500
Chris Lattnere13042c2008-07-11 19:10:17 +00009501bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009502 switch (E->getOpcode()) {
9503 default:
9504 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9505 // See C99 6.6p3.
9506 return Error(E);
9507 case UO_Extension:
9508 // FIXME: Should extension allow i-c-e extension expressions in its scope?
9509 // If so, we could clear the diagnostic ID.
9510 return Visit(E->getSubExpr());
9511 case UO_Plus:
9512 // The result is just the value.
9513 return Visit(E->getSubExpr());
9514 case UO_Minus: {
9515 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00009516 return false;
9517 if (!Result.isInt()) return Error(E);
9518 const APSInt &Value = Result.getInt();
9519 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9520 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9521 E->getType()))
9522 return false;
Richard Smithfe800032012-01-31 04:08:20 +00009523 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009524 }
9525 case UO_Not: {
9526 if (!Visit(E->getSubExpr()))
9527 return false;
9528 if (!Result.isInt()) return Error(E);
9529 return Success(~Result.getInt(), E);
9530 }
9531 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00009532 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00009533 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00009534 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009535 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00009536 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009537 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009538}
Mike Stump11289f42009-09-09 15:08:12 +00009539
Chris Lattner477c4be2008-07-12 01:15:53 +00009540/// HandleCast - This is used to evaluate implicit or explicit casts where the
9541/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00009542bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9543 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009544 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00009545 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009546
Eli Friedmanc757de22011-03-25 00:43:55 +00009547 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00009548 case CK_BaseToDerived:
9549 case CK_DerivedToBase:
9550 case CK_UncheckedDerivedToBase:
9551 case CK_Dynamic:
9552 case CK_ToUnion:
9553 case CK_ArrayToPointerDecay:
9554 case CK_FunctionToPointerDecay:
9555 case CK_NullToPointer:
9556 case CK_NullToMemberPointer:
9557 case CK_BaseToDerivedMemberPointer:
9558 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00009559 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00009560 case CK_ConstructorConversion:
9561 case CK_IntegralToPointer:
9562 case CK_ToVoid:
9563 case CK_VectorSplat:
9564 case CK_IntegralToFloating:
9565 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009566 case CK_CPointerToObjCPointerCast:
9567 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009568 case CK_AnyPointerToBlockPointerCast:
9569 case CK_ObjCObjectLValueCast:
9570 case CK_FloatingRealToComplex:
9571 case CK_FloatingComplexToReal:
9572 case CK_FloatingComplexCast:
9573 case CK_FloatingComplexToIntegralComplex:
9574 case CK_IntegralRealToComplex:
9575 case CK_IntegralComplexCast:
9576 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00009577 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +00009578 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +00009579 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009580 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009581 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00009582 case CK_FixedPointCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009583 llvm_unreachable("invalid cast kind for integral value");
9584
Eli Friedman9faf2f92011-03-25 19:07:11 +00009585 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009586 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009587 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00009588 case CK_ARCProduceObject:
9589 case CK_ARCConsumeObject:
9590 case CK_ARCReclaimReturnedObject:
9591 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009592 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009593 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009594
Richard Smith4ef685b2012-01-17 21:17:26 +00009595 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00009596 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009597 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009598 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009599 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009600
9601 case CK_MemberPointerToBoolean:
9602 case CK_PointerToBoolean:
9603 case CK_IntegralToBoolean:
9604 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009605 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009606 case CK_FloatingComplexToBoolean:
9607 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009608 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009609 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009610 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009611 uint64_t IntResult = BoolResult;
9612 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9613 IntResult = (uint64_t)-1;
9614 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009615 }
9616
Leonard Chanb4ba4672018-10-23 17:55:35 +00009617 case CK_FixedPointToBoolean: {
9618 // Unsigned padding does not affect this.
9619 APValue Val;
9620 if (!Evaluate(Val, Info, SubExpr))
9621 return false;
9622 return Success(Val.getInt().getBoolValue(), E);
9623 }
9624
Eli Friedmanc757de22011-03-25 00:43:55 +00009625 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009626 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009627 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009628
Eli Friedman742421e2009-02-20 01:15:07 +00009629 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009630 // Allow casts of address-of-label differences if they are no-ops
9631 // or narrowing. (The narrowing case isn't actually guaranteed to
9632 // be constant-evaluatable except in some narrow cases which are hard
9633 // to detect here. We let it through on the assumption the user knows
9634 // what they are doing.)
9635 if (Result.isAddrLabelDiff())
9636 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009637 // Only allow casts of lvalues if they are lossless.
9638 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9639 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009640
Richard Smith911e1422012-01-30 22:27:01 +00009641 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9642 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009643 }
Mike Stump11289f42009-09-09 15:08:12 +00009644
Eli Friedmanc757de22011-03-25 00:43:55 +00009645 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009646 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9647
John McCall45d55e42010-05-07 21:00:08 +00009648 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009649 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009650 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009651
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009652 if (LV.getLValueBase()) {
9653 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009654 // FIXME: Allow a larger integer size than the pointer size, and allow
9655 // narrowing back down to pointer width in subsequent integral casts.
9656 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009657 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009658 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009659
Richard Smithcf74da72011-11-16 07:18:12 +00009660 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009661 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009662 return true;
9663 }
9664
Yaxun Liu402804b2016-12-15 08:09:08 +00009665 uint64_t V;
9666 if (LV.isNullPointer())
9667 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9668 else
9669 V = LV.getLValueOffset().getQuantity();
9670
9671 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009672 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009673 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009674
Eli Friedmanc757de22011-03-25 00:43:55 +00009675 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009676 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009677 if (!EvaluateComplex(SubExpr, C, Info))
9678 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009679 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009680 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009681
Eli Friedmanc757de22011-03-25 00:43:55 +00009682 case CK_FloatingToIntegral: {
9683 APFloat F(0.0);
9684 if (!EvaluateFloat(SubExpr, F, Info))
9685 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009686
Richard Smith357362d2011-12-13 06:39:58 +00009687 APSInt Value;
9688 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9689 return false;
9690 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009691 }
9692 }
Mike Stump11289f42009-09-09 15:08:12 +00009693
Eli Friedmanc757de22011-03-25 00:43:55 +00009694 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009695}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009696
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009697bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9698 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009699 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009700 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9701 return false;
9702 if (!LV.isComplexInt())
9703 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009704 return Success(LV.getComplexIntReal(), E);
9705 }
9706
9707 return Visit(E->getSubExpr());
9708}
9709
Eli Friedman4e7a2412009-02-27 04:45:43 +00009710bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009711 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009712 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009713 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9714 return false;
9715 if (!LV.isComplexInt())
9716 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009717 return Success(LV.getComplexIntImag(), E);
9718 }
9719
Richard Smith4a678122011-10-24 18:44:57 +00009720 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009721 return Success(0, E);
9722}
9723
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009724bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9725 return Success(E->getPackLength(), E);
9726}
9727
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009728bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9729 return Success(E->getValue(), E);
9730}
9731
Leonard Chandb01c3a2018-06-20 17:19:40 +00009732bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9733 switch (E->getOpcode()) {
9734 default:
9735 // Invalid unary operators
9736 return Error(E);
9737 case UO_Plus:
9738 // The result is just the value.
9739 return Visit(E->getSubExpr());
9740 case UO_Minus: {
9741 if (!Visit(E->getSubExpr())) return false;
9742 if (!Result.isInt()) return Error(E);
9743 const APSInt &Value = Result.getInt();
9744 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
9745 SmallString<64> S;
9746 FixedPointValueToString(S, Value,
Leonard Chanc03642e2018-08-06 16:05:08 +00009747 Info.Ctx.getTypeInfo(E->getType()).Width);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009748 Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
9749 if (Info.noteUndefinedBehavior()) return false;
9750 }
9751 return Success(-Value, E);
9752 }
9753 case UO_LNot: {
9754 bool bres;
9755 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9756 return false;
9757 return Success(!bres, E);
9758 }
9759 }
9760}
9761
Chris Lattner05706e882008-07-11 18:11:29 +00009762//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009763// Float Evaluation
9764//===----------------------------------------------------------------------===//
9765
9766namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009767class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009768 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009769 APFloat &Result;
9770public:
9771 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009772 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009773
Richard Smith2e312c82012-03-03 22:46:17 +00009774 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009775 Result = V.getFloat();
9776 return true;
9777 }
Eli Friedman24c01542008-08-22 00:06:13 +00009778
Richard Smithfddd3842011-12-30 21:15:51 +00009779 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009780 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9781 return true;
9782 }
9783
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009784 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009785
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009786 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009787 bool VisitBinaryOperator(const BinaryOperator *E);
9788 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009789 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009790
John McCallb1fb0d32010-05-07 22:08:54 +00009791 bool VisitUnaryReal(const UnaryOperator *E);
9792 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009793
Richard Smithfddd3842011-12-30 21:15:51 +00009794 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009795};
9796} // end anonymous namespace
9797
9798static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009799 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009800 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009801}
9802
Jay Foad39c79802011-01-12 09:06:06 +00009803static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009804 QualType ResultTy,
9805 const Expr *Arg,
9806 bool SNaN,
9807 llvm::APFloat &Result) {
9808 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9809 if (!S) return false;
9810
9811 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9812
9813 llvm::APInt fill;
9814
9815 // Treat empty strings as if they were zero.
9816 if (S->getString().empty())
9817 fill = llvm::APInt(32, 0);
9818 else if (S->getString().getAsInteger(0, fill))
9819 return false;
9820
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009821 if (Context.getTargetInfo().isNan2008()) {
9822 if (SNaN)
9823 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9824 else
9825 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9826 } else {
9827 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9828 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9829 // a different encoding to what became a standard in 2008, and for pre-
9830 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9831 // sNaN. This is now known as "legacy NaN" encoding.
9832 if (SNaN)
9833 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9834 else
9835 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9836 }
9837
John McCall16291492010-02-28 13:00:19 +00009838 return true;
9839}
9840
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009841bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009842 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009843 default:
9844 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9845
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009846 case Builtin::BI__builtin_huge_val:
9847 case Builtin::BI__builtin_huge_valf:
9848 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009849 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009850 case Builtin::BI__builtin_inf:
9851 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009852 case Builtin::BI__builtin_infl:
9853 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009854 const llvm::fltSemantics &Sem =
9855 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009856 Result = llvm::APFloat::getInf(Sem);
9857 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009858 }
Mike Stump11289f42009-09-09 15:08:12 +00009859
John McCall16291492010-02-28 13:00:19 +00009860 case Builtin::BI__builtin_nans:
9861 case Builtin::BI__builtin_nansf:
9862 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009863 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009864 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9865 true, Result))
9866 return Error(E);
9867 return true;
John McCall16291492010-02-28 13:00:19 +00009868
Chris Lattner0b7282e2008-10-06 06:31:58 +00009869 case Builtin::BI__builtin_nan:
9870 case Builtin::BI__builtin_nanf:
9871 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009872 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +00009873 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009874 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009875 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9876 false, Result))
9877 return Error(E);
9878 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009879
9880 case Builtin::BI__builtin_fabs:
9881 case Builtin::BI__builtin_fabsf:
9882 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009883 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009884 if (!EvaluateFloat(E->getArg(0), Result, Info))
9885 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009886
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009887 if (Result.isNegative())
9888 Result.changeSign();
9889 return true;
9890
Richard Smith8889a3d2013-06-13 06:26:32 +00009891 // FIXME: Builtin::BI__builtin_powi
9892 // FIXME: Builtin::BI__builtin_powif
9893 // FIXME: Builtin::BI__builtin_powil
9894
Mike Stump11289f42009-09-09 15:08:12 +00009895 case Builtin::BI__builtin_copysign:
9896 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009897 case Builtin::BI__builtin_copysignl:
9898 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009899 APFloat RHS(0.);
9900 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9901 !EvaluateFloat(E->getArg(1), RHS, Info))
9902 return false;
9903 Result.copySign(RHS);
9904 return true;
9905 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009906 }
9907}
9908
John McCallb1fb0d32010-05-07 22:08:54 +00009909bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009910 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9911 ComplexValue CV;
9912 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9913 return false;
9914 Result = CV.FloatReal;
9915 return true;
9916 }
9917
9918 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009919}
9920
9921bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009922 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9923 ComplexValue CV;
9924 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9925 return false;
9926 Result = CV.FloatImag;
9927 return true;
9928 }
9929
Richard Smith4a678122011-10-24 18:44:57 +00009930 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009931 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9932 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009933 return true;
9934}
9935
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009936bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009937 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009938 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009939 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009940 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009941 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009942 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9943 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009944 Result.changeSign();
9945 return true;
9946 }
9947}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009948
Eli Friedman24c01542008-08-22 00:06:13 +00009949bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009950 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9951 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009952
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009953 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009954 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009955 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009956 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009957 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9958 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009959}
9960
9961bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9962 Result = E->getValue();
9963 return true;
9964}
9965
Peter Collingbournee9200682011-05-13 03:29:01 +00009966bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9967 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009968
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009969 switch (E->getCastKind()) {
9970 default:
Richard Smith11562c52011-10-28 17:51:58 +00009971 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009972
9973 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009974 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009975 return EvaluateInteger(SubExpr, IntResult, Info) &&
9976 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9977 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009978 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009979
9980 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009981 if (!Visit(SubExpr))
9982 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009983 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9984 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009985 }
John McCalld7646252010-11-14 08:17:51 +00009986
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009987 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009988 ComplexValue V;
9989 if (!EvaluateComplex(SubExpr, V, Info))
9990 return false;
9991 Result = V.getComplexFloatReal();
9992 return true;
9993 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009994 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009995}
9996
Eli Friedman24c01542008-08-22 00:06:13 +00009997//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009998// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009999//===----------------------------------------------------------------------===//
10000
10001namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000010002class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010003 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000010004 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000010005
Anders Carlsson537969c2008-11-16 20:27:53 +000010006public:
John McCall93d91dc2010-05-07 17:22:02 +000010007 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000010008 : ExprEvaluatorBaseTy(info), Result(Result) {}
10009
Richard Smith2e312c82012-03-03 22:46:17 +000010010 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010011 Result.setFrom(V);
10012 return true;
10013 }
Mike Stump11289f42009-09-09 15:08:12 +000010014
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010015 bool ZeroInitialization(const Expr *E);
10016
Anders Carlsson537969c2008-11-16 20:27:53 +000010017 //===--------------------------------------------------------------------===//
10018 // Visitor Methods
10019 //===--------------------------------------------------------------------===//
10020
Peter Collingbournee9200682011-05-13 03:29:01 +000010021 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000010022 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000010023 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010024 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010025 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010026};
10027} // end anonymous namespace
10028
John McCall93d91dc2010-05-07 17:22:02 +000010029static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
10030 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000010031 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010032 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010033}
10034
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010035bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000010036 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010037 if (ElemTy->isRealFloatingType()) {
10038 Result.makeComplexFloat();
10039 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10040 Result.FloatReal = Zero;
10041 Result.FloatImag = Zero;
10042 } else {
10043 Result.makeComplexInt();
10044 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10045 Result.IntReal = Zero;
10046 Result.IntImag = Zero;
10047 }
10048 return true;
10049}
10050
Peter Collingbournee9200682011-05-13 03:29:01 +000010051bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10052 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010053
10054 if (SubExpr->getType()->isRealFloatingType()) {
10055 Result.makeComplexFloat();
10056 APFloat &Imag = Result.FloatImag;
10057 if (!EvaluateFloat(SubExpr, Imag, Info))
10058 return false;
10059
10060 Result.FloatReal = APFloat(Imag.getSemantics());
10061 return true;
10062 } else {
10063 assert(SubExpr->getType()->isIntegerType() &&
10064 "Unexpected imaginary literal.");
10065
10066 Result.makeComplexInt();
10067 APSInt &Imag = Result.IntImag;
10068 if (!EvaluateInteger(SubExpr, Imag, Info))
10069 return false;
10070
10071 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10072 return true;
10073 }
10074}
10075
Peter Collingbournee9200682011-05-13 03:29:01 +000010076bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010077
John McCallfcef3cf2010-12-14 17:51:41 +000010078 switch (E->getCastKind()) {
10079 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010080 case CK_BaseToDerived:
10081 case CK_DerivedToBase:
10082 case CK_UncheckedDerivedToBase:
10083 case CK_Dynamic:
10084 case CK_ToUnion:
10085 case CK_ArrayToPointerDecay:
10086 case CK_FunctionToPointerDecay:
10087 case CK_NullToPointer:
10088 case CK_NullToMemberPointer:
10089 case CK_BaseToDerivedMemberPointer:
10090 case CK_DerivedToBaseMemberPointer:
10091 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000010092 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000010093 case CK_ConstructorConversion:
10094 case CK_IntegralToPointer:
10095 case CK_PointerToIntegral:
10096 case CK_PointerToBoolean:
10097 case CK_ToVoid:
10098 case CK_VectorSplat:
10099 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000010100 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000010101 case CK_IntegralToBoolean:
10102 case CK_IntegralToFloating:
10103 case CK_FloatingToIntegral:
10104 case CK_FloatingToBoolean:
10105 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000010106 case CK_CPointerToObjCPointerCast:
10107 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010108 case CK_AnyPointerToBlockPointerCast:
10109 case CK_ObjCObjectLValueCast:
10110 case CK_FloatingComplexToReal:
10111 case CK_FloatingComplexToBoolean:
10112 case CK_IntegralComplexToReal:
10113 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000010114 case CK_ARCProduceObject:
10115 case CK_ARCConsumeObject:
10116 case CK_ARCReclaimReturnedObject:
10117 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000010118 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000010119 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000010120 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000010121 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000010122 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000010123 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000010124 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000010125 case CK_FixedPointToBoolean:
John McCallfcef3cf2010-12-14 17:51:41 +000010126 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000010127
John McCallfcef3cf2010-12-14 17:51:41 +000010128 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010129 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000010130 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +000010131 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010132
10133 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000010134 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010135 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010136 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010137
10138 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010139 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000010140 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010141 return false;
10142
John McCallfcef3cf2010-12-14 17:51:41 +000010143 Result.makeComplexFloat();
10144 Result.FloatImag = APFloat(Real.getSemantics());
10145 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010146 }
10147
John McCallfcef3cf2010-12-14 17:51:41 +000010148 case CK_FloatingComplexCast: {
10149 if (!Visit(E->getSubExpr()))
10150 return false;
10151
10152 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10153 QualType From
10154 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10155
Richard Smith357362d2011-12-13 06:39:58 +000010156 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
10157 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010158 }
10159
10160 case CK_FloatingComplexToIntegralComplex: {
10161 if (!Visit(E->getSubExpr()))
10162 return false;
10163
10164 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10165 QualType From
10166 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10167 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000010168 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
10169 To, Result.IntReal) &&
10170 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
10171 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010172 }
10173
10174 case CK_IntegralRealToComplex: {
10175 APSInt &Real = Result.IntReal;
10176 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
10177 return false;
10178
10179 Result.makeComplexInt();
10180 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
10181 return true;
10182 }
10183
10184 case CK_IntegralComplexCast: {
10185 if (!Visit(E->getSubExpr()))
10186 return false;
10187
10188 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10189 QualType From
10190 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10191
Richard Smith911e1422012-01-30 22:27:01 +000010192 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
10193 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010194 return true;
10195 }
10196
10197 case CK_IntegralComplexToFloatingComplex: {
10198 if (!Visit(E->getSubExpr()))
10199 return false;
10200
Ted Kremenek28831752012-08-23 20:46:57 +000010201 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010202 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000010203 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010204 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000010205 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
10206 To, Result.FloatReal) &&
10207 HandleIntToFloatCast(Info, E, From, Result.IntImag,
10208 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010209 }
10210 }
10211
10212 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010213}
10214
John McCall93d91dc2010-05-07 17:22:02 +000010215bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000010216 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000010217 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10218
Chandler Carrutha216cad2014-10-11 00:57:18 +000010219 // Track whether the LHS or RHS is real at the type system level. When this is
10220 // the case we can simplify our evaluation strategy.
10221 bool LHSReal = false, RHSReal = false;
10222
10223 bool LHSOK;
10224 if (E->getLHS()->getType()->isRealFloatingType()) {
10225 LHSReal = true;
10226 APFloat &Real = Result.FloatReal;
10227 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
10228 if (LHSOK) {
10229 Result.makeComplexFloat();
10230 Result.FloatImag = APFloat(Real.getSemantics());
10231 }
10232 } else {
10233 LHSOK = Visit(E->getLHS());
10234 }
George Burgess IVa145e252016-05-25 22:38:36 +000010235 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000010236 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010237
John McCall93d91dc2010-05-07 17:22:02 +000010238 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010239 if (E->getRHS()->getType()->isRealFloatingType()) {
10240 RHSReal = true;
10241 APFloat &Real = RHS.FloatReal;
10242 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
10243 return false;
10244 RHS.makeComplexFloat();
10245 RHS.FloatImag = APFloat(Real.getSemantics());
10246 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000010247 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010248
Chandler Carrutha216cad2014-10-11 00:57:18 +000010249 assert(!(LHSReal && RHSReal) &&
10250 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010251 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010252 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000010253 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010254 if (Result.isComplexFloat()) {
10255 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
10256 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010257 if (LHSReal)
10258 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10259 else if (!RHSReal)
10260 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
10261 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010262 } else {
10263 Result.getComplexIntReal() += RHS.getComplexIntReal();
10264 Result.getComplexIntImag() += RHS.getComplexIntImag();
10265 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010266 break;
John McCalle3027922010-08-25 11:45:40 +000010267 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010268 if (Result.isComplexFloat()) {
10269 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
10270 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010271 if (LHSReal) {
10272 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10273 Result.getComplexFloatImag().changeSign();
10274 } else if (!RHSReal) {
10275 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
10276 APFloat::rmNearestTiesToEven);
10277 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010278 } else {
10279 Result.getComplexIntReal() -= RHS.getComplexIntReal();
10280 Result.getComplexIntImag() -= RHS.getComplexIntImag();
10281 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010282 break;
John McCalle3027922010-08-25 11:45:40 +000010283 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010284 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010285 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +000010286 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010287 // following naming scheme:
10288 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000010289 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010290 APFloat &A = LHS.getComplexFloatReal();
10291 APFloat &B = LHS.getComplexFloatImag();
10292 APFloat &C = RHS.getComplexFloatReal();
10293 APFloat &D = RHS.getComplexFloatImag();
10294 APFloat &ResR = Result.getComplexFloatReal();
10295 APFloat &ResI = Result.getComplexFloatImag();
10296 if (LHSReal) {
10297 assert(!RHSReal && "Cannot have two real operands for a complex op!");
10298 ResR = A * C;
10299 ResI = A * D;
10300 } else if (RHSReal) {
10301 ResR = C * A;
10302 ResI = C * B;
10303 } else {
10304 // In the fully general case, we need to handle NaNs and infinities
10305 // robustly.
10306 APFloat AC = A * C;
10307 APFloat BD = B * D;
10308 APFloat AD = A * D;
10309 APFloat BC = B * C;
10310 ResR = AC - BD;
10311 ResI = AD + BC;
10312 if (ResR.isNaN() && ResI.isNaN()) {
10313 bool Recalc = false;
10314 if (A.isInfinity() || B.isInfinity()) {
10315 A = APFloat::copySign(
10316 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10317 B = APFloat::copySign(
10318 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10319 if (C.isNaN())
10320 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10321 if (D.isNaN())
10322 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10323 Recalc = true;
10324 }
10325 if (C.isInfinity() || D.isInfinity()) {
10326 C = APFloat::copySign(
10327 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10328 D = APFloat::copySign(
10329 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10330 if (A.isNaN())
10331 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10332 if (B.isNaN())
10333 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10334 Recalc = true;
10335 }
10336 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
10337 AD.isInfinity() || BC.isInfinity())) {
10338 if (A.isNaN())
10339 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10340 if (B.isNaN())
10341 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10342 if (C.isNaN())
10343 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10344 if (D.isNaN())
10345 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10346 Recalc = true;
10347 }
10348 if (Recalc) {
10349 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
10350 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
10351 }
10352 }
10353 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010354 } else {
John McCall93d91dc2010-05-07 17:22:02 +000010355 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000010356 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010357 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
10358 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000010359 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010360 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
10361 LHS.getComplexIntImag() * RHS.getComplexIntReal());
10362 }
10363 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010364 case BO_Div:
10365 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010366 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +000010367 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010368 // following naming scheme:
10369 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010370 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010371 APFloat &A = LHS.getComplexFloatReal();
10372 APFloat &B = LHS.getComplexFloatImag();
10373 APFloat &C = RHS.getComplexFloatReal();
10374 APFloat &D = RHS.getComplexFloatImag();
10375 APFloat &ResR = Result.getComplexFloatReal();
10376 APFloat &ResI = Result.getComplexFloatImag();
10377 if (RHSReal) {
10378 ResR = A / C;
10379 ResI = B / C;
10380 } else {
10381 if (LHSReal) {
10382 // No real optimizations we can do here, stub out with zero.
10383 B = APFloat::getZero(A.getSemantics());
10384 }
10385 int DenomLogB = 0;
10386 APFloat MaxCD = maxnum(abs(C), abs(D));
10387 if (MaxCD.isFinite()) {
10388 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000010389 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
10390 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010391 }
10392 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000010393 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
10394 APFloat::rmNearestTiesToEven);
10395 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
10396 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010397 if (ResR.isNaN() && ResI.isNaN()) {
10398 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
10399 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
10400 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
10401 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
10402 D.isFinite()) {
10403 A = APFloat::copySign(
10404 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10405 B = APFloat::copySign(
10406 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10407 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
10408 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
10409 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
10410 C = APFloat::copySign(
10411 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10412 D = APFloat::copySign(
10413 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10414 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
10415 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
10416 }
10417 }
10418 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010419 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010420 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
10421 return Error(E, diag::note_expr_divide_by_zero);
10422
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010423 ComplexValue LHS = Result;
10424 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
10425 RHS.getComplexIntImag() * RHS.getComplexIntImag();
10426 Result.getComplexIntReal() =
10427 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10428 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10429 Result.getComplexIntImag() =
10430 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10431 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10432 }
10433 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010434 }
10435
John McCall93d91dc2010-05-07 17:22:02 +000010436 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010437}
10438
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010439bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10440 // Get the operand value into 'Result'.
10441 if (!Visit(E->getSubExpr()))
10442 return false;
10443
10444 switch (E->getOpcode()) {
10445 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010446 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010447 case UO_Extension:
10448 return true;
10449 case UO_Plus:
10450 // The result is always just the subexpr.
10451 return true;
10452 case UO_Minus:
10453 if (Result.isComplexFloat()) {
10454 Result.getComplexFloatReal().changeSign();
10455 Result.getComplexFloatImag().changeSign();
10456 }
10457 else {
10458 Result.getComplexIntReal() = -Result.getComplexIntReal();
10459 Result.getComplexIntImag() = -Result.getComplexIntImag();
10460 }
10461 return true;
10462 case UO_Not:
10463 if (Result.isComplexFloat())
10464 Result.getComplexFloatImag().changeSign();
10465 else
10466 Result.getComplexIntImag() = -Result.getComplexIntImag();
10467 return true;
10468 }
10469}
10470
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010471bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10472 if (E->getNumInits() == 2) {
10473 if (E->getType()->isComplexType()) {
10474 Result.makeComplexFloat();
10475 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10476 return false;
10477 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10478 return false;
10479 } else {
10480 Result.makeComplexInt();
10481 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10482 return false;
10483 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10484 return false;
10485 }
10486 return true;
10487 }
10488 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10489}
10490
Anders Carlsson537969c2008-11-16 20:27:53 +000010491//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000010492// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10493// implicit conversion.
10494//===----------------------------------------------------------------------===//
10495
10496namespace {
10497class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000010498 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010499 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000010500 APValue &Result;
10501public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010502 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10503 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000010504
10505 bool Success(const APValue &V, const Expr *E) {
10506 Result = V;
10507 return true;
10508 }
10509
10510 bool ZeroInitialization(const Expr *E) {
10511 ImplicitValueInitExpr VIE(
10512 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010513 // For atomic-qualified class (and array) types in C++, initialize the
10514 // _Atomic-wrapped subobject directly, in-place.
10515 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10516 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000010517 }
10518
10519 bool VisitCastExpr(const CastExpr *E) {
10520 switch (E->getCastKind()) {
10521 default:
10522 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10523 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010524 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10525 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000010526 }
10527 }
10528};
10529} // end anonymous namespace
10530
Richard Smith64cb9ca2017-02-22 22:09:50 +000010531static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10532 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000010533 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010534 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000010535}
10536
10537//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000010538// Void expression evaluation, primarily for a cast to void on the LHS of a
10539// comma operator
10540//===----------------------------------------------------------------------===//
10541
10542namespace {
10543class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010544 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000010545public:
10546 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10547
Richard Smith2e312c82012-03-03 22:46:17 +000010548 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000010549
Richard Smith7cd577b2017-08-17 19:35:50 +000010550 bool ZeroInitialization(const Expr *E) { return true; }
10551
Richard Smith42d3af92011-12-07 00:43:50 +000010552 bool VisitCastExpr(const CastExpr *E) {
10553 switch (E->getCastKind()) {
10554 default:
10555 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10556 case CK_ToVoid:
10557 VisitIgnoredValue(E->getSubExpr());
10558 return true;
10559 }
10560 }
Hal Finkela8443c32014-07-17 14:49:58 +000010561
10562 bool VisitCallExpr(const CallExpr *E) {
10563 switch (E->getBuiltinCallee()) {
10564 default:
10565 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10566 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000010567 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000010568 // The argument is not evaluated!
10569 return true;
10570 }
10571 }
Richard Smith42d3af92011-12-07 00:43:50 +000010572};
10573} // end anonymous namespace
10574
10575static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10576 assert(E->isRValue() && E->getType()->isVoidType());
10577 return VoidExprEvaluator(Info).Visit(E);
10578}
10579
10580//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000010581// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000010582//===----------------------------------------------------------------------===//
10583
Richard Smith2e312c82012-03-03 22:46:17 +000010584static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000010585 // In C, function designators are not lvalues, but we evaluate them as if they
10586 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000010587 QualType T = E->getType();
10588 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000010589 LValue LV;
10590 if (!EvaluateLValue(E, LV, Info))
10591 return false;
10592 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010593 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010594 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000010595 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010596 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010597 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010598 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010599 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000010600 LValue LV;
10601 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010602 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010603 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010604 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000010605 llvm::APFloat F(0.0);
10606 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010607 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000010608 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000010609 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000010610 ComplexValue C;
10611 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010612 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010613 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010614 } else if (T->isFixedPointType()) {
10615 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010616 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000010617 MemberPtr P;
10618 if (!EvaluateMemberPointer(E, P, Info))
10619 return false;
10620 P.moveInto(Result);
10621 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000010622 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010623 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010624 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010625 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000010626 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010627 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010628 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010629 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010630 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010631 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000010632 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010633 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010634 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010635 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010636 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000010637 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000010638 if (!EvaluateVoid(E, Info))
10639 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010640 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010641 QualType Unqual = T.getAtomicUnqualifiedType();
10642 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10643 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010644 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010645 if (!EvaluateAtomic(E, &LV, Value, Info))
10646 return false;
10647 } else {
10648 if (!EvaluateAtomic(E, nullptr, Result, Info))
10649 return false;
10650 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010651 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010652 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010653 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010654 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010655 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010656 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010657 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010658
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010659 return true;
10660}
10661
Richard Smithb228a862012-02-15 02:18:13 +000010662/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10663/// cases, the in-place evaluation is essential, since later initializers for
10664/// an object can indirectly refer to subobjects which were initialized earlier.
10665static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010666 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010667 assert(!E->isValueDependent());
10668
Richard Smith7525ff62013-05-09 07:14:00 +000010669 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010670 return false;
10671
10672 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010673 // Evaluate arrays and record types in-place, so that later initializers can
10674 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010675 QualType T = E->getType();
10676 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010677 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010678 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010679 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010680 else if (T->isAtomicType()) {
10681 QualType Unqual = T.getAtomicUnqualifiedType();
10682 if (Unqual->isArrayType() || Unqual->isRecordType())
10683 return EvaluateAtomic(E, &This, Result, Info);
10684 }
Richard Smithed5165f2011-11-04 05:33:44 +000010685 }
10686
10687 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010688 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010689}
10690
Richard Smithf57d8cb2011-12-09 22:58:01 +000010691/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10692/// lvalue-to-rvalue cast if it is an lvalue.
10693static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010694 if (E->getType().isNull())
10695 return false;
10696
Nick Lewyckyc190f962017-05-02 01:06:16 +000010697 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010698 return false;
10699
Richard Smith2e312c82012-03-03 22:46:17 +000010700 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010701 return false;
10702
10703 if (E->isGLValue()) {
10704 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010705 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010706 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010707 return false;
10708 }
10709
Richard Smith2e312c82012-03-03 22:46:17 +000010710 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010711 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010712}
Richard Smith11562c52011-10-28 17:51:58 +000010713
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010714static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010715 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010716 // Fast-path evaluations of integer literals, since we sometimes see files
10717 // containing vast quantities of these.
10718 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10719 Result.Val = APValue(APSInt(L->getValue(),
10720 L->getType()->isUnsignedIntegerType()));
10721 IsConst = true;
10722 return true;
10723 }
James Dennett0492ef02014-03-14 17:44:10 +000010724
10725 // This case should be rare, but we need to check it before we check on
10726 // the type below.
10727 if (Exp->getType().isNull()) {
10728 IsConst = false;
10729 return true;
10730 }
Fangrui Song6907ce22018-07-30 19:24:48 +000010731
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010732 // FIXME: Evaluating values of large array and record types can cause
10733 // performance problems. Only do so in C++11 for now.
10734 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10735 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010736 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010737 IsConst = false;
10738 return true;
10739 }
10740 return false;
10741}
10742
10743
Richard Smith7b553f12011-10-29 00:50:52 +000010744/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010745/// any crazy technique (that has nothing to do with language standards) that
10746/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010747/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10748/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010749bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010750 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010751 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010752 return IsConst;
Fangrui Song6907ce22018-07-30 19:24:48 +000010753
Richard Smith6d4c6582013-11-05 22:18:15 +000010754 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010755 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010756}
10757
Jay Foad39c79802011-01-12 09:06:06 +000010758bool Expr::EvaluateAsBooleanCondition(bool &Result,
10759 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010760 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010761 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010762 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010763}
10764
Richard Smith3f1d6de2018-05-21 20:36:58 +000010765static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10766 Expr::SideEffectsKind SEK) {
10767 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10768 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10769}
10770
Richard Smith5fab0c92011-12-28 19:48:30 +000010771bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10772 SideEffectsKind AllowSideEffects) const {
10773 if (!getType()->isIntegralOrEnumerationType())
10774 return false;
10775
Richard Smith11562c52011-10-28 17:51:58 +000010776 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010777 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000010778 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010779 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010780
Richard Smith11562c52011-10-28 17:51:58 +000010781 Result = ExprResult.Val.getInt();
10782 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010783}
10784
Richard Trieube234c32016-04-21 21:04:55 +000010785bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10786 SideEffectsKind AllowSideEffects) const {
10787 if (!getType()->isRealFloatingType())
10788 return false;
10789
10790 EvalResult ExprResult;
10791 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000010792 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000010793 return false;
10794
10795 Result = ExprResult.Val.getFloat();
10796 return true;
10797}
10798
Jay Foad39c79802011-01-12 09:06:06 +000010799bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010800 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010801
John McCall45d55e42010-05-07 21:00:08 +000010802 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010803 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10804 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000010805 Ctx.getLValueReferenceType(getType()), LV,
10806 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000010807 return false;
10808
Richard Smith2e312c82012-03-03 22:46:17 +000010809 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010810 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010811}
10812
Reid Kleckner1a840d22018-05-10 18:57:35 +000010813bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
10814 const ASTContext &Ctx) const {
10815 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
10816 EvalInfo Info(Ctx, Result, EM);
10817 if (!::Evaluate(Result.Val, Info, this))
10818 return false;
10819
10820 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
10821 Usage);
10822}
10823
Richard Smithd0b4dd62011-12-19 06:19:21 +000010824bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10825 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010826 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010827 // FIXME: Evaluating initializers for large array and record types can cause
10828 // performance problems. Only do so in C++11 for now.
10829 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010830 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010831 return false;
10832
Richard Smithd0b4dd62011-12-19 06:19:21 +000010833 Expr::EvalStatus EStatus;
10834 EStatus.Diag = &Notes;
10835
Richard Smith0c6124b2015-12-03 01:36:22 +000010836 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10837 ? EvalInfo::EM_ConstantExpression
10838 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010839 InitInfo.setEvaluatingDecl(VD, Value);
10840
10841 LValue LVal;
10842 LVal.set(VD);
10843
Richard Smithfddd3842011-12-30 21:15:51 +000010844 // C++11 [basic.start.init]p2:
10845 // Variables with static storage duration or thread storage duration shall be
10846 // zero-initialized before any other initialization takes place.
10847 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010848 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010849 !VD->getType()->isReferenceType()) {
10850 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010851 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010852 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010853 return false;
10854 }
10855
Richard Smith7525ff62013-05-09 07:14:00 +000010856 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10857 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010858 EStatus.HasSideEffects)
10859 return false;
10860
10861 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10862 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010863}
10864
Richard Smith7b553f12011-10-29 00:50:52 +000010865/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10866/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010867bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010868 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010869 return EvaluateAsRValue(Result, Ctx) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000010870 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010871}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010872
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010873APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010874 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010875 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010876 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010877 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010878 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010879 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010880 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010881
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010882 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010883}
John McCall864e3962010-05-07 05:32:02 +000010884
David Bolvansky3b6ae572018-10-18 20:49:06 +000010885APSInt Expr::EvaluateKnownConstIntCheckOverflow(
10886 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
10887 EvalResult EvalResult;
10888 EvalResult.Diag = Diag;
10889 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
10890 bool Result = ::EvaluateAsRValue(Info, this, EvalResult.Val);
10891 (void)Result;
10892 assert(Result && "Could not evaluate expression");
10893 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
10894
10895 return EvalResult.Val.getInt();
10896}
10897
Richard Smithe9ff7702013-11-05 22:23:30 +000010898void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010899 bool IsConst;
10900 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010901 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010902 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010903 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10904 }
10905}
10906
Richard Smithe6c01442013-06-05 00:46:14 +000010907bool Expr::EvalResult::isGlobalLValue() const {
10908 assert(Val.isLValue());
10909 return IsGlobalLValue(Val.getLValueBase());
10910}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010911
10912
John McCall864e3962010-05-07 05:32:02 +000010913/// isIntegerConstantExpr - this recursive routine will test if an expression is
10914/// an integer constant expression.
10915
10916/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10917/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010918
10919// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010920// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10921// and a (possibly null) SourceLocation indicating the location of the problem.
10922//
John McCall864e3962010-05-07 05:32:02 +000010923// Note that to reduce code duplication, this helper does no evaluation
10924// itself; the caller checks whether the expression is evaluatable, and
10925// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010926// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010927
Dan Gohman28ade552010-07-26 21:25:24 +000010928namespace {
10929
Richard Smith9e575da2012-12-28 13:25:52 +000010930enum ICEKind {
10931 /// This expression is an ICE.
10932 IK_ICE,
10933 /// This expression is not an ICE, but if it isn't evaluated, it's
10934 /// a legal subexpression for an ICE. This return value is used to handle
10935 /// the comma operator in C99 mode, and non-constant subexpressions.
10936 IK_ICEIfUnevaluated,
10937 /// This expression is not an ICE, and is not a legal subexpression for one.
10938 IK_NotICE
10939};
10940
John McCall864e3962010-05-07 05:32:02 +000010941struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010942 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010943 SourceLocation Loc;
10944
Richard Smith9e575da2012-12-28 13:25:52 +000010945 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010946};
10947
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010948}
Dan Gohman28ade552010-07-26 21:25:24 +000010949
Richard Smith9e575da2012-12-28 13:25:52 +000010950static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10951
10952static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010953
Craig Toppera31a8822013-08-22 07:09:37 +000010954static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010955 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010956 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010957 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010958 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000010959
John McCall864e3962010-05-07 05:32:02 +000010960 return NoDiag();
10961}
10962
Craig Toppera31a8822013-08-22 07:09:37 +000010963static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010964 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010965 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010966 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000010967
10968 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010969#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010970#define STMT(Node, Base) case Expr::Node##Class:
10971#define EXPR(Node, Base)
10972#include "clang/AST/StmtNodes.inc"
10973 case Expr::PredefinedExprClass:
10974 case Expr::FloatingLiteralClass:
10975 case Expr::ImaginaryLiteralClass:
10976 case Expr::StringLiteralClass:
10977 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010978 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010979 case Expr::MemberExprClass:
10980 case Expr::CompoundAssignOperatorClass:
10981 case Expr::CompoundLiteralExprClass:
10982 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010983 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010984 case Expr::ArrayInitLoopExprClass:
10985 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010986 case Expr::NoInitExprClass:
10987 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010988 case Expr::ImplicitValueInitExprClass:
10989 case Expr::ParenListExprClass:
10990 case Expr::VAArgExprClass:
10991 case Expr::AddrLabelExprClass:
10992 case Expr::StmtExprClass:
10993 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010994 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010995 case Expr::CXXDynamicCastExprClass:
10996 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010997 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010998 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010999 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011000 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000011001 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011002 case Expr::CXXThisExprClass:
11003 case Expr::CXXThrowExprClass:
11004 case Expr::CXXNewExprClass:
11005 case Expr::CXXDeleteExprClass:
11006 case Expr::CXXPseudoDestructorExprClass:
11007 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000011008 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000011009 case Expr::DependentScopeDeclRefExprClass:
11010 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000011011 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000011012 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000011013 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000011014 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000011015 case Expr::CXXTemporaryObjectExprClass:
11016 case Expr::CXXUnresolvedConstructExprClass:
11017 case Expr::CXXDependentScopeMemberExprClass:
11018 case Expr::UnresolvedMemberExprClass:
11019 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000011020 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011021 case Expr::ObjCArrayLiteralClass:
11022 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011023 case Expr::ObjCEncodeExprClass:
11024 case Expr::ObjCMessageExprClass:
11025 case Expr::ObjCSelectorExprClass:
11026 case Expr::ObjCProtocolExprClass:
11027 case Expr::ObjCIvarRefExprClass:
11028 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011029 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000011030 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000011031 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000011032 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000011033 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000011034 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000011035 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000011036 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000011037 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000011038 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000011039 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000011040 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000011041 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000011042 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000011043 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000011044 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000011045 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000011046 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011047 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000011048 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011049 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011050 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000011051
Richard Smithf137f932014-01-25 20:50:08 +000011052 case Expr::InitListExprClass: {
11053 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
11054 // form "T x = { a };" is equivalent to "T x = a;".
11055 // Unless we're initializing a reference, T is a scalar as it is known to be
11056 // of integral or enumeration type.
11057 if (E->isRValue())
11058 if (cast<InitListExpr>(E)->getNumInits() == 1)
11059 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011060 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000011061 }
11062
Douglas Gregor820ba7b2011-01-04 17:33:58 +000011063 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000011064 case Expr::GNUNullExprClass:
11065 // GCC considers the GNU __null value to be an integral constant expression.
11066 return NoDiag();
11067
John McCall7c454bb2011-07-15 05:09:51 +000011068 case Expr::SubstNonTypeTemplateParmExprClass:
11069 return
11070 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
11071
Bill Wendling7c44da22018-10-31 03:48:47 +000011072 case Expr::ConstantExprClass:
11073 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
11074
John McCall864e3962010-05-07 05:32:02 +000011075 case Expr::ParenExprClass:
11076 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000011077 case Expr::GenericSelectionExprClass:
11078 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011079 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000011080 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011081 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011082 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000011083 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000011084 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000011085 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000011086 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000011087 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000011088 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011089 return NoDiag();
11090 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000011091 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000011092 // C99 6.6/3 allows function calls within unevaluated subexpressions of
11093 // constant expressions, but they can never be ICEs because an ICE cannot
11094 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000011095 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000011096 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000011097 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011098 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011099 }
Richard Smith6365c912012-02-24 22:12:32 +000011100 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011101 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
11102 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000011103 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011104 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000011105 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000011106 // Parameter variables are never constants. Without this check,
11107 // getAnyInitializer() can find a default argument, which leads
11108 // to chaos.
11109 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000011110 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011111
11112 // C++ 7.1.5.1p2
11113 // A variable of non-volatile const-qualified integral or enumeration
11114 // type initialized by an ICE can be used in ICEs.
11115 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000011116 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000011117 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000011118
Richard Smithd0b4dd62011-12-19 06:19:21 +000011119 const VarDecl *VD;
11120 // Look for a declaration of this variable that has an initializer, and
11121 // check whether it is an ICE.
11122 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
11123 return NoDiag();
11124 else
Richard Smith9e575da2012-12-28 13:25:52 +000011125 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011126 }
11127 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011128 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000011129 }
John McCall864e3962010-05-07 05:32:02 +000011130 case Expr::UnaryOperatorClass: {
11131 const UnaryOperator *Exp = cast<UnaryOperator>(E);
11132 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011133 case UO_PostInc:
11134 case UO_PostDec:
11135 case UO_PreInc:
11136 case UO_PreDec:
11137 case UO_AddrOf:
11138 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000011139 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000011140 // C99 6.6/3 allows increment and decrement within unevaluated
11141 // subexpressions of constant expressions, but they can never be ICEs
11142 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011143 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000011144 case UO_Extension:
11145 case UO_LNot:
11146 case UO_Plus:
11147 case UO_Minus:
11148 case UO_Not:
11149 case UO_Real:
11150 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000011151 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011152 }
Reid Klecknere540d972018-11-01 17:51:48 +000011153 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000011154 }
11155 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000011156 // Note that per C99, offsetof must be an ICE. And AFAIK, using
11157 // EvaluateAsRValue matches the proposed gcc behavior for cases like
11158 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
11159 // compliance: we should warn earlier for offsetof expressions with
11160 // array subscripts that aren't ICEs, and if the array subscripts
11161 // are ICEs, the value of the offsetof must be an integer constant.
11162 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011163 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000011164 case Expr::UnaryExprOrTypeTraitExprClass: {
11165 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
11166 if ((Exp->getKind() == UETT_SizeOf) &&
11167 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011168 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011169 return NoDiag();
11170 }
11171 case Expr::BinaryOperatorClass: {
11172 const BinaryOperator *Exp = cast<BinaryOperator>(E);
11173 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011174 case BO_PtrMemD:
11175 case BO_PtrMemI:
11176 case BO_Assign:
11177 case BO_MulAssign:
11178 case BO_DivAssign:
11179 case BO_RemAssign:
11180 case BO_AddAssign:
11181 case BO_SubAssign:
11182 case BO_ShlAssign:
11183 case BO_ShrAssign:
11184 case BO_AndAssign:
11185 case BO_XorAssign:
11186 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000011187 // C99 6.6/3 allows assignments within unevaluated subexpressions of
11188 // constant expressions, but they can never be ICEs because an ICE cannot
11189 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011190 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011191
John McCalle3027922010-08-25 11:45:40 +000011192 case BO_Mul:
11193 case BO_Div:
11194 case BO_Rem:
11195 case BO_Add:
11196 case BO_Sub:
11197 case BO_Shl:
11198 case BO_Shr:
11199 case BO_LT:
11200 case BO_GT:
11201 case BO_LE:
11202 case BO_GE:
11203 case BO_EQ:
11204 case BO_NE:
11205 case BO_And:
11206 case BO_Xor:
11207 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011208 case BO_Comma:
11209 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000011210 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11211 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000011212 if (Exp->getOpcode() == BO_Div ||
11213 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000011214 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000011215 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000011216 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000011217 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011218 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011219 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011220 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000011221 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011222 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011223 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011224 }
11225 }
11226 }
John McCalle3027922010-08-25 11:45:40 +000011227 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011228 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000011229 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
11230 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000011231 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011232 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011233 } else {
11234 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011235 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011236 }
11237 }
Richard Smith9e575da2012-12-28 13:25:52 +000011238 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011239 }
John McCalle3027922010-08-25 11:45:40 +000011240 case BO_LAnd:
11241 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000011242 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11243 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011244 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000011245 // Rare case where the RHS has a comma "side-effect"; we need
11246 // to actually check the condition to see whether the side
11247 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000011248 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000011249 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000011250 return RHSResult;
11251 return NoDiag();
11252 }
11253
Richard Smith9e575da2012-12-28 13:25:52 +000011254 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011255 }
11256 }
Reid Klecknere540d972018-11-01 17:51:48 +000011257 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000011258 }
11259 case Expr::ImplicitCastExprClass:
11260 case Expr::CStyleCastExprClass:
11261 case Expr::CXXFunctionalCastExprClass:
11262 case Expr::CXXStaticCastExprClass:
11263 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000011264 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000011265 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011266 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000011267 if (isa<ExplicitCastExpr>(E)) {
11268 if (const FloatingLiteral *FL
11269 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
11270 unsigned DestWidth = Ctx.getIntWidth(E->getType());
11271 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
11272 APSInt IgnoredVal(DestWidth, !DestSigned);
11273 bool Ignored;
11274 // If the value does not fit in the destination type, the behavior is
11275 // undefined, so we are not required to treat it as a constant
11276 // expression.
11277 if (FL->getValue().convertToInteger(IgnoredVal,
11278 llvm::APFloat::rmTowardZero,
11279 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011280 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000011281 return NoDiag();
11282 }
11283 }
Eli Friedman76d4e432011-09-29 21:49:34 +000011284 switch (cast<CastExpr>(E)->getCastKind()) {
11285 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011286 case CK_AtomicToNonAtomic:
11287 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000011288 case CK_NoOp:
11289 case CK_IntegralToBoolean:
11290 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000011291 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000011292 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011293 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000011294 }
John McCall864e3962010-05-07 05:32:02 +000011295 }
John McCallc07a0c72011-02-17 10:25:35 +000011296 case Expr::BinaryConditionalOperatorClass: {
11297 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
11298 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011299 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000011300 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011301 if (FalseResult.Kind == IK_NotICE) return FalseResult;
11302 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
11303 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000011304 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000011305 return FalseResult;
11306 }
John McCall864e3962010-05-07 05:32:02 +000011307 case Expr::ConditionalOperatorClass: {
11308 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
11309 // If the condition (ignoring parens) is a __builtin_constant_p call,
11310 // then only the true side is actually considered in an integer constant
11311 // expression, and it is fully evaluated. This is an important GNU
11312 // extension. See GCC PR38377 for discussion.
11313 if (const CallExpr *CallCE
11314 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000011315 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000011316 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011317 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011318 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011319 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011320
Richard Smithf57d8cb2011-12-09 22:58:01 +000011321 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
11322 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011323
Richard Smith9e575da2012-12-28 13:25:52 +000011324 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011325 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011326 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011327 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011328 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000011329 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011330 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000011331 return NoDiag();
11332 // Rare case where the diagnostics depend on which side is evaluated
11333 // Note that if we get here, CondResult is 0, and at least one of
11334 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000011335 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000011336 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000011337 return TrueResult;
11338 }
11339 case Expr::CXXDefaultArgExprClass:
11340 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000011341 case Expr::CXXDefaultInitExprClass:
11342 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011343 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000011344 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011345 }
11346 }
11347
David Blaikiee4d798f2012-01-20 21:50:17 +000011348 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000011349}
11350
Richard Smithf57d8cb2011-12-09 22:58:01 +000011351/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000011352static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011353 const Expr *E,
11354 llvm::APSInt *Value,
11355 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000011356 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011357 if (Loc) *Loc = E->getExprLoc();
11358 return false;
11359 }
11360
Richard Smith66e05fe2012-01-18 05:21:49 +000011361 APValue Result;
11362 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000011363 return false;
11364
Richard Smith98710fc2014-11-13 23:03:19 +000011365 if (!Result.isInt()) {
11366 if (Loc) *Loc = E->getExprLoc();
11367 return false;
11368 }
11369
Richard Smith66e05fe2012-01-18 05:21:49 +000011370 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000011371 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011372}
11373
Craig Toppera31a8822013-08-22 07:09:37 +000011374bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
11375 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011376 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000011377 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011378
Richard Smith9e575da2012-12-28 13:25:52 +000011379 ICEDiag D = CheckICE(this, Ctx);
11380 if (D.Kind != IK_ICE) {
11381 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000011382 return false;
11383 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011384 return true;
11385}
11386
Craig Toppera31a8822013-08-22 07:09:37 +000011387bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011388 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011389 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011390 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
11391
11392 if (!isIntegerConstantExpr(Ctx, Loc))
11393 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000011394 // The only possible side-effects here are due to UB discovered in the
11395 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
11396 // required to treat the expression as an ICE, so we produce the folded
11397 // value.
11398 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000011399 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000011400 return true;
11401}
Richard Smith66e05fe2012-01-18 05:21:49 +000011402
Craig Toppera31a8822013-08-22 07:09:37 +000011403bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000011404 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000011405}
11406
Craig Toppera31a8822013-08-22 07:09:37 +000011407bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000011408 SourceLocation *Loc) const {
11409 // We support this checking in C++98 mode in order to diagnose compatibility
11410 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011411 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000011412
Richard Smith98a0a492012-02-14 21:38:30 +000011413 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000011414 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011415 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000011416 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000011417 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000011418
11419 APValue Scratch;
11420 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
11421
11422 if (!Diags.empty()) {
11423 IsConstExpr = false;
11424 if (Loc) *Loc = Diags[0].first;
11425 } else if (!IsConstExpr) {
11426 // FIXME: This shouldn't happen.
11427 if (Loc) *Loc = getExprLoc();
11428 }
11429
11430 return IsConstExpr;
11431}
Richard Smith253c2a32012-01-27 01:14:48 +000011432
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011433bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
11434 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000011435 ArrayRef<const Expr*> Args,
11436 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011437 Expr::EvalStatus Status;
11438 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
11439
George Burgess IV177399e2017-01-09 04:12:14 +000011440 LValue ThisVal;
11441 const LValue *ThisPtr = nullptr;
11442 if (This) {
11443#ifndef NDEBUG
11444 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11445 assert(MD && "Don't provide `this` for non-methods.");
11446 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11447#endif
11448 if (EvaluateObjectArgument(Info, This, ThisVal))
11449 ThisPtr = &ThisVal;
11450 if (Info.EvalStatus.HasSideEffects)
11451 return false;
11452 }
11453
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011454 ArgVector ArgValues(Args.size());
11455 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11456 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000011457 if ((*I)->isValueDependent() ||
11458 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011459 // If evaluation fails, throw away the argument entirely.
11460 ArgValues[I - Args.begin()] = APValue();
11461 if (Info.EvalStatus.HasSideEffects)
11462 return false;
11463 }
11464
11465 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000011466 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011467 ArgValues.data());
11468 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11469}
11470
Richard Smith253c2a32012-01-27 01:14:48 +000011471bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011472 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000011473 PartialDiagnosticAt> &Diags) {
11474 // FIXME: It would be useful to check constexpr function templates, but at the
11475 // moment the constant expression evaluator cannot cope with the non-rigorous
11476 // ASTs which we build for dependent expressions.
11477 if (FD->isDependentContext())
11478 return true;
11479
11480 Expr::EvalStatus Status;
11481 Status.Diag = &Diags;
11482
Richard Smith6d4c6582013-11-05 22:18:15 +000011483 EvalInfo Info(FD->getASTContext(), Status,
11484 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000011485
11486 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000011487 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000011488
Richard Smith7525ff62013-05-09 07:14:00 +000011489 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000011490 // is a temporary being used as the 'this' pointer.
11491 LValue This;
11492 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011493 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000011494
Richard Smith253c2a32012-01-27 01:14:48 +000011495 ArrayRef<const Expr*> Args;
11496
Richard Smith2e312c82012-03-03 22:46:17 +000011497 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000011498 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11499 // Evaluate the call as a constant initializer, to allow the construction
11500 // of objects of non-literal types.
11501 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000011502 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11503 } else {
11504 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000011505 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000011506 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000011507 }
Richard Smith253c2a32012-01-27 01:14:48 +000011508
11509 return Diags.empty();
11510}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011511
11512bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11513 const FunctionDecl *FD,
11514 SmallVectorImpl<
11515 PartialDiagnosticAt> &Diags) {
11516 Expr::EvalStatus Status;
11517 Status.Diag = &Diags;
11518
11519 EvalInfo Info(FD->getASTContext(), Status,
11520 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
11521
11522 // Fabricate a call stack frame to give the arguments a plausible cover story.
11523 ArrayRef<const Expr*> Args;
11524 ArgVector ArgValues(0);
11525 bool Success = EvaluateArgs(Args, ArgValues, Info);
11526 (void)Success;
11527 assert(Success &&
11528 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000011529 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011530
11531 APValue ResultScratch;
11532 Evaluate(ResultScratch, Info, E);
11533 return Diags.empty();
11534}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011535
11536bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11537 unsigned Type) const {
11538 if (!getType()->isPointerType())
11539 return false;
11540
11541 Expr::EvalStatus Status;
11542 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000011543 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011544}