blob: 3581d97c8b1722addfb50fb6bb1c0fc5124f02d8 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson7a241ba2008-07-03 04:20:39 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
Richard Smith253c2a32012-01-27 01:14:48 +000011// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000025// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000027//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000033//===----------------------------------------------------------------------===//
34
35#include "clang/AST/APValue.h"
36#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000037#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000038#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Tim Northover314fbfa2018-11-02 13:14:11 +000041#include "clang/AST/OSLog.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000042#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000043#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000044#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000045#include "clang/Basic/Builtins.h"
Leonard Chand3f3e162019-01-18 21:04:25 +000046#include "clang/Basic/FixedPoint.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000047#include "clang/Basic/TargetInfo.h"
Fangrui Song407659a2018-11-30 23:41:18 +000048#include "llvm/Support/SaveAndRestore.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000049#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000050#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000051#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000052
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000053#define DEBUG_TYPE "exprconstant"
54
Anders Carlsson7a241ba2008-07-03 04:20:39 +000055using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000056using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000057using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000058
Richard Smithb228a862012-02-15 02:18:13 +000059static bool IsGlobalLValue(APValue::LValueBase B);
60
John McCall93d91dc2010-05-07 17:22:02 +000061namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000062 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000063 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000064 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000065
Richard Smithb228a862012-02-15 02:18:13 +000066 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000067 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000068 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000069 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000070 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000071 //
72 // extern int arr[]; void f() { extern int arr[3]; };
73 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000074 //
75 // For now, we take the array bound from the most recent declaration.
76 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
77 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
78 QualType T = Redecl->getType();
79 if (!T->isIncompleteArrayType())
80 return T;
81 }
82 return D->getType();
83 }
Richard Smith84401042013-06-03 05:03:02 +000084
85 const Expr *Base = B.get<const Expr*>();
86
87 // For a materialized temporary, the type of the temporary we materialized
88 // may not be the type of the expression.
89 if (const MaterializeTemporaryExpr *MTE =
90 dyn_cast<MaterializeTemporaryExpr>(Base)) {
91 SmallVector<const Expr *, 2> CommaLHSs;
92 SmallVector<SubobjectAdjustment, 2> Adjustments;
93 const Expr *Temp = MTE->GetTemporaryExpr();
94 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
95 Adjustments);
96 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000097 // for it directly. Otherwise use the type after adjustment.
98 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000099 return Inner->getType();
100 }
101
102 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000103 }
104
Richard Smithd62306a2011-11-10 06:34:14 +0000105 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000106 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +0000107 static
Richard Smith84f6dcf2012-02-02 01:16:57 +0000108 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +0000109 APValue::BaseOrMemberType Value;
110 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +0000111 return Value;
112 }
113
114 /// Get an LValue path entry, which is known to not be an array index, as a
115 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000116 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000117 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000118 }
119 /// Get an LValue path entry, which is known to not be an array index, as a
120 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000121 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000122 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000123 }
124 /// Determine whether this LValue path entry for a base class names a virtual
125 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000126 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000127 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000128 }
129
George Burgess IVe3763372016-12-22 02:50:20 +0000130 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
131 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
132 const FunctionDecl *Callee = CE->getDirectCallee();
133 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
134 }
135
136 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
137 /// This will look through a single cast.
138 ///
139 /// Returns null if we couldn't unwrap a function with alloc_size.
140 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
141 if (!E->getType()->isPointerType())
142 return nullptr;
143
144 E = E->IgnoreParens();
145 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000146 // probably be a cast of some kind. In exotic cases, we might also see a
147 // top-level ExprWithCleanups. Ignore them either way.
Bill Wendling7c44da22018-10-31 03:48:47 +0000148 if (const auto *FE = dyn_cast<FullExpr>(E))
149 E = FE->getSubExpr()->IgnoreParens();
George Burgess IV47638762018-03-07 04:52:34 +0000150
George Burgess IVe3763372016-12-22 02:50:20 +0000151 if (const auto *Cast = dyn_cast<CastExpr>(E))
152 E = Cast->getSubExpr()->IgnoreParens();
153
154 if (const auto *CE = dyn_cast<CallExpr>(E))
155 return getAllocSizeAttr(CE) ? CE : nullptr;
156 return nullptr;
157 }
158
159 /// Determines whether or not the given Base contains a call to a function
160 /// with the alloc_size attribute.
161 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
162 const auto *E = Base.dyn_cast<const Expr *>();
163 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
164 }
165
Richard Smith6f4f0f12017-10-20 22:56:25 +0000166 /// The bound to claim that an array of unknown bound has.
167 /// The value in MostDerivedArraySize is undefined in this case. So, set it
168 /// to an arbitrary value that's likely to loudly break things if it's used.
169 static const uint64_t AssumedSizeForUnsizedArray =
170 std::numeric_limits<uint64_t>::max() / 2;
171
George Burgess IVe3763372016-12-22 02:50:20 +0000172 /// Determines if an LValue with the given LValueBase will have an unsized
173 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000174 /// Find the path length and type of the most-derived subobject in the given
175 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000176 static unsigned
177 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
178 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000179 uint64_t &ArraySize, QualType &Type, bool &IsArray,
180 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000181 // This only accepts LValueBases from APValues, and APValues don't support
182 // arrays that lack size info.
183 assert(!isBaseAnAllocSizeCall(Base) &&
184 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000185 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000186 Type = getType(Base);
187
Richard Smith80815602011-11-07 05:07:52 +0000188 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000189 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000190 const ArrayType *AT = Ctx.getAsArrayType(Type);
191 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000192 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000193 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000194
195 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
196 ArraySize = CAT->getSize().getZExtValue();
197 } else {
198 assert(I == 0 && "unexpected unsized array designator");
199 FirstEntryIsUnsizedArray = true;
200 ArraySize = AssumedSizeForUnsizedArray;
201 }
Richard Smith66c96992012-02-18 22:04:06 +0000202 } else if (Type->isAnyComplexType()) {
203 const ComplexType *CT = Type->castAs<ComplexType>();
204 Type = CT->getElementType();
205 ArraySize = 2;
206 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000207 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000208 } else if (const FieldDecl *FD = getAsField(Path[I])) {
209 Type = FD->getType();
210 ArraySize = 0;
211 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000212 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000213 } else {
Richard Smith80815602011-11-07 05:07:52 +0000214 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000215 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000216 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 }
Richard Smith80815602011-11-07 05:07:52 +0000218 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000219 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000220 }
221
Richard Smitha8105bc2012-01-06 16:39:00 +0000222 // The order of this enum is important for diagnostics.
223 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000224 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000225 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000226 };
227
Richard Smith96e0c102011-11-04 02:25:55 +0000228 /// A path from a glvalue to a subobject of that glvalue.
229 struct SubobjectDesignator {
230 /// True if the subobject was named in a manner not supported by C++11. Such
231 /// lvalues can still be folded, but they are not core constant expressions
232 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000233 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000234
Richard Smitha8105bc2012-01-06 16:39:00 +0000235 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000236 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000237
Daniel Jasperffdee092017-05-02 19:21:42 +0000238 /// Indicator of whether the first entry is an unsized array.
239 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000240
George Burgess IVa51c4072015-10-16 01:49:01 +0000241 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000242 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000243
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 /// The length of the path to the most-derived object of which this is a
245 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000246 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000247
George Burgess IVa51c4072015-10-16 01:49:01 +0000248 /// The size of the array of which the most-derived object is an element.
249 /// This will always be 0 if the most-derived object is not an array
250 /// element. 0 is not an indicator of whether or not the most-derived object
251 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000252 ///
253 /// If the current array is an unsized array, the value of this is
254 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000255 uint64_t MostDerivedArraySize;
256
257 /// The type of the most derived object referred to by this address.
258 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000259
Richard Smith80815602011-11-07 05:07:52 +0000260 typedef APValue::LValuePathEntry PathEntry;
261
Richard Smith96e0c102011-11-04 02:25:55 +0000262 /// The entries on the path from the glvalue to the designated subobject.
263 SmallVector<PathEntry, 8> Entries;
264
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000266
Richard Smitha8105bc2012-01-06 16:39:00 +0000267 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000268 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000269 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000270 MostDerivedPathLength(0), MostDerivedArraySize(0),
271 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000272
273 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000274 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000275 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000276 MostDerivedPathLength(0), MostDerivedArraySize(0) {
277 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000278 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000279 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000280 ArrayRef<PathEntry> VEntries = V.getLValuePath();
281 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000282 if (V.getLValueBase()) {
283 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000284 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000285 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000286 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000287 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000288 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000289 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000290 }
Richard Smith80815602011-11-07 05:07:52 +0000291 }
292 }
293
Richard Smith96e0c102011-11-04 02:25:55 +0000294 void setInvalid() {
295 Invalid = true;
296 Entries.clear();
297 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000298
George Burgess IVe3763372016-12-22 02:50:20 +0000299 /// Determine whether the most derived subobject is an array without a
300 /// known bound.
301 bool isMostDerivedAnUnsizedArray() const {
302 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000303 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000304 }
305
306 /// Determine what the most derived array's size is. Results in an assertion
307 /// failure if the most derived array lacks a size.
308 uint64_t getMostDerivedArraySize() const {
309 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
310 return MostDerivedArraySize;
311 }
312
Richard Smitha8105bc2012-01-06 16:39:00 +0000313 /// Determine whether this is a one-past-the-end pointer.
314 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000315 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000316 if (IsOnePastTheEnd)
317 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000318 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000319 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
320 return true;
321 return false;
322 }
323
Richard Smith06f71b52018-08-04 00:57:17 +0000324 /// Get the range of valid index adjustments in the form
325 /// {maximum value that can be subtracted from this pointer,
326 /// maximum value that can be added to this pointer}
327 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
328 if (Invalid || isMostDerivedAnUnsizedArray())
329 return {0, 0};
330
331 // [expr.add]p4: For the purposes of these operators, a pointer to a
332 // nonarray object behaves the same as a pointer to the first element of
333 // an array of length one with the type of the object as its element type.
334 bool IsArray = MostDerivedPathLength == Entries.size() &&
335 MostDerivedIsArrayElement;
336 uint64_t ArrayIndex =
337 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
338 uint64_t ArraySize =
339 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
340 return {ArrayIndex, ArraySize - ArrayIndex};
341 }
342
Richard Smitha8105bc2012-01-06 16:39:00 +0000343 /// Check that this refers to a valid subobject.
344 bool isValidSubobject() const {
345 if (Invalid)
346 return false;
347 return !isOnePastTheEnd();
348 }
349 /// Check that this refers to a valid subobject, and if not, produce a
350 /// relevant diagnostic and set the designator as invalid.
351 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
352
Richard Smith06f71b52018-08-04 00:57:17 +0000353 /// Get the type of the designated object.
354 QualType getType(ASTContext &Ctx) const {
355 assert(!Invalid && "invalid designator has no subobject type");
356 return MostDerivedPathLength == Entries.size()
357 ? MostDerivedType
358 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
359 }
360
Richard Smitha8105bc2012-01-06 16:39:00 +0000361 /// Update this designator to refer to the first element within this array.
362 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000363 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000364 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000365 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000366
367 // This is a most-derived object.
368 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000369 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000370 MostDerivedArraySize = CAT->getSize().getZExtValue();
371 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000372 }
George Burgess IVe3763372016-12-22 02:50:20 +0000373 /// Update this designator to refer to the first element within the array of
374 /// elements of type T. This is an array of unknown size.
375 void addUnsizedArrayUnchecked(QualType ElemTy) {
376 PathEntry Entry;
377 Entry.ArrayIndex = 0;
378 Entries.push_back(Entry);
379
380 MostDerivedType = ElemTy;
381 MostDerivedIsArrayElement = true;
382 // The value in MostDerivedArraySize is undefined in this case. So, set it
383 // to an arbitrary value that's likely to loudly break things if it's
384 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000385 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000386 MostDerivedPathLength = Entries.size();
387 }
Richard Smith96e0c102011-11-04 02:25:55 +0000388 /// Update this designator to refer to the given base or member of this
389 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000390 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000391 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000392 APValue::BaseOrMemberType Value(D, Virtual);
393 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000394 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000395
396 // If this isn't a base class, it's a new most-derived object.
397 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
398 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000399 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000400 MostDerivedArraySize = 0;
401 MostDerivedPathLength = Entries.size();
402 }
Richard Smith96e0c102011-11-04 02:25:55 +0000403 }
Richard Smith66c96992012-02-18 22:04:06 +0000404 /// Update this designator to refer to the given complex component.
405 void addComplexUnchecked(QualType EltTy, bool Imag) {
406 PathEntry Entry;
407 Entry.ArrayIndex = Imag;
408 Entries.push_back(Entry);
409
410 // This is technically a most-derived object, though in practice this
411 // is unlikely to matter.
412 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000413 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000414 MostDerivedArraySize = 2;
415 MostDerivedPathLength = Entries.size();
416 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000417 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000418 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
419 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000420 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000421 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
422 if (Invalid || !N) return;
423 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
424 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000425 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000426 // Can't verify -- trust that the user is doing the right thing (or if
427 // not, trust that the caller will catch the bad behavior).
428 // FIXME: Should we reject if this overflows, at least?
429 Entries.back().ArrayIndex += TruncatedN;
430 return;
431 }
432
433 // [expr.add]p4: For the purposes of these operators, a pointer to a
434 // nonarray object behaves the same as a pointer to the first element of
435 // an array of length one with the type of the object as its element type.
436 bool IsArray = MostDerivedPathLength == Entries.size() &&
437 MostDerivedIsArrayElement;
438 uint64_t ArrayIndex =
439 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
440 uint64_t ArraySize =
441 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
442
443 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
444 // Calculate the actual index in a wide enough type, so we can include
445 // it in the note.
446 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
447 (llvm::APInt&)N += ArrayIndex;
448 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
449 diagnosePointerArithmetic(Info, E, N);
450 setInvalid();
451 return;
452 }
453
454 ArrayIndex += TruncatedN;
455 assert(ArrayIndex <= ArraySize &&
456 "bounds check succeeded for out-of-bounds index");
457
458 if (IsArray)
459 Entries.back().ArrayIndex = ArrayIndex;
460 else
461 IsOnePastTheEnd = (ArrayIndex != 0);
462 }
Richard Smith96e0c102011-11-04 02:25:55 +0000463 };
464
Richard Smith254a73d2011-10-28 22:34:42 +0000465 /// A stack frame in the constexpr call stack.
466 struct CallStackFrame {
467 EvalInfo &Info;
468
469 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000470 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000471
Richard Smithf6f003a2011-12-16 19:06:07 +0000472 /// Callee - The function which was called.
473 const FunctionDecl *Callee;
474
Richard Smithd62306a2011-11-10 06:34:14 +0000475 /// This - The binding for the this pointer in this call, if any.
476 const LValue *This;
477
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000478 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000479 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000480 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000481
Eli Friedman4830ec82012-06-25 21:21:08 +0000482 // Note that we intentionally use std::map here so that references to
483 // values are stable.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000484 typedef std::pair<const void *, unsigned> MapKeyTy;
485 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000486 /// Temporaries - Temporary lvalues materialized within this stack frame.
487 MapTy Temporaries;
488
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000489 /// CallLoc - The location of the call expression for this call.
490 SourceLocation CallLoc;
491
492 /// Index - The call index of this call.
493 unsigned Index;
494
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000495 /// The stack of integers for tracking version numbers for temporaries.
496 SmallVector<unsigned, 2> TempVersionStack = {1};
497 unsigned CurTempVersion = TempVersionStack.back();
498
499 unsigned getTempVersion() const { return TempVersionStack.back(); }
500
501 void pushTempVersion() {
502 TempVersionStack.push_back(++CurTempVersion);
503 }
504
505 void popTempVersion() {
506 TempVersionStack.pop_back();
507 }
508
Faisal Vali051e3a22017-02-16 04:12:21 +0000509 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000510 // on the overall stack usage of deeply-recursing constexpr evaluations.
Faisal Vali051e3a22017-02-16 04:12:21 +0000511 // (We should cache this map rather than recomputing it repeatedly.)
512 // But let's try this and see how it goes; we can look into caching the map
513 // as a later change.
514
515 /// LambdaCaptureFields - Mapping from captured variables/this to
516 /// corresponding data members in the closure class.
517 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
518 FieldDecl *LambdaThisCaptureField;
519
Richard Smithf6f003a2011-12-16 19:06:07 +0000520 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
521 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000522 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000523 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000524
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000525 // Return the temporary for Key whose version number is Version.
526 APValue *getTemporary(const void *Key, unsigned Version) {
527 MapKeyTy KV(Key, Version);
528 auto LB = Temporaries.lower_bound(KV);
529 if (LB != Temporaries.end() && LB->first == KV)
530 return &LB->second;
531 // Pair (Key,Version) wasn't found in the map. Check that no elements
532 // in the map have 'Key' as their key.
533 assert((LB == Temporaries.end() || LB->first.first != Key) &&
534 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
535 "Element with key 'Key' found in map");
536 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000537 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000538
539 // Return the current temporary for Key in the map.
540 APValue *getCurrentTemporary(const void *Key) {
541 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
542 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
543 return &std::prev(UB)->second;
544 return nullptr;
545 }
546
547 // Return the version number of the current temporary for Key.
548 unsigned getCurrentTemporaryVersion(const void *Key) const {
549 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
550 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
551 return std::prev(UB)->first.second;
552 return 0;
553 }
554
Richard Smith08d6a2c2013-07-24 07:11:57 +0000555 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000556 };
557
Richard Smith852c9db2013-04-20 22:23:05 +0000558 /// Temporarily override 'this'.
559 class ThisOverrideRAII {
560 public:
561 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
562 : Frame(Frame), OldThis(Frame.This) {
563 if (Enable)
564 Frame.This = NewThis;
565 }
566 ~ThisOverrideRAII() {
567 Frame.This = OldThis;
568 }
569 private:
570 CallStackFrame &Frame;
571 const LValue *OldThis;
572 };
573
Richard Smith92b1ce02011-12-12 09:28:41 +0000574 /// A partial diagnostic which we might know in advance that we are not going
575 /// to emit.
576 class OptionalDiagnostic {
577 PartialDiagnostic *Diag;
578
579 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000580 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
581 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000582
583 template<typename T>
584 OptionalDiagnostic &operator<<(const T &v) {
585 if (Diag)
586 *Diag << v;
587 return *this;
588 }
Richard Smithfe800032012-01-31 04:08:20 +0000589
590 OptionalDiagnostic &operator<<(const APSInt &I) {
591 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000592 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000593 I.toString(Buffer);
594 *Diag << StringRef(Buffer.data(), Buffer.size());
595 }
596 return *this;
597 }
598
599 OptionalDiagnostic &operator<<(const APFloat &F) {
600 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000601 // FIXME: Force the precision of the source value down so we don't
602 // print digits which are usually useless (we don't really care here if
603 // we truncate a digit by accident in edge cases). Ideally,
Fangrui Song6907ce22018-07-30 19:24:48 +0000604 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000605 // representation which rounds to the correct value, but it's a bit
606 // tricky to implement.
607 unsigned precision =
608 llvm::APFloat::semanticsPrecision(F.getSemantics());
609 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000610 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000611 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000612 *Diag << StringRef(Buffer.data(), Buffer.size());
613 }
614 return *this;
615 }
Leonard Chand3f3e162019-01-18 21:04:25 +0000616
617 OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
618 if (Diag) {
619 SmallVector<char, 32> Buffer;
620 FX.toString(Buffer);
621 *Diag << StringRef(Buffer.data(), Buffer.size());
622 }
623 return *this;
624 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000625 };
626
Richard Smith08d6a2c2013-07-24 07:11:57 +0000627 /// A cleanup, and a flag indicating whether it is lifetime-extended.
628 class Cleanup {
629 llvm::PointerIntPair<APValue*, 1, bool> Value;
630
631 public:
632 Cleanup(APValue *Val, bool IsLifetimeExtended)
633 : Value(Val, IsLifetimeExtended) {}
634
635 bool isLifetimeExtended() const { return Value.getInt(); }
636 void endLifetime() {
637 *Value.getPointer() = APValue();
638 }
639 };
640
Richard Smithb228a862012-02-15 02:18:13 +0000641 /// EvalInfo - This is a private struct used by the evaluator to capture
642 /// information about a subexpression as it is folded. It retains information
643 /// about the AST context, but also maintains information about the folded
644 /// expression.
645 ///
646 /// If an expression could be evaluated, it is still possible it is not a C
647 /// "integer constant expression" or constant expression. If not, this struct
648 /// captures information about how and why not.
649 ///
650 /// One bit of information passed *into* the request for constant folding
651 /// indicates whether the subexpression is "evaluated" or not according to C
652 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
653 /// evaluate the expression regardless of what the RHS is, but C only allows
654 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000655 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000656 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000657
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000658 /// EvalStatus - Contains information about the evaluation.
659 Expr::EvalStatus &EvalStatus;
660
661 /// CurrentCall - The top of the constexpr call stack.
662 CallStackFrame *CurrentCall;
663
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000664 /// CallStackDepth - The number of calls in the call stack right now.
665 unsigned CallStackDepth;
666
Richard Smithb228a862012-02-15 02:18:13 +0000667 /// NextCallIndex - The next call index to assign.
668 unsigned NextCallIndex;
669
Richard Smitha3d3bd22013-05-08 02:12:03 +0000670 /// StepsLeft - The remaining number of evaluation steps we're permitted
671 /// to perform. This is essentially a limit for the number of statements
672 /// we will evaluate.
673 unsigned StepsLeft;
674
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000675 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000676 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000677 CallStackFrame BottomFrame;
678
Richard Smith08d6a2c2013-07-24 07:11:57 +0000679 /// A stack of values whose lifetimes end at the end of some surrounding
680 /// evaluation frame.
681 llvm::SmallVector<Cleanup, 16> CleanupStack;
682
Richard Smithd62306a2011-11-10 06:34:14 +0000683 /// EvaluatingDecl - This is the declaration whose initializer is being
684 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000685 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000686
687 /// EvaluatingDeclValue - This is the value being constructed for the
688 /// declaration whose initializer is being evaluated, if any.
689 APValue *EvaluatingDeclValue;
690
Erik Pilkington42925492017-10-04 00:18:55 +0000691 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
692 /// the call index that that lvalue was allocated in.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000693 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
694 EvaluatingObject;
Erik Pilkington42925492017-10-04 00:18:55 +0000695
696 /// EvaluatingConstructors - Set of objects that are currently being
697 /// constructed.
698 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
699
700 struct EvaluatingConstructorRAII {
701 EvalInfo &EI;
702 EvaluatingObject Object;
703 bool DidInsert;
704 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
705 : EI(EI), Object(Object) {
706 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
707 }
708 ~EvaluatingConstructorRAII() {
709 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
710 }
711 };
712
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000713 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
714 unsigned Version) {
715 return EvaluatingConstructors.count(
716 EvaluatingObject(Decl, {CallIndex, Version}));
Erik Pilkington42925492017-10-04 00:18:55 +0000717 }
718
Richard Smith37be3362019-05-04 04:00:45 +0000719 /// If we're currently speculatively evaluating, the outermost call stack
720 /// depth at which we can mutate state, otherwise 0.
721 unsigned SpeculativeEvaluationDepth = 0;
722
Richard Smith410306b2016-12-12 02:53:20 +0000723 /// The current array initialization index, if we're performing array
724 /// initialization.
725 uint64_t ArrayInitIndex = -1;
726
Richard Smith357362d2011-12-13 06:39:58 +0000727 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
728 /// notes attached to it will also be stored, otherwise they will not be.
729 bool HasActiveDiagnostic;
730
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000731 /// Have we emitted a diagnostic explaining why we couldn't constant
Richard Smith0c6124b2015-12-03 01:36:22 +0000732 /// fold (not just why it's not strictly a constant expression)?
733 bool HasFoldFailureDiagnostic;
734
Fangrui Song407659a2018-11-30 23:41:18 +0000735 /// Whether or not we're in a context where the front end requires a
736 /// constant value.
737 bool InConstantContext;
738
Richard Smith6d4c6582013-11-05 22:18:15 +0000739 enum EvaluationMode {
740 /// Evaluate as a constant expression. Stop if we find that the expression
741 /// is not a constant expression.
742 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000743
Richard Smith6d4c6582013-11-05 22:18:15 +0000744 /// Evaluate as a potential constant expression. Keep going if we hit a
745 /// construct that we can't evaluate yet (because we don't yet know the
746 /// value of something) but stop if we hit something that could never be
747 /// a constant expression.
748 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000749
Richard Smith6d4c6582013-11-05 22:18:15 +0000750 /// Fold the expression to a constant. Stop if we hit a side-effect that
751 /// we can't model.
752 EM_ConstantFold,
753
754 /// Evaluate the expression looking for integer overflow and similar
755 /// issues. Don't worry about side-effects, and try to visit all
756 /// subexpressions.
757 EM_EvaluateForOverflow,
758
759 /// Evaluate in any way we know how. Don't worry about side-effects that
760 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000761 EM_IgnoreSideEffects,
762
763 /// Evaluate as a constant expression. Stop if we find that the expression
764 /// is not a constant expression. Some expressions can be retried in the
765 /// optimizer if we don't constant fold them here, but in an unevaluated
766 /// context we try to fold them immediately since the optimizer never
767 /// gets a chance to look at it.
768 EM_ConstantExpressionUnevaluated,
769
770 /// Evaluate as a potential constant expression. Keep going if we hit a
771 /// construct that we can't evaluate yet (because we don't yet know the
772 /// value of something) but stop if we hit something that could never be
773 /// a constant expression. Some expressions can be retried in the
774 /// optimizer if we don't constant fold them here, but in an unevaluated
775 /// context we try to fold them immediately since the optimizer never
776 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000777 EM_PotentialConstantExpressionUnevaluated,
Richard Smith6d4c6582013-11-05 22:18:15 +0000778 } EvalMode;
779
780 /// Are we checking whether the expression is a potential constant
781 /// expression?
782 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000783 return EvalMode == EM_PotentialConstantExpression ||
784 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000785 }
786
787 /// Are we checking an expression for overflow?
788 // FIXME: We should check for any kind of undefined or suspicious behavior
789 // in such constructs, not just overflow.
790 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
791
792 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000793 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000794 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000795 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000796 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
797 EvaluatingDecl((const ValueDecl *)nullptr),
798 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
Richard Smith37be3362019-05-04 04:00:45 +0000799 HasFoldFailureDiagnostic(false),
Fangrui Song407659a2018-11-30 23:41:18 +0000800 InConstantContext(false), EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000801
Richard Smith7525ff62013-05-09 07:14:00 +0000802 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
803 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000804 EvaluatingDeclValue = &Value;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000805 EvaluatingConstructors.insert({Base, {0, 0}});
Richard Smithd62306a2011-11-10 06:34:14 +0000806 }
807
David Blaikiebbafb8a2012-03-11 07:00:24 +0000808 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000809
Richard Smith357362d2011-12-13 06:39:58 +0000810 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000811 // Don't perform any constexpr calls (other than the call we're checking)
812 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000813 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000814 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000815 if (NextCallIndex == 0) {
816 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000817 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000818 return false;
819 }
Richard Smith357362d2011-12-13 06:39:58 +0000820 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
821 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000822 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000823 << getLangOpts().ConstexprCallDepth;
824 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000825 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000826
Richard Smith37be3362019-05-04 04:00:45 +0000827 std::pair<CallStackFrame *, unsigned>
828 getCallFrameAndDepth(unsigned CallIndex) {
829 assert(CallIndex && "no call index in getCallFrameAndDepth");
Richard Smithb228a862012-02-15 02:18:13 +0000830 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
831 // be null in this loop.
Richard Smith37be3362019-05-04 04:00:45 +0000832 unsigned Depth = CallStackDepth;
Richard Smithb228a862012-02-15 02:18:13 +0000833 CallStackFrame *Frame = CurrentCall;
Richard Smith37be3362019-05-04 04:00:45 +0000834 while (Frame->Index > CallIndex) {
Richard Smithb228a862012-02-15 02:18:13 +0000835 Frame = Frame->Caller;
Richard Smith37be3362019-05-04 04:00:45 +0000836 --Depth;
837 }
838 if (Frame->Index == CallIndex)
839 return {Frame, Depth};
840 return {nullptr, 0};
Richard Smithb228a862012-02-15 02:18:13 +0000841 }
842
Richard Smitha3d3bd22013-05-08 02:12:03 +0000843 bool nextStep(const Stmt *S) {
844 if (!StepsLeft) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000845 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000846 return false;
847 }
848 --StepsLeft;
849 return true;
850 }
851
Richard Smith357362d2011-12-13 06:39:58 +0000852 private:
853 /// Add a diagnostic to the diagnostics list.
854 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
855 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
856 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
857 return EvalStatus.Diag->back().second;
858 }
859
Richard Smithf6f003a2011-12-16 19:06:07 +0000860 /// Add notes containing a call stack to the current point of evaluation.
861 void addCallStack(unsigned Limit);
862
Faisal Valie690b7a2016-07-02 22:34:24 +0000863 private:
864 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
865 unsigned ExtraNotes, bool IsCCEDiag) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000866
Richard Smith92b1ce02011-12-12 09:28:41 +0000867 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000868 // If we have a prior diagnostic, it will be noting that the expression
869 // isn't a constant expression. This diagnostic is more important,
870 // unless we require this evaluation to produce a constant expression.
871 //
872 // FIXME: We might want to show both diagnostics to the user in
873 // EM_ConstantFold mode.
874 if (!EvalStatus.Diag->empty()) {
875 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000876 case EM_ConstantFold:
877 case EM_IgnoreSideEffects:
878 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000879 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000880 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000881 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000882 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000883 case EM_ConstantExpression:
884 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000885 case EM_ConstantExpressionUnevaluated:
886 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000887 HasActiveDiagnostic = false;
888 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000889 }
890 }
891
Richard Smithf6f003a2011-12-16 19:06:07 +0000892 unsigned CallStackNotes = CallStackDepth - 1;
893 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
894 if (Limit)
895 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000896 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000897 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000898
Richard Smith357362d2011-12-13 06:39:58 +0000899 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000900 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000901 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000902 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
903 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000904 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000905 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000906 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000907 }
Richard Smith357362d2011-12-13 06:39:58 +0000908 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000909 return OptionalDiagnostic();
910 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000911 public:
912 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
913 OptionalDiagnostic
914 FFDiag(SourceLocation Loc,
915 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
916 unsigned ExtraNotes = 0) {
917 return Diag(Loc, DiagId, ExtraNotes, false);
918 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000919
Faisal Valie690b7a2016-07-02 22:34:24 +0000920 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000921 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000922 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000923 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000924 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000925 HasActiveDiagnostic = false;
926 return OptionalDiagnostic();
927 }
928
Richard Smith92b1ce02011-12-12 09:28:41 +0000929 /// Diagnose that the evaluation does not produce a C++11 core constant
930 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000931 ///
932 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
933 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000934 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000935 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000936 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000937 // Don't override a previous diagnostic. Don't bother collecting
938 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000939 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000940 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000941 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000942 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000943 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000944 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000945 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
946 = diag::note_invalid_subexpr_in_const_expr,
947 unsigned ExtraNotes = 0) {
948 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
949 }
Richard Smith357362d2011-12-13 06:39:58 +0000950 /// Add a note to a prior diagnostic.
951 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
952 if (!HasActiveDiagnostic)
953 return OptionalDiagnostic();
954 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000955 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000956
957 /// Add a stack of notes to a prior diagnostic.
958 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
959 if (HasActiveDiagnostic) {
960 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
961 Diags.begin(), Diags.end());
962 }
963 }
Richard Smith253c2a32012-01-27 01:14:48 +0000964
Richard Smith6d4c6582013-11-05 22:18:15 +0000965 /// Should we continue evaluation after encountering a side-effect that we
966 /// couldn't model?
967 bool keepEvaluatingAfterSideEffect() {
968 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000969 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000970 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000971 case EM_EvaluateForOverflow:
972 case EM_IgnoreSideEffects:
973 return true;
974
Richard Smith6d4c6582013-11-05 22:18:15 +0000975 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000976 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000977 case EM_ConstantFold:
978 return false;
979 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000980 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000981 }
982
983 /// Note that we have had a side-effect, and determine whether we should
984 /// keep evaluating.
985 bool noteSideEffect() {
986 EvalStatus.HasSideEffects = true;
987 return keepEvaluatingAfterSideEffect();
988 }
989
Richard Smithce8eca52015-12-08 03:21:47 +0000990 /// Should we continue evaluation after encountering undefined behavior?
991 bool keepEvaluatingAfterUndefinedBehavior() {
992 switch (EvalMode) {
993 case EM_EvaluateForOverflow:
994 case EM_IgnoreSideEffects:
995 case EM_ConstantFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000996 return true;
997
998 case EM_PotentialConstantExpression:
999 case EM_PotentialConstantExpressionUnevaluated:
1000 case EM_ConstantExpression:
1001 case EM_ConstantExpressionUnevaluated:
1002 return false;
1003 }
1004 llvm_unreachable("Missed EvalMode case");
1005 }
1006
1007 /// Note that we hit something that was technically undefined behavior, but
1008 /// that we can evaluate past it (such as signed overflow or floating-point
1009 /// division by zero.)
1010 bool noteUndefinedBehavior() {
1011 EvalStatus.HasUndefinedBehavior = true;
1012 return keepEvaluatingAfterUndefinedBehavior();
1013 }
1014
Richard Smith253c2a32012-01-27 01:14:48 +00001015 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +00001016 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +00001017 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +00001018 if (!StepsLeft)
1019 return false;
1020
1021 switch (EvalMode) {
1022 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001023 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001024 case EM_EvaluateForOverflow:
1025 return true;
1026
1027 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001028 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +00001029 case EM_ConstantFold:
1030 case EM_IgnoreSideEffects:
1031 return false;
1032 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001033 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001034 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001035
George Burgess IV8c892b52016-05-25 22:31:54 +00001036 /// Notes that we failed to evaluate an expression that other expressions
1037 /// directly depend on, and determine if we should keep evaluating. This
1038 /// should only be called if we actually intend to keep evaluating.
1039 ///
1040 /// Call noteSideEffect() instead if we may be able to ignore the value that
1041 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1042 ///
1043 /// (Foo(), 1) // use noteSideEffect
1044 /// (Foo() || true) // use noteSideEffect
1045 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001046 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001047 // Failure when evaluating some expression often means there is some
1048 // subexpression whose evaluation was skipped. Therefore, (because we
1049 // don't track whether we skipped an expression when unwinding after an
1050 // evaluation failure) every evaluation failure that bubbles up from a
1051 // subexpression implies that a side-effect has potentially happened. We
1052 // skip setting the HasSideEffects flag to true until we decide to
1053 // continue evaluating after that point, which happens here.
1054 bool KeepGoing = keepEvaluatingAfterFailure();
1055 EvalStatus.HasSideEffects |= KeepGoing;
1056 return KeepGoing;
1057 }
1058
Richard Smith410306b2016-12-12 02:53:20 +00001059 class ArrayInitLoopIndex {
1060 EvalInfo &Info;
1061 uint64_t OuterIndex;
1062
1063 public:
1064 ArrayInitLoopIndex(EvalInfo &Info)
1065 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1066 Info.ArrayInitIndex = 0;
1067 }
1068 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1069
1070 operator uint64_t&() { return Info.ArrayInitIndex; }
1071 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001072 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001073
1074 /// Object used to treat all foldable expressions as constant expressions.
1075 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001076 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001077 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001078 bool HadNoPriorDiags;
1079 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001080
Richard Smith6d4c6582013-11-05 22:18:15 +00001081 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1082 : Info(Info),
1083 Enabled(Enabled),
1084 HadNoPriorDiags(Info.EvalStatus.Diag &&
1085 Info.EvalStatus.Diag->empty() &&
1086 !Info.EvalStatus.HasSideEffects),
1087 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001088 if (Enabled &&
1089 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1090 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001091 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001092 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001093 void keepDiagnostics() { Enabled = false; }
1094 ~FoldConstant() {
1095 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001096 !Info.EvalStatus.HasSideEffects)
1097 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001098 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001099 }
1100 };
Richard Smith17100ba2012-02-16 02:46:34 +00001101
James Y Knight892b09b2018-10-10 02:53:43 +00001102 /// RAII object used to set the current evaluation mode to ignore
1103 /// side-effects.
1104 struct IgnoreSideEffectsRAII {
George Burgess IV3a03fab2015-09-04 21:28:13 +00001105 EvalInfo &Info;
1106 EvalInfo::EvaluationMode OldMode;
James Y Knight892b09b2018-10-10 02:53:43 +00001107 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001108 : Info(Info), OldMode(Info.EvalMode) {
1109 if (!Info.checkingPotentialConstantExpression())
James Y Knight892b09b2018-10-10 02:53:43 +00001110 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001111 }
1112
James Y Knight892b09b2018-10-10 02:53:43 +00001113 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001114 };
1115
George Burgess IV8c892b52016-05-25 22:31:54 +00001116 /// RAII object used to optionally suppress diagnostics and side-effects from
1117 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001118 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001119 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001120 Expr::EvalStatus OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001121 unsigned OldSpeculativeEvaluationDepth;
Richard Smith17100ba2012-02-16 02:46:34 +00001122
George Burgess IV8c892b52016-05-25 22:31:54 +00001123 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001124 Info = Other.Info;
1125 OldStatus = Other.OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001126 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001127 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001128 }
1129
1130 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001131 if (!Info)
1132 return;
1133
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001134 Info->EvalStatus = OldStatus;
Richard Smith37be3362019-05-04 04:00:45 +00001135 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
George Burgess IV8c892b52016-05-25 22:31:54 +00001136 }
1137
Richard Smith17100ba2012-02-16 02:46:34 +00001138 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001139 SpeculativeEvaluationRAII() = default;
1140
1141 SpeculativeEvaluationRAII(
1142 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001143 : Info(&Info), OldStatus(Info.EvalStatus),
Richard Smith37be3362019-05-04 04:00:45 +00001144 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
Richard Smith17100ba2012-02-16 02:46:34 +00001145 Info.EvalStatus.Diag = NewDiag;
Richard Smith37be3362019-05-04 04:00:45 +00001146 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
Richard Smith17100ba2012-02-16 02:46:34 +00001147 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001148
1149 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1150 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1151 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001152 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001153
1154 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1155 maybeRestoreState();
1156 moveFromAndCancel(std::move(Other));
1157 return *this;
1158 }
1159
1160 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001161 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001162
1163 /// RAII object wrapping a full-expression or block scope, and handling
1164 /// the ending of the lifetime of temporaries created within it.
1165 template<bool IsFullExpression>
1166 class ScopeRAII {
1167 EvalInfo &Info;
1168 unsigned OldStackSize;
1169 public:
1170 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001171 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1172 // Push a new temporary version. This is needed to distinguish between
1173 // temporaries created in different iterations of a loop.
1174 Info.CurrentCall->pushTempVersion();
1175 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001176 ~ScopeRAII() {
1177 // Body moved to a static method to encourage the compiler to inline away
1178 // instances of this class.
1179 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001180 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001181 }
1182 private:
1183 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1184 unsigned NewEnd = OldStackSize;
1185 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1186 I != N; ++I) {
1187 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1188 // Full-expression cleanup of a lifetime-extended temporary: nothing
1189 // to do, just move this cleanup to the right place in the stack.
1190 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1191 ++NewEnd;
1192 } else {
1193 // End the lifetime of the object.
1194 Info.CleanupStack[I].endLifetime();
1195 }
1196 }
1197 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1198 Info.CleanupStack.end());
1199 }
1200 };
1201 typedef ScopeRAII<false> BlockScopeRAII;
1202 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001203}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001204
Richard Smitha8105bc2012-01-06 16:39:00 +00001205bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1206 CheckSubobjectKind CSK) {
1207 if (Invalid)
1208 return false;
1209 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001210 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001211 << CSK;
1212 setInvalid();
1213 return false;
1214 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001215 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1216 // must actually be at least one array element; even a VLA cannot have a
1217 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001218 return true;
1219}
1220
Richard Smith6f4f0f12017-10-20 22:56:25 +00001221void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1222 const Expr *E) {
1223 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1224 // Do not set the designator as invalid: we can represent this situation,
1225 // and correct handling of __builtin_object_size requires us to do so.
1226}
1227
Richard Smitha8105bc2012-01-06 16:39:00 +00001228void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001229 const Expr *E,
1230 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001231 // If we're complaining, we must be able to statically determine the size of
1232 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001233 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001234 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001235 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001236 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001237 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001238 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001239 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001240 setInvalid();
1241}
1242
Richard Smithf6f003a2011-12-16 19:06:07 +00001243CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1244 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001245 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001246 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1247 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001248 Info.CurrentCall = this;
1249 ++Info.CallStackDepth;
1250}
1251
1252CallStackFrame::~CallStackFrame() {
1253 assert(Info.CurrentCall == this && "calls retired out of order");
1254 --Info.CallStackDepth;
1255 Info.CurrentCall = Caller;
1256}
1257
Richard Smith08d6a2c2013-07-24 07:11:57 +00001258APValue &CallStackFrame::createTemporary(const void *Key,
1259 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001260 unsigned Version = Info.CurrentCall->getTempVersion();
1261 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smith08d6a2c2013-07-24 07:11:57 +00001262 assert(Result.isUninit() && "temporary created multiple times");
1263 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1264 return Result;
1265}
1266
Richard Smith84401042013-06-03 05:03:02 +00001267static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001268
1269void EvalInfo::addCallStack(unsigned Limit) {
1270 // Determine which calls to skip, if any.
1271 unsigned ActiveCalls = CallStackDepth - 1;
1272 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1273 if (Limit && Limit < ActiveCalls) {
1274 SkipStart = Limit / 2 + Limit % 2;
1275 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001276 }
1277
Richard Smithf6f003a2011-12-16 19:06:07 +00001278 // Walk the call stack and add the diagnostics.
1279 unsigned CallIdx = 0;
1280 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1281 Frame = Frame->Caller, ++CallIdx) {
1282 // Skip this call?
1283 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1284 if (CallIdx == SkipStart) {
1285 // Note that we're skipping calls.
1286 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1287 << unsigned(ActiveCalls - Limit);
1288 }
1289 continue;
1290 }
1291
Richard Smith5179eb72016-06-28 19:03:57 +00001292 // Use a different note for an inheriting constructor, because from the
1293 // user's perspective it's not really a function at all.
1294 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1295 if (CD->isInheritingConstructor()) {
1296 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1297 << CD->getParent();
1298 continue;
1299 }
1300 }
1301
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001302 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001303 llvm::raw_svector_ostream Out(Buffer);
1304 describeCall(Frame, Out);
1305 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1306 }
1307}
1308
Hubert Tong147b7432018-12-12 16:53:43 +00001309/// Kinds of access we can perform on an object, for diagnostics.
1310enum AccessKinds {
1311 AK_Read,
1312 AK_Assign,
1313 AK_Increment,
1314 AK_Decrement
1315};
1316
Richard Smithf6f003a2011-12-16 19:06:07 +00001317namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001318 struct ComplexValue {
1319 private:
1320 bool IsInt;
1321
1322 public:
1323 APSInt IntReal, IntImag;
1324 APFloat FloatReal, FloatImag;
1325
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001326 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001327
1328 void makeComplexFloat() { IsInt = false; }
1329 bool isComplexFloat() const { return !IsInt; }
1330 APFloat &getComplexFloatReal() { return FloatReal; }
1331 APFloat &getComplexFloatImag() { return FloatImag; }
1332
1333 void makeComplexInt() { IsInt = true; }
1334 bool isComplexInt() const { return IsInt; }
1335 APSInt &getComplexIntReal() { return IntReal; }
1336 APSInt &getComplexIntImag() { return IntImag; }
1337
Richard Smith2e312c82012-03-03 22:46:17 +00001338 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001339 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001340 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001341 else
Richard Smith2e312c82012-03-03 22:46:17 +00001342 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001343 }
Richard Smith2e312c82012-03-03 22:46:17 +00001344 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001345 assert(v.isComplexFloat() || v.isComplexInt());
1346 if (v.isComplexFloat()) {
1347 makeComplexFloat();
1348 FloatReal = v.getComplexFloatReal();
1349 FloatImag = v.getComplexFloatImag();
1350 } else {
1351 makeComplexInt();
1352 IntReal = v.getComplexIntReal();
1353 IntImag = v.getComplexIntImag();
1354 }
1355 }
John McCall93d91dc2010-05-07 17:22:02 +00001356 };
John McCall45d55e42010-05-07 21:00:08 +00001357
1358 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001359 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001360 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001361 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001362 bool IsNullPtr : 1;
1363 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001364
Richard Smithce40ad62011-11-12 22:28:03 +00001365 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001366 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001367 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001368 SubobjectDesignator &getLValueDesignator() { return Designator; }
1369 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001370 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001371
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001372 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1373 unsigned getLValueVersion() const { return Base.getVersion(); }
1374
Richard Smith2e312c82012-03-03 22:46:17 +00001375 void moveInto(APValue &V) const {
1376 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001377 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001378 else {
1379 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001380 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001381 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001382 }
John McCall45d55e42010-05-07 21:00:08 +00001383 }
Richard Smith2e312c82012-03-03 22:46:17 +00001384 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001385 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001386 Base = V.getLValueBase();
1387 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001388 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001389 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001390 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001391 }
1392
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001393 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001394#ifndef NDEBUG
1395 // We only allow a few types of invalid bases. Enforce that here.
1396 if (BInvalid) {
1397 const auto *E = B.get<const Expr *>();
1398 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1399 "Unexpected type of invalid base");
1400 }
1401#endif
1402
Richard Smithce40ad62011-11-12 22:28:03 +00001403 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001404 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001405 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001406 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001407 IsNullPtr = false;
1408 }
1409
1410 void setNull(QualType PointerTy, uint64_t TargetVal) {
1411 Base = (Expr *)nullptr;
1412 Offset = CharUnits::fromQuantity(TargetVal);
1413 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001414 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1415 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001416 }
1417
George Burgess IV3a03fab2015-09-04 21:28:13 +00001418 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001419 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001420 }
1421
Hubert Tong147b7432018-12-12 16:53:43 +00001422 private:
Richard Smitha8105bc2012-01-06 16:39:00 +00001423 // Check that this LValue is not based on a null pointer. If it is, produce
1424 // a diagnostic and mark the designator as invalid.
Hubert Tong147b7432018-12-12 16:53:43 +00001425 template <typename GenDiagType>
1426 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001427 if (Designator.Invalid)
1428 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001429 if (IsNullPtr) {
Hubert Tong147b7432018-12-12 16:53:43 +00001430 GenDiag();
Richard Smitha8105bc2012-01-06 16:39:00 +00001431 Designator.setInvalid();
1432 return false;
1433 }
1434 return true;
1435 }
1436
Hubert Tong147b7432018-12-12 16:53:43 +00001437 public:
1438 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1439 CheckSubobjectKind CSK) {
1440 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1441 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1442 });
1443 }
1444
1445 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1446 AccessKinds AK) {
1447 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1448 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1449 });
1450 }
1451
Richard Smitha8105bc2012-01-06 16:39:00 +00001452 // Check this LValue refers to an object. If not, set the designator to be
1453 // invalid and emit a diagnostic.
1454 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001455 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001456 Designator.checkSubobject(Info, E, CSK);
1457 }
1458
1459 void addDecl(EvalInfo &Info, const Expr *E,
1460 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001461 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1462 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001463 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001464 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1465 if (!Designator.Entries.empty()) {
1466 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1467 Designator.setInvalid();
1468 return;
1469 }
Richard Smithefdb5032017-11-15 03:03:56 +00001470 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1471 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1472 Designator.FirstEntryIsAnUnsizedArray = true;
1473 Designator.addUnsizedArrayUnchecked(ElemTy);
1474 }
George Burgess IVe3763372016-12-22 02:50:20 +00001475 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001476 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001477 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1478 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001479 }
Richard Smith66c96992012-02-18 22:04:06 +00001480 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001481 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1482 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001483 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001484 void clearIsNullPointer() {
1485 IsNullPtr = false;
1486 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001487 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1488 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001489 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1490 // but we're not required to diagnose it and it's valid in C++.)
1491 if (!Index)
1492 return;
1493
1494 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1495 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1496 // offsets.
1497 uint64_t Offset64 = Offset.getQuantity();
1498 uint64_t ElemSize64 = ElementSize.getQuantity();
1499 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1500 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1501
1502 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001503 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001504 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001505 }
1506 void adjustOffset(CharUnits N) {
1507 Offset += N;
1508 if (N.getQuantity())
1509 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001510 }
John McCall45d55e42010-05-07 21:00:08 +00001511 };
Richard Smith027bf112011-11-17 22:56:20 +00001512
1513 struct MemberPtr {
1514 MemberPtr() {}
1515 explicit MemberPtr(const ValueDecl *Decl) :
1516 DeclAndIsDerivedMember(Decl, false), Path() {}
1517
1518 /// The member or (direct or indirect) field referred to by this member
1519 /// pointer, or 0 if this is a null member pointer.
1520 const ValueDecl *getDecl() const {
1521 return DeclAndIsDerivedMember.getPointer();
1522 }
1523 /// Is this actually a member of some type derived from the relevant class?
1524 bool isDerivedMember() const {
1525 return DeclAndIsDerivedMember.getInt();
1526 }
1527 /// Get the class which the declaration actually lives in.
1528 const CXXRecordDecl *getContainingRecord() const {
1529 return cast<CXXRecordDecl>(
1530 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1531 }
1532
Richard Smith2e312c82012-03-03 22:46:17 +00001533 void moveInto(APValue &V) const {
1534 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001535 }
Richard Smith2e312c82012-03-03 22:46:17 +00001536 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001537 assert(V.isMemberPointer());
1538 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1539 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1540 Path.clear();
1541 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1542 Path.insert(Path.end(), P.begin(), P.end());
1543 }
1544
1545 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1546 /// whether the member is a member of some class derived from the class type
1547 /// of the member pointer.
1548 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1549 /// Path - The path of base/derived classes from the member declaration's
1550 /// class (exclusive) to the class type of the member pointer (inclusive).
1551 SmallVector<const CXXRecordDecl*, 4> Path;
1552
1553 /// Perform a cast towards the class of the Decl (either up or down the
1554 /// hierarchy).
1555 bool castBack(const CXXRecordDecl *Class) {
1556 assert(!Path.empty());
1557 const CXXRecordDecl *Expected;
1558 if (Path.size() >= 2)
1559 Expected = Path[Path.size() - 2];
1560 else
1561 Expected = getContainingRecord();
1562 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1563 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1564 // if B does not contain the original member and is not a base or
1565 // derived class of the class containing the original member, the result
1566 // of the cast is undefined.
1567 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1568 // (D::*). We consider that to be a language defect.
1569 return false;
1570 }
1571 Path.pop_back();
1572 return true;
1573 }
1574 /// Perform a base-to-derived member pointer cast.
1575 bool castToDerived(const CXXRecordDecl *Derived) {
1576 if (!getDecl())
1577 return true;
1578 if (!isDerivedMember()) {
1579 Path.push_back(Derived);
1580 return true;
1581 }
1582 if (!castBack(Derived))
1583 return false;
1584 if (Path.empty())
1585 DeclAndIsDerivedMember.setInt(false);
1586 return true;
1587 }
1588 /// Perform a derived-to-base member pointer cast.
1589 bool castToBase(const CXXRecordDecl *Base) {
1590 if (!getDecl())
1591 return true;
1592 if (Path.empty())
1593 DeclAndIsDerivedMember.setInt(true);
1594 if (isDerivedMember()) {
1595 Path.push_back(Base);
1596 return true;
1597 }
1598 return castBack(Base);
1599 }
1600 };
Richard Smith357362d2011-12-13 06:39:58 +00001601
Richard Smith7bb00672012-02-01 01:42:44 +00001602 /// Compare two member pointers, which are assumed to be of the same type.
1603 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1604 if (!LHS.getDecl() || !RHS.getDecl())
1605 return !LHS.getDecl() && !RHS.getDecl();
1606 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1607 return false;
1608 return LHS.Path == RHS.Path;
1609 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001610}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001611
Richard Smith2e312c82012-03-03 22:46:17 +00001612static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001613static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1614 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001615 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001616static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1617 bool InvalidBaseOK = false);
1618static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1619 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001620static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1621 EvalInfo &Info);
1622static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001623static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001624static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001625 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001626static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001627static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001628static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1629 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001630static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001631
Leonard Chand3f3e162019-01-18 21:04:25 +00001632/// Evaluate an integer or fixed point expression into an APResult.
1633static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1634 EvalInfo &Info);
1635
1636/// Evaluate only a fixed point expression into an APResult.
1637static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1638 EvalInfo &Info);
1639
Chris Lattner05706e882008-07-11 18:11:29 +00001640//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001641// Misc utilities
1642//===----------------------------------------------------------------------===//
1643
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001644/// A helper function to create a temporary and set an LValue.
1645template <class KeyTy>
1646static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1647 LValue &LV, CallStackFrame &Frame) {
1648 LV.set({Key, Frame.Info.CurrentCall->Index,
1649 Frame.Info.CurrentCall->getTempVersion()});
1650 return Frame.createTemporary(Key, IsLifetimeExtended);
1651}
1652
Richard Smithd6cc1982017-01-31 02:23:02 +00001653/// Negate an APSInt in place, converting it to a signed form if necessary, and
1654/// preserving its value (by extending by up to one bit as needed).
1655static void negateAsSigned(APSInt &Int) {
1656 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1657 Int = Int.extend(Int.getBitWidth() + 1);
1658 Int.setIsSigned(true);
1659 }
1660 Int = -Int;
1661}
1662
Richard Smith84401042013-06-03 05:03:02 +00001663/// Produce a string describing the given constexpr call.
1664static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1665 unsigned ArgIndex = 0;
1666 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1667 !isa<CXXConstructorDecl>(Frame->Callee) &&
1668 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1669
1670 if (!IsMemberCall)
1671 Out << *Frame->Callee << '(';
1672
1673 if (Frame->This && IsMemberCall) {
1674 APValue Val;
1675 Frame->This->moveInto(Val);
1676 Val.printPretty(Out, Frame->Info.Ctx,
1677 Frame->This->Designator.MostDerivedType);
1678 // FIXME: Add parens around Val if needed.
1679 Out << "->" << *Frame->Callee << '(';
1680 IsMemberCall = false;
1681 }
1682
1683 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1684 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1685 if (ArgIndex > (unsigned)IsMemberCall)
1686 Out << ", ";
1687
1688 const ParmVarDecl *Param = *I;
1689 const APValue &Arg = Frame->Arguments[ArgIndex];
1690 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1691
1692 if (ArgIndex == 0 && IsMemberCall)
1693 Out << "->" << *Frame->Callee << '(';
1694 }
1695
1696 Out << ')';
1697}
1698
Richard Smithd9f663b2013-04-22 15:31:51 +00001699/// Evaluate an expression to see if it had side-effects, and discard its
1700/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001701/// \return \c true if the caller should keep evaluating.
1702static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001703 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001704 if (!Evaluate(Scratch, Info, E))
1705 // We don't need the value, but we might have skipped a side effect here.
1706 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001707 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001708}
1709
Richard Smithd62306a2011-11-10 06:34:14 +00001710/// Should this call expression be treated as a string literal?
1711static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001712 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001713 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1714 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1715}
1716
Richard Smithce40ad62011-11-12 22:28:03 +00001717static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001718 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1719 // constant expression of pointer type that evaluates to...
1720
1721 // ... a null pointer value, or a prvalue core constant expression of type
1722 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001723 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001724
Richard Smithce40ad62011-11-12 22:28:03 +00001725 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1726 // ... the address of an object with static storage duration,
1727 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1728 return VD->hasGlobalStorage();
1729 // ... the address of a function,
1730 return isa<FunctionDecl>(D);
1731 }
1732
1733 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001734 switch (E->getStmtClass()) {
1735 default:
1736 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001737 case Expr::CompoundLiteralExprClass: {
1738 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1739 return CLE->isFileScope() && CLE->isLValue();
1740 }
Richard Smithe6c01442013-06-05 00:46:14 +00001741 case Expr::MaterializeTemporaryExprClass:
1742 // A materialized temporary might have been lifetime-extended to static
1743 // storage duration.
1744 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001745 // A string literal has static storage duration.
1746 case Expr::StringLiteralClass:
1747 case Expr::PredefinedExprClass:
1748 case Expr::ObjCStringLiteralClass:
1749 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001750 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001751 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001752 return true;
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001753 case Expr::ObjCBoxedExprClass:
1754 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
Richard Smithd62306a2011-11-10 06:34:14 +00001755 case Expr::CallExprClass:
1756 return IsStringLiteralCall(cast<CallExpr>(E));
1757 // For GCC compatibility, &&label has static storage duration.
1758 case Expr::AddrLabelExprClass:
1759 return true;
1760 // A Block literal expression may be used as the initialization value for
1761 // Block variables at global or local static scope.
1762 case Expr::BlockExprClass:
1763 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001764 case Expr::ImplicitValueInitExprClass:
1765 // FIXME:
1766 // We can never form an lvalue with an implicit value initialization as its
1767 // base through expression evaluation, so these only appear in one case: the
1768 // implicit variable declaration we invent when checking whether a constexpr
1769 // constructor can produce a constant expression. We must assume that such
1770 // an expression might be a global lvalue.
1771 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001772 }
John McCall95007602010-05-10 23:27:23 +00001773}
1774
Richard Smith06f71b52018-08-04 00:57:17 +00001775static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1776 return LVal.Base.dyn_cast<const ValueDecl*>();
1777}
1778
1779static bool IsLiteralLValue(const LValue &Value) {
1780 if (Value.getLValueCallIndex())
1781 return false;
1782 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1783 return E && !isa<MaterializeTemporaryExpr>(E);
1784}
1785
1786static bool IsWeakLValue(const LValue &Value) {
1787 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1788 return Decl && Decl->isWeak();
1789}
1790
1791static bool isZeroSized(const LValue &Value) {
1792 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1793 if (Decl && isa<VarDecl>(Decl)) {
1794 QualType Ty = Decl->getType();
1795 if (Ty->isArrayType())
1796 return Ty->isIncompleteType() ||
1797 Decl->getASTContext().getTypeSize(Ty) == 0;
1798 }
1799 return false;
1800}
1801
1802static bool HasSameBase(const LValue &A, const LValue &B) {
1803 if (!A.getLValueBase())
1804 return !B.getLValueBase();
1805 if (!B.getLValueBase())
1806 return false;
1807
1808 if (A.getLValueBase().getOpaqueValue() !=
1809 B.getLValueBase().getOpaqueValue()) {
1810 const Decl *ADecl = GetLValueBaseDecl(A);
1811 if (!ADecl)
1812 return false;
1813 const Decl *BDecl = GetLValueBaseDecl(B);
1814 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1815 return false;
1816 }
1817
1818 return IsGlobalLValue(A.getLValueBase()) ||
1819 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1820 A.getLValueVersion() == B.getLValueVersion());
1821}
1822
Richard Smithb228a862012-02-15 02:18:13 +00001823static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1824 assert(Base && "no location for a null lvalue");
1825 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1826 if (VD)
1827 Info.Note(VD->getLocation(), diag::note_declared_at);
1828 else
Ted Kremenek28831752012-08-23 20:46:57 +00001829 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001830 diag::note_constexpr_temporary_here);
1831}
1832
Richard Smith80815602011-11-07 05:07:52 +00001833/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001834/// value for an address or reference constant expression. Return true if we
1835/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001836static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001837 QualType Type, const LValue &LVal,
1838 Expr::ConstExprUsage Usage) {
Richard Smithb228a862012-02-15 02:18:13 +00001839 bool IsReferenceType = Type->isReferenceType();
1840
Richard Smith357362d2011-12-13 06:39:58 +00001841 APValue::LValueBase Base = LVal.getLValueBase();
1842 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1843
Richard Smith0dea49e2012-02-18 04:58:18 +00001844 // Check that the object is a global. Note that the fake 'this' object we
1845 // manufacture when checking potential constant expressions is conservatively
1846 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001847 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001848 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001849 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001850 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001851 << IsReferenceType << !Designator.Entries.empty()
1852 << !!VD << VD;
1853 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001854 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001855 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001856 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001857 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001858 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001859 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001860 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001861 LVal.getLValueCallIndex() == 0) &&
1862 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001863
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001864 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1865 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001866 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001867 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001868 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001869
Hans Wennborg82dd8772014-06-25 22:19:48 +00001870 // A dllimport variable never acts like a constant.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001871 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001872 return false;
1873 }
1874 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1875 // __declspec(dllimport) must be handled very carefully:
1876 // We must never initialize an expression with the thunk in C++.
1877 // Doing otherwise would allow the same id-expression to yield
1878 // different addresses for the same function in different translation
1879 // units. However, this means that we must dynamically initialize the
1880 // expression with the contents of the import address table at runtime.
1881 //
1882 // The C language has no notion of ODR; furthermore, it has no notion of
1883 // dynamic initialization. This means that we are permitted to
1884 // perform initialization with the address of the thunk.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001885 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1886 FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001887 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001888 }
1889 }
1890
Richard Smitha8105bc2012-01-06 16:39:00 +00001891 // Allow address constant expressions to be past-the-end pointers. This is
1892 // an extension: the standard requires them to point to an object.
1893 if (!IsReferenceType)
1894 return true;
1895
1896 // A reference constant expression must refer to an object.
1897 if (!Base) {
1898 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001899 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001900 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001901 }
1902
Richard Smith357362d2011-12-13 06:39:58 +00001903 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001904 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001905 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001906 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001907 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001908 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001909 }
1910
Richard Smith80815602011-11-07 05:07:52 +00001911 return true;
1912}
1913
Reid Klecknercd016d82017-07-07 22:04:29 +00001914/// Member pointers are constant expressions unless they point to a
1915/// non-virtual dllimport member function.
1916static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1917 SourceLocation Loc,
1918 QualType Type,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001919 const APValue &Value,
1920 Expr::ConstExprUsage Usage) {
Reid Klecknercd016d82017-07-07 22:04:29 +00001921 const ValueDecl *Member = Value.getMemberPointerDecl();
1922 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1923 if (!FD)
1924 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001925 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1926 !FD->hasAttr<DLLImportAttr>();
Reid Klecknercd016d82017-07-07 22:04:29 +00001927}
1928
Richard Smithfddd3842011-12-30 21:15:51 +00001929/// Check that this core constant expression is of literal type, and if not,
1930/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001931static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001932 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001933 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001934 return true;
1935
Richard Smith7525ff62013-05-09 07:14:00 +00001936 // C++1y: A constant initializer for an object o [...] may also invoke
1937 // constexpr constructors for o and its subobjects even if those objects
1938 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001939 //
1940 // C++11 missed this detail for aggregates, so classes like this:
1941 // struct foo_t { union { int i; volatile int j; } u; };
1942 // are not (obviously) initializable like so:
1943 // __attribute__((__require_constant_initialization__))
1944 // static const foo_t x = {{0}};
1945 // because "i" is a subobject with non-literal initialization (due to the
1946 // volatile member of the union). See:
1947 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1948 // Therefore, we use the C++1y behavior.
1949 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001950 return true;
1951
Richard Smithfddd3842011-12-30 21:15:51 +00001952 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001953 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001954 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001955 << E->getType();
1956 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001957 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001958 return false;
1959}
1960
Richard Smith0b0a0b62011-10-29 20:57:55 +00001961/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001962/// constant expression. If not, report an appropriate diagnostic. Does not
1963/// check that the expression is of literal type.
Reid Kleckner1a840d22018-05-10 18:57:35 +00001964static bool
1965CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1966 const APValue &Value,
1967 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
Richard Smith1a90f592013-06-18 17:51:51 +00001968 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001969 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001970 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001971 return false;
1972 }
1973
Richard Smith77be48a2014-07-31 06:31:19 +00001974 // We allow _Atomic(T) to be initialized from anything that T can be
1975 // initialized from.
1976 if (const AtomicType *AT = Type->getAs<AtomicType>())
1977 Type = AT->getValueType();
1978
Richard Smithb228a862012-02-15 02:18:13 +00001979 // Core issue 1454: For a literal constant expression of array or class type,
1980 // each subobject of its value shall have been initialized by a constant
1981 // expression.
1982 if (Value.isArray()) {
1983 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1984 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1985 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
Reid Kleckner1a840d22018-05-10 18:57:35 +00001986 Value.getArrayInitializedElt(I), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00001987 return false;
1988 }
1989 if (!Value.hasArrayFiller())
1990 return true;
Reid Kleckner1a840d22018-05-10 18:57:35 +00001991 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1992 Usage);
Richard Smith80815602011-11-07 05:07:52 +00001993 }
Richard Smithb228a862012-02-15 02:18:13 +00001994 if (Value.isUnion() && Value.getUnionField()) {
1995 return CheckConstantExpression(Info, DiagLoc,
1996 Value.getUnionField()->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00001997 Value.getUnionValue(), Usage);
Richard Smithb228a862012-02-15 02:18:13 +00001998 }
1999 if (Value.isStruct()) {
2000 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2001 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2002 unsigned BaseIndex = 0;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002003 for (const CXXBaseSpecifier &BS : CD->bases()) {
2004 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
2005 Value.getStructBase(BaseIndex), Usage))
Richard Smithb228a862012-02-15 02:18:13 +00002006 return false;
Reid Kleckner1a840d22018-05-10 18:57:35 +00002007 ++BaseIndex;
Richard Smithb228a862012-02-15 02:18:13 +00002008 }
2009 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002010 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00002011 if (I->isUnnamedBitfield())
2012 continue;
2013
David Blaikie2d7c57e2012-04-30 02:36:29 +00002014 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
Reid Kleckner1a840d22018-05-10 18:57:35 +00002015 Value.getStructField(I->getFieldIndex()),
2016 Usage))
Richard Smithb228a862012-02-15 02:18:13 +00002017 return false;
2018 }
2019 }
2020
2021 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00002022 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00002023 LVal.setFrom(Info.Ctx, Value);
Reid Kleckner1a840d22018-05-10 18:57:35 +00002024 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
Richard Smithb228a862012-02-15 02:18:13 +00002025 }
2026
Reid Klecknercd016d82017-07-07 22:04:29 +00002027 if (Value.isMemberPointer())
Reid Kleckner1a840d22018-05-10 18:57:35 +00002028 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
Reid Klecknercd016d82017-07-07 22:04:29 +00002029
Richard Smithb228a862012-02-15 02:18:13 +00002030 // Everything else is fine.
2031 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002032}
2033
Richard Smith2e312c82012-03-03 22:46:17 +00002034static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00002035 // A null base expression indicates a null pointer. These are always
2036 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00002037 if (!Value.getLValueBase()) {
2038 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00002039 return true;
2040 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00002041
Richard Smith027bf112011-11-17 22:56:20 +00002042 // We have a non-null base. These are generally known to be true, but if it's
2043 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00002044 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00002045 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00002046 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00002047}
2048
Richard Smith2e312c82012-03-03 22:46:17 +00002049static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00002050 switch (Val.getKind()) {
2051 case APValue::Uninitialized:
2052 return false;
2053 case APValue::Int:
2054 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00002055 return true;
Leonard Chan86285d22019-01-16 18:53:05 +00002056 case APValue::FixedPoint:
2057 Result = Val.getFixedPoint().getBoolValue();
2058 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002059 case APValue::Float:
2060 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00002061 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002062 case APValue::ComplexInt:
2063 Result = Val.getComplexIntReal().getBoolValue() ||
2064 Val.getComplexIntImag().getBoolValue();
2065 return true;
2066 case APValue::ComplexFloat:
2067 Result = !Val.getComplexFloatReal().isZero() ||
2068 !Val.getComplexFloatImag().isZero();
2069 return true;
Richard Smith027bf112011-11-17 22:56:20 +00002070 case APValue::LValue:
2071 return EvalPointerValueAsBool(Val, Result);
2072 case APValue::MemberPointer:
2073 Result = Val.getMemberPointerDecl();
2074 return true;
Richard Smith11562c52011-10-28 17:51:58 +00002075 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00002076 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00002077 case APValue::Struct:
2078 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00002079 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00002080 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002081 }
2082
Richard Smith11562c52011-10-28 17:51:58 +00002083 llvm_unreachable("unknown APValue kind");
2084}
2085
2086static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2087 EvalInfo &Info) {
2088 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00002089 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002090 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00002091 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00002092 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00002093}
2094
Richard Smith357362d2011-12-13 06:39:58 +00002095template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00002096static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002097 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002098 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002099 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002100 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002101}
2102
2103static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2104 QualType SrcType, const APFloat &Value,
2105 QualType DestType, APSInt &Result) {
2106 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002107 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002108 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002109
Richard Smith357362d2011-12-13 06:39:58 +00002110 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002111 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002112 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2113 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002114 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002115 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002116}
2117
Richard Smith357362d2011-12-13 06:39:58 +00002118static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2119 QualType SrcType, QualType DestType,
2120 APFloat &Result) {
2121 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002122 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002123 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2124 APFloat::rmNearestTiesToEven, &ignored)
2125 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002126 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002127 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002128}
2129
Richard Smith911e1422012-01-30 22:27:01 +00002130static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2131 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002132 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002133 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002134 // Figure out if this is a truncate, extend or noop cast.
2135 // If the input is signed, do a sign extend, noop, or truncate.
Richard Smithbd844e02018-11-12 20:11:57 +00002136 APSInt Result = Value.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002137 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Richard Smithbd844e02018-11-12 20:11:57 +00002138 if (DestType->isBooleanType())
2139 Result = Value.getBoolValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002140 return Result;
2141}
2142
Richard Smith357362d2011-12-13 06:39:58 +00002143static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2144 QualType SrcType, const APSInt &Value,
2145 QualType DestType, APFloat &Result) {
2146 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2147 if (Result.convertFromAPInt(Value, Value.isSigned(),
2148 APFloat::rmNearestTiesToEven)
2149 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002150 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002151 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002152}
2153
Richard Smith49ca8aa2013-08-06 07:09:20 +00002154static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2155 APValue &Value, const FieldDecl *FD) {
2156 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2157
2158 if (!Value.isInt()) {
2159 // Trying to store a pointer-cast-to-integer into a bitfield.
2160 // FIXME: In this case, we should provide the diagnostic for casting
2161 // a pointer to an integer.
2162 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002163 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002164 return false;
2165 }
2166
2167 APSInt &Int = Value.getInt();
2168 unsigned OldBitWidth = Int.getBitWidth();
2169 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2170 if (NewBitWidth < OldBitWidth)
2171 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2172 return true;
2173}
2174
Eli Friedman803acb32011-12-22 03:51:45 +00002175static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2176 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002177 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002178 if (!Evaluate(SVal, Info, E))
2179 return false;
2180 if (SVal.isInt()) {
2181 Res = SVal.getInt();
2182 return true;
2183 }
2184 if (SVal.isFloat()) {
2185 Res = SVal.getFloat().bitcastToAPInt();
2186 return true;
2187 }
2188 if (SVal.isVector()) {
2189 QualType VecTy = E->getType();
2190 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2191 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2192 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2193 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2194 Res = llvm::APInt::getNullValue(VecSize);
2195 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2196 APValue &Elt = SVal.getVectorElt(i);
2197 llvm::APInt EltAsInt;
2198 if (Elt.isInt()) {
2199 EltAsInt = Elt.getInt();
2200 } else if (Elt.isFloat()) {
2201 EltAsInt = Elt.getFloat().bitcastToAPInt();
2202 } else {
2203 // Don't try to handle vectors of anything other than int or float
2204 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002205 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002206 return false;
2207 }
2208 unsigned BaseEltSize = EltAsInt.getBitWidth();
2209 if (BigEndian)
2210 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2211 else
2212 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2213 }
2214 return true;
2215 }
2216 // Give up if the input isn't an int, float, or vector. For example, we
2217 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002218 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002219 return false;
2220}
2221
Richard Smith43e77732013-05-07 04:50:00 +00002222/// Perform the given integer operation, which is known to need at most BitWidth
2223/// bits, and check for overflow in the original type (if that type was not an
2224/// unsigned type).
2225template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002226static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2227 const APSInt &LHS, const APSInt &RHS,
2228 unsigned BitWidth, Operation Op,
2229 APSInt &Result) {
2230 if (LHS.isUnsigned()) {
2231 Result = Op(LHS, RHS);
2232 return true;
2233 }
Richard Smith43e77732013-05-07 04:50:00 +00002234
2235 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002236 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002237 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002238 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002239 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002240 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002241 << Result.toString(10) << E->getType();
2242 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002243 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002244 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002245 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002246}
2247
2248/// Perform the given binary integer operation.
2249static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2250 BinaryOperatorKind Opcode, APSInt RHS,
2251 APSInt &Result) {
2252 switch (Opcode) {
2253 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002254 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002255 return false;
2256 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002257 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2258 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002259 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002260 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2261 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002262 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002263 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2264 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002265 case BO_And: Result = LHS & RHS; return true;
2266 case BO_Xor: Result = LHS ^ RHS; return true;
2267 case BO_Or: Result = LHS | RHS; return true;
2268 case BO_Div:
2269 case BO_Rem:
2270 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002271 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002272 return false;
2273 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002274 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2275 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2276 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002277 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2278 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002279 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2280 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002281 return true;
2282 case BO_Shl: {
2283 if (Info.getLangOpts().OpenCL)
2284 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2285 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2286 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2287 RHS.isUnsigned());
2288 else if (RHS.isSigned() && RHS.isNegative()) {
2289 // During constant-folding, a negative shift is an opposite shift. Such
2290 // a shift is not a constant expression.
2291 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2292 RHS = -RHS;
2293 goto shift_right;
2294 }
2295 shift_left:
2296 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2297 // the shifted type.
2298 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2299 if (SA != RHS) {
2300 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2301 << RHS << E->getType() << LHS.getBitWidth();
2302 } else if (LHS.isSigned()) {
2303 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2304 // operand, and must not overflow the corresponding unsigned type.
2305 if (LHS.isNegative())
2306 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2307 else if (LHS.countLeadingZeros() < SA)
2308 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2309 }
2310 Result = LHS << SA;
2311 return true;
2312 }
2313 case BO_Shr: {
2314 if (Info.getLangOpts().OpenCL)
2315 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2316 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2317 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2318 RHS.isUnsigned());
2319 else if (RHS.isSigned() && RHS.isNegative()) {
2320 // During constant-folding, a negative shift is an opposite shift. Such a
2321 // shift is not a constant expression.
2322 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2323 RHS = -RHS;
2324 goto shift_left;
2325 }
2326 shift_right:
2327 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2328 // shifted type.
2329 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2330 if (SA != RHS)
2331 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2332 << RHS << E->getType() << LHS.getBitWidth();
2333 Result = LHS >> SA;
2334 return true;
2335 }
2336
2337 case BO_LT: Result = LHS < RHS; return true;
2338 case BO_GT: Result = LHS > RHS; return true;
2339 case BO_LE: Result = LHS <= RHS; return true;
2340 case BO_GE: Result = LHS >= RHS; return true;
2341 case BO_EQ: Result = LHS == RHS; return true;
2342 case BO_NE: Result = LHS != RHS; return true;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00002343 case BO_Cmp:
2344 llvm_unreachable("BO_Cmp should be handled elsewhere");
Richard Smith43e77732013-05-07 04:50:00 +00002345 }
2346}
2347
Richard Smith861b5b52013-05-07 23:34:45 +00002348/// Perform the given binary floating-point operation, in-place, on LHS.
2349static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2350 APFloat &LHS, BinaryOperatorKind Opcode,
2351 const APFloat &RHS) {
2352 switch (Opcode) {
2353 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002354 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002355 return false;
2356 case BO_Mul:
2357 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2358 break;
2359 case BO_Add:
2360 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2361 break;
2362 case BO_Sub:
2363 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2364 break;
2365 case BO_Div:
2366 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2367 break;
2368 }
2369
Richard Smith0c6124b2015-12-03 01:36:22 +00002370 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002371 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002372 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002373 }
Richard Smith861b5b52013-05-07 23:34:45 +00002374 return true;
2375}
2376
Richard Smitha8105bc2012-01-06 16:39:00 +00002377/// Cast an lvalue referring to a base subobject to a derived class, by
2378/// truncating the lvalue's path to the given length.
2379static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2380 const RecordDecl *TruncatedType,
2381 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002382 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002383
2384 // Check we actually point to a derived class object.
2385 if (TruncatedElements == D.Entries.size())
2386 return true;
2387 assert(TruncatedElements >= D.MostDerivedPathLength &&
2388 "not casting to a derived class");
2389 if (!Result.checkSubobject(Info, E, CSK_Derived))
2390 return false;
2391
2392 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002393 const RecordDecl *RD = TruncatedType;
2394 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002395 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002396 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2397 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002398 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002399 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002400 else
Richard Smithd62306a2011-11-10 06:34:14 +00002401 Result.Offset -= Layout.getBaseClassOffset(Base);
2402 RD = Base;
2403 }
Richard Smith027bf112011-11-17 22:56:20 +00002404 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002405 return true;
2406}
2407
John McCalld7bca762012-05-01 00:38:49 +00002408static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002409 const CXXRecordDecl *Derived,
2410 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002411 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002412 if (!RL) {
2413 if (Derived->isInvalidDecl()) return false;
2414 RL = &Info.Ctx.getASTRecordLayout(Derived);
2415 }
2416
Richard Smithd62306a2011-11-10 06:34:14 +00002417 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002418 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002419 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002420}
2421
Richard Smitha8105bc2012-01-06 16:39:00 +00002422static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002423 const CXXRecordDecl *DerivedDecl,
2424 const CXXBaseSpecifier *Base) {
2425 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2426
John McCalld7bca762012-05-01 00:38:49 +00002427 if (!Base->isVirtual())
2428 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002429
Richard Smitha8105bc2012-01-06 16:39:00 +00002430 SubobjectDesignator &D = Obj.Designator;
2431 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002432 return false;
2433
Richard Smitha8105bc2012-01-06 16:39:00 +00002434 // Extract most-derived object and corresponding type.
2435 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2436 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2437 return false;
2438
2439 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002440 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002441 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2442 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002443 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002444 return true;
2445}
2446
Richard Smith84401042013-06-03 05:03:02 +00002447static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2448 QualType Type, LValue &Result) {
2449 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2450 PathE = E->path_end();
2451 PathI != PathE; ++PathI) {
2452 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2453 *PathI))
2454 return false;
2455 Type = (*PathI)->getType();
2456 }
2457 return true;
2458}
2459
Richard Smithd62306a2011-11-10 06:34:14 +00002460/// Update LVal to refer to the given field, which must be a member of the type
2461/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002462static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002463 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002464 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002465 if (!RL) {
2466 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002467 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002468 }
Richard Smithd62306a2011-11-10 06:34:14 +00002469
2470 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002471 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002472 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002473 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002474}
2475
Richard Smith1b78b3d2012-01-25 22:15:11 +00002476/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002477static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002478 LValue &LVal,
2479 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002480 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002481 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002482 return false;
2483 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002484}
2485
Richard Smithd62306a2011-11-10 06:34:14 +00002486/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002487static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2488 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002489 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2490 // extension.
2491 if (Type->isVoidType() || Type->isFunctionType()) {
2492 Size = CharUnits::One();
2493 return true;
2494 }
2495
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002496 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002497 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002498 return false;
2499 }
2500
Richard Smithd62306a2011-11-10 06:34:14 +00002501 if (!Type->isConstantSizeType()) {
2502 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002503 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002504 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002505 return false;
2506 }
2507
2508 Size = Info.Ctx.getTypeSizeInChars(Type);
2509 return true;
2510}
2511
2512/// Update a pointer value to model pointer arithmetic.
2513/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002514/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002515/// \param LVal - The pointer value to be updated.
2516/// \param EltTy - The pointee type represented by LVal.
2517/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002518static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2519 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002520 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002521 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002522 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002523 return false;
2524
Yaxun Liu402804b2016-12-15 08:09:08 +00002525 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002526 return true;
2527}
2528
Richard Smithd6cc1982017-01-31 02:23:02 +00002529static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2530 LValue &LVal, QualType EltTy,
2531 int64_t Adjustment) {
2532 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2533 APSInt::get(Adjustment));
2534}
2535
Richard Smith66c96992012-02-18 22:04:06 +00002536/// Update an lvalue to refer to a component of a complex number.
2537/// \param Info - Information about the ongoing evaluation.
2538/// \param LVal - The lvalue to be updated.
2539/// \param EltTy - The complex number's component type.
2540/// \param Imag - False for the real component, true for the imaginary.
2541static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2542 LValue &LVal, QualType EltTy,
2543 bool Imag) {
2544 if (Imag) {
2545 CharUnits SizeOfComponent;
2546 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2547 return false;
2548 LVal.Offset += SizeOfComponent;
2549 }
2550 LVal.addComplex(Info, E, EltTy, Imag);
2551 return true;
2552}
2553
Faisal Vali051e3a22017-02-16 04:12:21 +00002554static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2555 QualType Type, const LValue &LVal,
2556 APValue &RVal);
2557
Richard Smith27908702011-10-24 17:54:18 +00002558/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002559///
2560/// \param Info Information about the ongoing evaluation.
2561/// \param E An expression to be used when printing diagnostics.
2562/// \param VD The variable whose initializer should be obtained.
2563/// \param Frame The frame in which the variable was created. Must be null
2564/// if this variable is not local to the evaluation.
2565/// \param Result Filled in with a pointer to the value of the variable.
2566static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2567 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002568 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002569
Richard Smith254a73d2011-10-28 22:34:42 +00002570 // If this is a parameter to an active constexpr function call, perform
2571 // argument substitution.
2572 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002573 // Assume arguments of a potential constant expression are unknown
2574 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002575 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002576 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002577 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002578 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002579 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002580 }
Richard Smith3229b742013-05-05 21:17:10 +00002581 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002582 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002583 }
Richard Smith27908702011-10-24 17:54:18 +00002584
Richard Smithd9f663b2013-04-22 15:31:51 +00002585 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002586 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002587 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2588 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002589 if (!Result) {
2590 // Assume variables referenced within a lambda's call operator that were
2591 // not declared within the call operator are captures and during checking
2592 // of a potential constant expression, assume they are unknown constant
2593 // expressions.
2594 assert(isLambdaCallOperator(Frame->Callee) &&
2595 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2596 "missing value for local variable");
2597 if (Info.checkingPotentialConstantExpression())
2598 return false;
2599 // FIXME: implement capture evaluation during constant expr evaluation.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002600 Info.FFDiag(E->getBeginLoc(),
2601 diag::note_unimplemented_constexpr_lambda_feature_ast)
Faisal Valia734ab92016-03-26 16:11:37 +00002602 << "captures not currently allowed";
2603 return false;
2604 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002605 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002606 }
2607
Richard Smithd0b4dd62011-12-19 06:19:21 +00002608 // Dig out the initializer, and use the declaration which it's attached to.
2609 const Expr *Init = VD->getAnyInitializer(VD);
2610 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002611 // If we're checking a potential constant expression, the variable could be
2612 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002613 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002614 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002615 return false;
2616 }
2617
Richard Smithd62306a2011-11-10 06:34:14 +00002618 // If we're currently evaluating the initializer of this declaration, use that
2619 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002620 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002621 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002622 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002623 }
2624
Richard Smithcecf1842011-11-01 21:06:14 +00002625 // Never evaluate the initializer of a weak variable. We can't be sure that
2626 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002627 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002628 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002629 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002630 }
Richard Smithcecf1842011-11-01 21:06:14 +00002631
Richard Smithd0b4dd62011-12-19 06:19:21 +00002632 // Check that we can fold the initializer. In C++, we will have already done
2633 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002634 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002635 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002636 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002637 Notes.size() + 1) << VD;
2638 Info.Note(VD->getLocation(), diag::note_declared_at);
2639 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002640 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002641 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002642 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002643 Notes.size() + 1) << VD;
2644 Info.Note(VD->getLocation(), diag::note_declared_at);
2645 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002646 }
Richard Smith27908702011-10-24 17:54:18 +00002647
Richard Smith3229b742013-05-05 21:17:10 +00002648 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002649 return true;
Richard Smith27908702011-10-24 17:54:18 +00002650}
2651
Richard Smith11562c52011-10-28 17:51:58 +00002652static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002653 Qualifiers Quals = T.getQualifiers();
2654 return Quals.hasConst() && !Quals.hasVolatile();
2655}
2656
Richard Smithe97cbd72011-11-11 04:05:33 +00002657/// Get the base index of the given base class within an APValue representing
2658/// the given derived class.
2659static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2660 const CXXRecordDecl *Base) {
2661 Base = Base->getCanonicalDecl();
2662 unsigned Index = 0;
2663 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2664 E = Derived->bases_end(); I != E; ++I, ++Index) {
2665 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2666 return Index;
2667 }
2668
2669 llvm_unreachable("base class missing from derived class's bases list");
2670}
2671
Richard Smith3da88fa2013-04-26 14:36:30 +00002672/// Extract the value of a character from a string literal.
2673static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2674 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002675 // FIXME: Support MakeStringConstant
2676 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2677 std::string Str;
2678 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2679 assert(Index <= Str.size() && "Index too large");
2680 return APSInt::getUnsigned(Str.c_str()[Index]);
2681 }
2682
Alexey Bataevec474782014-10-09 08:45:04 +00002683 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2684 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002685 const StringLiteral *S = cast<StringLiteral>(Lit);
2686 const ConstantArrayType *CAT =
2687 Info.Ctx.getAsConstantArrayType(S->getType());
2688 assert(CAT && "string literal isn't an array");
2689 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002690 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002691
2692 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002693 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002694 if (Index < S->getLength())
2695 Value = S->getCodeUnit(Index);
2696 return Value;
2697}
2698
Richard Smith3da88fa2013-04-26 14:36:30 +00002699// Expand a string literal into an array of characters.
Eli Friedman3bf72d72019-02-08 21:18:46 +00002700//
2701// FIXME: This is inefficient; we should probably introduce something similar
2702// to the LLVM ConstantDataArray to make this cheaper.
2703static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
Richard Smith3da88fa2013-04-26 14:36:30 +00002704 APValue &Result) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002705 const ConstantArrayType *CAT =
2706 Info.Ctx.getAsConstantArrayType(S->getType());
2707 assert(CAT && "string literal isn't an array");
2708 QualType CharType = CAT->getElementType();
2709 assert(CharType->isIntegerType() && "unexpected character type");
2710
2711 unsigned Elts = CAT->getSize().getZExtValue();
2712 Result = APValue(APValue::UninitArray(),
2713 std::min(S->getLength(), Elts), Elts);
2714 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2715 CharType->isUnsignedIntegerType());
2716 if (Result.hasArrayFiller())
2717 Result.getArrayFiller() = APValue(Value);
2718 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2719 Value = S->getCodeUnit(I);
2720 Result.getArrayInitializedElt(I) = APValue(Value);
2721 }
2722}
2723
2724// Expand an array so that it has more than Index filled elements.
2725static void expandArray(APValue &Array, unsigned Index) {
2726 unsigned Size = Array.getArraySize();
2727 assert(Index < Size);
2728
2729 // Always at least double the number of elements for which we store a value.
2730 unsigned OldElts = Array.getArrayInitializedElts();
2731 unsigned NewElts = std::max(Index+1, OldElts * 2);
2732 NewElts = std::min(Size, std::max(NewElts, 8u));
2733
2734 // Copy the data across.
2735 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2736 for (unsigned I = 0; I != OldElts; ++I)
2737 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2738 for (unsigned I = OldElts; I != NewElts; ++I)
2739 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2740 if (NewValue.hasArrayFiller())
2741 NewValue.getArrayFiller() = Array.getArrayFiller();
2742 Array.swap(NewValue);
2743}
2744
Richard Smithb01fe402014-09-16 01:24:02 +00002745/// Determine whether a type would actually be read by an lvalue-to-rvalue
2746/// conversion. If it's of class type, we may assume that the copy operation
2747/// is trivial. Note that this is never true for a union type with fields
2748/// (because the copy always "reads" the active member) and always true for
2749/// a non-class type.
2750static bool isReadByLvalueToRvalueConversion(QualType T) {
2751 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2752 if (!RD || (RD->isUnion() && !RD->field_empty()))
2753 return true;
2754 if (RD->isEmpty())
2755 return false;
2756
2757 for (auto *Field : RD->fields())
2758 if (isReadByLvalueToRvalueConversion(Field->getType()))
2759 return true;
2760
2761 for (auto &BaseSpec : RD->bases())
2762 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2763 return true;
2764
2765 return false;
2766}
2767
2768/// Diagnose an attempt to read from any unreadable field within the specified
2769/// type, which might be a class type.
2770static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2771 QualType T) {
2772 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2773 if (!RD)
2774 return false;
2775
2776 if (!RD->hasMutableFields())
2777 return false;
2778
2779 for (auto *Field : RD->fields()) {
2780 // If we're actually going to read this field in some way, then it can't
2781 // be mutable. If we're in a union, then assigning to a mutable field
2782 // (even an empty one) can change the active member, so that's not OK.
2783 // FIXME: Add core issue number for the union case.
2784 if (Field->isMutable() &&
2785 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002786 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002787 Info.Note(Field->getLocation(), diag::note_declared_at);
2788 return true;
2789 }
2790
2791 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2792 return true;
2793 }
2794
2795 for (auto &BaseSpec : RD->bases())
2796 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2797 return true;
2798
2799 // All mutable fields were empty, and thus not actually read.
2800 return false;
2801}
2802
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002803namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002804/// A handle to a complete object (an object that is not a subobject of
2805/// another object).
2806struct CompleteObject {
2807 /// The value of the complete object.
2808 APValue *Value;
2809 /// The type of the complete object.
2810 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002811 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002812
Craig Topper36250ad2014-05-12 05:36:57 +00002813 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002814 CompleteObject(APValue *Value, QualType Type,
2815 bool LifetimeStartedInEvaluation)
2816 : Value(Value), Type(Type),
2817 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002818 assert(Value && "missing value for complete object");
2819 }
2820
Aaron Ballman67347662015-02-15 22:00:28 +00002821 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002822};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002823} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002824
Richard Smith3da88fa2013-04-26 14:36:30 +00002825/// Find the designated sub-object of an rvalue.
2826template<typename SubobjectHandler>
2827typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002828findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002829 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002830 if (Sub.Invalid)
2831 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002832 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002833 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002834 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002835 Info.FFDiag(E, Sub.isOnePastTheEnd()
2836 ? diag::note_constexpr_access_past_end
2837 : diag::note_constexpr_access_unsized_array)
2838 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002839 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002840 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002841 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002842 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002843
Richard Smith3229b742013-05-05 21:17:10 +00002844 APValue *O = Obj.Value;
2845 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002846 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002847 const bool MayReadMutableMembers =
2848 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002849
Richard Smithd62306a2011-11-10 06:34:14 +00002850 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002851 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2852 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002853 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002854 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002855 return handler.failed();
2856 }
2857
Richard Smith49ca8aa2013-08-06 07:09:20 +00002858 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002859 // If we are reading an object of class type, there may still be more
2860 // things we need to check: if there are any mutable subobjects, we
2861 // cannot perform this read. (This only happens when performing a trivial
2862 // copy or assignment.)
2863 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002864 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002865 return handler.failed();
2866
Richard Smith49ca8aa2013-08-06 07:09:20 +00002867 if (!handler.found(*O, ObjType))
2868 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002869
Richard Smith49ca8aa2013-08-06 07:09:20 +00002870 // If we modified a bit-field, truncate it to the right width.
2871 if (handler.AccessKind != AK_Read &&
2872 LastField && LastField->isBitField() &&
2873 !truncateBitfieldValue(Info, E, *O, LastField))
2874 return false;
2875
2876 return true;
2877 }
2878
Craig Topper36250ad2014-05-12 05:36:57 +00002879 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002880 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002881 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002882 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002883 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002884 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002885 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002886 // Note, it should not be possible to form a pointer with a valid
2887 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002888 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002889 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002890 << handler.AccessKind;
2891 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002892 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002893 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002894 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002895
2896 ObjType = CAT->getElementType();
2897
Richard Smith3da88fa2013-04-26 14:36:30 +00002898 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002899 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002900 else if (handler.AccessKind != AK_Read) {
2901 expandArray(*O, Index);
2902 O = &O->getArrayInitializedElt(Index);
2903 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002904 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002905 } else if (ObjType->isAnyComplexType()) {
2906 // Next subobject is a complex number.
2907 uint64_t Index = Sub.Entries[I].ArrayIndex;
2908 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002909 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002910 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002911 << handler.AccessKind;
2912 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002913 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002914 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002915 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002916
2917 bool WasConstQualified = ObjType.isConstQualified();
2918 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2919 if (WasConstQualified)
2920 ObjType.addConst();
2921
Richard Smith66c96992012-02-18 22:04:06 +00002922 assert(I == N - 1 && "extracting subobject of scalar?");
2923 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002924 return handler.found(Index ? O->getComplexIntImag()
2925 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002926 } else {
2927 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002928 return handler.found(Index ? O->getComplexFloatImag()
2929 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002930 }
Richard Smithd62306a2011-11-10 06:34:14 +00002931 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002932 // In C++14 onwards, it is permitted to read a mutable member whose
2933 // lifetime began within the evaluation.
2934 // FIXME: Should we also allow this in C++11?
2935 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2936 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002937 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002938 << Field;
2939 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002940 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002941 }
2942
Richard Smithd62306a2011-11-10 06:34:14 +00002943 // Next subobject is a class, struct or union field.
2944 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2945 if (RD->isUnion()) {
2946 const FieldDecl *UnionField = O->getUnionField();
2947 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002948 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002949 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002950 << handler.AccessKind << Field << !UnionField << UnionField;
2951 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002952 }
Richard Smithd62306a2011-11-10 06:34:14 +00002953 O = &O->getUnionValue();
2954 } else
2955 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002956
2957 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002958 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002959 if (WasConstQualified && !Field->isMutable())
2960 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002961
2962 if (ObjType.isVolatileQualified()) {
2963 if (Info.getLangOpts().CPlusPlus) {
2964 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002965 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002966 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002967 Info.Note(Field->getLocation(), diag::note_declared_at);
2968 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002969 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002970 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002971 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002972 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002973
2974 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002975 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002976 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002977 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2978 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2979 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002980
2981 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002982 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002983 if (WasConstQualified)
2984 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002985 }
2986 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002987}
2988
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002989namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002990struct ExtractSubobjectHandler {
2991 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002992 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002993
2994 static const AccessKinds AccessKind = AK_Read;
2995
2996 typedef bool result_type;
2997 bool failed() { return false; }
2998 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002999 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00003000 return true;
3001 }
3002 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003003 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003004 return true;
3005 }
3006 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00003007 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00003008 return true;
3009 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003010};
Richard Smith3229b742013-05-05 21:17:10 +00003011} // end anonymous namespace
3012
Richard Smith3da88fa2013-04-26 14:36:30 +00003013const AccessKinds ExtractSubobjectHandler::AccessKind;
3014
3015/// Extract the designated sub-object of an rvalue.
3016static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003017 const CompleteObject &Obj,
3018 const SubobjectDesignator &Sub,
3019 APValue &Result) {
3020 ExtractSubobjectHandler Handler = { Info, Result };
3021 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00003022}
3023
Richard Smith3229b742013-05-05 21:17:10 +00003024namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00003025struct ModifySubobjectHandler {
3026 EvalInfo &Info;
3027 APValue &NewVal;
3028 const Expr *E;
3029
3030 typedef bool result_type;
3031 static const AccessKinds AccessKind = AK_Assign;
3032
3033 bool checkConst(QualType QT) {
3034 // Assigning to a const object has undefined behavior.
3035 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003036 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00003037 return false;
3038 }
3039 return true;
3040 }
3041
3042 bool failed() { return false; }
3043 bool found(APValue &Subobj, QualType SubobjType) {
3044 if (!checkConst(SubobjType))
3045 return false;
3046 // We've been given ownership of NewVal, so just swap it in.
3047 Subobj.swap(NewVal);
3048 return true;
3049 }
3050 bool found(APSInt &Value, QualType SubobjType) {
3051 if (!checkConst(SubobjType))
3052 return false;
3053 if (!NewVal.isInt()) {
3054 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00003055 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003056 return false;
3057 }
3058 Value = NewVal.getInt();
3059 return true;
3060 }
3061 bool found(APFloat &Value, QualType SubobjType) {
3062 if (!checkConst(SubobjType))
3063 return false;
3064 Value = NewVal.getFloat();
3065 return true;
3066 }
Richard Smith3da88fa2013-04-26 14:36:30 +00003067};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00003068} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00003069
Richard Smith3229b742013-05-05 21:17:10 +00003070const AccessKinds ModifySubobjectHandler::AccessKind;
3071
Richard Smith3da88fa2013-04-26 14:36:30 +00003072/// Update the designated sub-object of an rvalue to the given value.
3073static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003074 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003075 const SubobjectDesignator &Sub,
3076 APValue &NewVal) {
3077 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003078 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003079}
3080
Richard Smith84f6dcf2012-02-02 01:16:57 +00003081/// Find the position where two subobject designators diverge, or equivalently
3082/// the length of the common initial subsequence.
3083static unsigned FindDesignatorMismatch(QualType ObjType,
3084 const SubobjectDesignator &A,
3085 const SubobjectDesignator &B,
3086 bool &WasArrayIndex) {
3087 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3088 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003089 if (!ObjType.isNull() &&
3090 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003091 // Next subobject is an array element.
3092 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3093 WasArrayIndex = true;
3094 return I;
3095 }
Richard Smith66c96992012-02-18 22:04:06 +00003096 if (ObjType->isAnyComplexType())
3097 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3098 else
3099 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003100 } else {
3101 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3102 WasArrayIndex = false;
3103 return I;
3104 }
3105 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3106 // Next subobject is a field.
3107 ObjType = FD->getType();
3108 else
3109 // Next subobject is a base class.
3110 ObjType = QualType();
3111 }
3112 }
3113 WasArrayIndex = false;
3114 return I;
3115}
3116
3117/// Determine whether the given subobject designators refer to elements of the
3118/// same array object.
3119static bool AreElementsOfSameArray(QualType ObjType,
3120 const SubobjectDesignator &A,
3121 const SubobjectDesignator &B) {
3122 if (A.Entries.size() != B.Entries.size())
3123 return false;
3124
George Burgess IVa51c4072015-10-16 01:49:01 +00003125 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003126 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3127 // A is a subobject of the array element.
3128 return false;
3129
3130 // If A (and B) designates an array element, the last entry will be the array
3131 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3132 // of length 1' case, and the entire path must match.
3133 bool WasArrayIndex;
3134 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3135 return CommonLength >= A.Entries.size() - IsArray;
3136}
3137
Richard Smith3229b742013-05-05 21:17:10 +00003138/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003139static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3140 AccessKinds AK, const LValue &LVal,
3141 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003142 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003143 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003144 return CompleteObject();
3145 }
3146
Craig Topper36250ad2014-05-12 05:36:57 +00003147 CallStackFrame *Frame = nullptr;
Richard Smith37be3362019-05-04 04:00:45 +00003148 unsigned Depth = 0;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003149 if (LVal.getLValueCallIndex()) {
Richard Smith37be3362019-05-04 04:00:45 +00003150 std::tie(Frame, Depth) =
3151 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003152 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003153 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003154 << AK << LVal.Base.is<const ValueDecl*>();
3155 NoteLValueLocation(Info, LVal.Base);
3156 return CompleteObject();
3157 }
Richard Smith3229b742013-05-05 21:17:10 +00003158 }
3159
3160 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3161 // is not a constant expression (even if the object is non-volatile). We also
3162 // apply this rule to C++98, in order to conform to the expected 'volatile'
3163 // semantics.
3164 if (LValType.isVolatileQualified()) {
3165 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003166 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003167 << AK << LValType;
3168 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003169 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003170 return CompleteObject();
3171 }
3172
3173 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003174 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003175 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003176 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003177
3178 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3179 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3180 // In C++11, constexpr, non-volatile variables initialized with constant
3181 // expressions are constant expressions too. Inside constexpr functions,
3182 // parameters are constant expressions even if they're non-const.
3183 // In C++1y, objects local to a constant expression (those with a Frame) are
3184 // both readable and writable inside constant expressions.
3185 // In C, such things can also be folded, although they are not ICEs.
3186 const VarDecl *VD = dyn_cast<VarDecl>(D);
3187 if (VD) {
3188 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3189 VD = VDef;
3190 }
3191 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003192 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003193 return CompleteObject();
3194 }
3195
3196 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003197 if (BaseType.isVolatileQualified()) {
3198 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003199 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003200 << AK << 1 << VD;
3201 Info.Note(VD->getLocation(), diag::note_declared_at);
3202 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003203 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003204 }
3205 return CompleteObject();
3206 }
3207
3208 // Unless we're looking at a local variable or argument in a constexpr call,
3209 // the variable we're reading must be const.
3210 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003211 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003212 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3213 // OK, we can read and modify an object if we're in the process of
3214 // evaluating its initializer, because its lifetime began in this
3215 // evaluation.
3216 } else if (AK != AK_Read) {
3217 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003218 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003219 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003220 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003221 // OK, we can read this variable.
3222 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003223 // In OpenCL if a variable is in constant address space it is a const value.
3224 if (!(BaseType.isConstQualified() ||
3225 (Info.getLangOpts().OpenCL &&
3226 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003227 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003228 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003229 Info.Note(VD->getLocation(), diag::note_declared_at);
3230 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003231 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003232 }
3233 return CompleteObject();
3234 }
3235 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3236 // We support folding of const floating-point types, in order to make
3237 // static const data members of such types (supported as an extension)
3238 // more useful.
3239 if (Info.getLangOpts().CPlusPlus11) {
3240 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3241 Info.Note(VD->getLocation(), diag::note_declared_at);
3242 } else {
3243 Info.CCEDiag(E);
3244 }
George Burgess IVb5316982016-12-27 05:33:20 +00003245 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3246 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3247 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003248 } else {
3249 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003250 if (Info.checkingPotentialConstantExpression() &&
3251 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3252 // The definition of this variable could be constexpr. We can't
3253 // access it right now, but may be able to in future.
3254 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003255 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003256 Info.Note(VD->getLocation(), diag::note_declared_at);
3257 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003258 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003259 }
3260 return CompleteObject();
3261 }
3262 }
3263
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003264 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003265 return CompleteObject();
3266 } else {
3267 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3268
3269 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003270 if (const MaterializeTemporaryExpr *MTE =
3271 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3272 assert(MTE->getStorageDuration() == SD_Static &&
3273 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003274
Richard Smithe6c01442013-06-05 00:46:14 +00003275 // Per C++1y [expr.const]p2:
3276 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3277 // - a [...] glvalue of integral or enumeration type that refers to
3278 // a non-volatile const object [...]
3279 // [...]
3280 // - a [...] glvalue of literal type that refers to a non-volatile
3281 // object whose lifetime began within the evaluation of e.
3282 //
3283 // C++11 misses the 'began within the evaluation of e' check and
3284 // instead allows all temporaries, including things like:
3285 // int &&r = 1;
3286 // int x = ++r;
3287 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003288 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003289 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3290 const ValueDecl *ED = MTE->getExtendingDecl();
3291 if (!(BaseType.isConstQualified() &&
3292 BaseType->isIntegralOrEnumerationType()) &&
3293 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003294 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003295 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3296 return CompleteObject();
3297 }
3298
3299 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3300 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003301 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003302 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003303 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003304 return CompleteObject();
3305 }
3306 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003307 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003308 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003309 }
Richard Smith3229b742013-05-05 21:17:10 +00003310
3311 // Volatile temporary objects cannot be accessed in constant expressions.
3312 if (BaseType.isVolatileQualified()) {
3313 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003314 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003315 << AK << 0;
3316 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3317 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003318 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003319 }
3320 return CompleteObject();
3321 }
3322 }
3323
Richard Smith7525ff62013-05-09 07:14:00 +00003324 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003325 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003326 // object under construction.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003327 if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3328 LVal.getLValueCallIndex(),
3329 LVal.getLValueVersion())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003330 BaseType = Info.Ctx.getCanonicalType(BaseType);
3331 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003332 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003333 }
3334
Richard Smith9defb7d2018-02-21 03:38:30 +00003335 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003336 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003337 //
3338 // FIXME: Not all local state is mutable. Allow local constant subobjects
3339 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003340 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3341 Info.EvalStatus.HasSideEffects) ||
Richard Smith37be3362019-05-04 04:00:45 +00003342 (AK != AK_Read && Depth < Info.SpeculativeEvaluationDepth))
Richard Smith3229b742013-05-05 21:17:10 +00003343 return CompleteObject();
3344
Richard Smith9defb7d2018-02-21 03:38:30 +00003345 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003346}
3347
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003348/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
Richard Smith243ef902013-05-05 23:31:59 +00003349/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3350/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003351///
3352/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003353/// \param Conv - The expression for which we are performing the conversion.
3354/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003355/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3356/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003357/// \param LVal - The glvalue on which we are attempting to perform this action.
3358/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003359static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003360 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003361 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003362 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003363 return false;
3364
Richard Smith3229b742013-05-05 21:17:10 +00003365 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003366 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003367 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003368 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3369 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3370 // initializer until now for such expressions. Such an expression can't be
3371 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003372 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003373 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003374 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003375 }
Richard Smith3229b742013-05-05 21:17:10 +00003376 APValue Lit;
3377 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3378 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003379 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003380 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003381 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00003382 // Special-case character extraction so we don't have to construct an
3383 // APValue for the whole string.
Eli Friedman041adb02019-02-09 02:22:17 +00003384 assert(LVal.Designator.Entries.size() <= 1 &&
Eli Friedman3bf72d72019-02-08 21:18:46 +00003385 "Can only read characters from string literals");
Eli Friedman041adb02019-02-09 02:22:17 +00003386 if (LVal.Designator.Entries.empty()) {
3387 // Fail for now for LValue to RValue conversion of an array.
3388 // (This shouldn't show up in C/C++, but it could be triggered by a
3389 // weird EvaluateAsRValue call from a tool.)
3390 Info.FFDiag(Conv);
3391 return false;
3392 }
Eli Friedman3bf72d72019-02-08 21:18:46 +00003393 if (LVal.Designator.isOnePastTheEnd()) {
3394 if (Info.getLangOpts().CPlusPlus11)
3395 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3396 else
3397 Info.FFDiag(Conv);
3398 return false;
3399 }
3400 uint64_t CharIndex = LVal.Designator.Entries[0].ArrayIndex;
3401 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3402 return true;
Richard Smith96e0c102011-11-04 02:25:55 +00003403 }
Richard Smith11562c52011-10-28 17:51:58 +00003404 }
3405
Richard Smith3229b742013-05-05 21:17:10 +00003406 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3407 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003408}
3409
3410/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003411static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003412 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003413 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003414 return false;
3415
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003416 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003417 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003418 return false;
3419 }
3420
Richard Smith3229b742013-05-05 21:17:10 +00003421 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003422 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3423}
3424
3425namespace {
3426struct CompoundAssignSubobjectHandler {
3427 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003428 const Expr *E;
3429 QualType PromotedLHSType;
3430 BinaryOperatorKind Opcode;
3431 const APValue &RHS;
3432
3433 static const AccessKinds AccessKind = AK_Assign;
3434
3435 typedef bool result_type;
3436
3437 bool checkConst(QualType QT) {
3438 // Assigning to a const object has undefined behavior.
3439 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003440 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003441 return false;
3442 }
3443 return true;
3444 }
3445
3446 bool failed() { return false; }
3447 bool found(APValue &Subobj, QualType SubobjType) {
3448 switch (Subobj.getKind()) {
3449 case APValue::Int:
3450 return found(Subobj.getInt(), SubobjType);
3451 case APValue::Float:
3452 return found(Subobj.getFloat(), SubobjType);
3453 case APValue::ComplexInt:
3454 case APValue::ComplexFloat:
3455 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003456 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003457 return false;
3458 case APValue::LValue:
3459 return foundPointer(Subobj, SubobjType);
3460 default:
3461 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003462 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003463 return false;
3464 }
3465 }
3466 bool found(APSInt &Value, QualType SubobjType) {
3467 if (!checkConst(SubobjType))
3468 return false;
3469
Tan S. B.9f935e82018-12-18 07:38:06 +00003470 if (!SubobjType->isIntegerType()) {
Richard Smith43e77732013-05-07 04:50:00 +00003471 // We don't support compound assignment on integer-cast-to-pointer
3472 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003473 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003474 return false;
3475 }
3476
Tan S. B.9f935e82018-12-18 07:38:06 +00003477 if (RHS.isInt()) {
3478 APSInt LHS =
3479 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3480 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3481 return false;
3482 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3483 return true;
3484 } else if (RHS.isFloat()) {
3485 APFloat FValue(0.0);
3486 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3487 FValue) &&
3488 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3489 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3490 Value);
3491 }
3492
3493 Info.FFDiag(E);
3494 return false;
Richard Smith43e77732013-05-07 04:50:00 +00003495 }
3496 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003497 return checkConst(SubobjType) &&
3498 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3499 Value) &&
3500 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3501 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003502 }
3503 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3504 if (!checkConst(SubobjType))
3505 return false;
3506
3507 QualType PointeeType;
3508 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3509 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003510
3511 if (PointeeType.isNull() || !RHS.isInt() ||
3512 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003513 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003514 return false;
3515 }
3516
Richard Smithd6cc1982017-01-31 02:23:02 +00003517 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003518 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003519 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003520
3521 LValue LVal;
3522 LVal.setFrom(Info.Ctx, Subobj);
3523 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3524 return false;
3525 LVal.moveInto(Subobj);
3526 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003527 }
Richard Smith43e77732013-05-07 04:50:00 +00003528};
3529} // end anonymous namespace
3530
3531const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3532
3533/// Perform a compound assignment of LVal <op>= RVal.
3534static bool handleCompoundAssignment(
3535 EvalInfo &Info, const Expr *E,
3536 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3537 BinaryOperatorKind Opcode, const APValue &RVal) {
3538 if (LVal.Designator.Invalid)
3539 return false;
3540
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003541 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003542 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003543 return false;
3544 }
3545
3546 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3547 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3548 RVal };
3549 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3550}
3551
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003552namespace {
3553struct IncDecSubobjectHandler {
3554 EvalInfo &Info;
3555 const UnaryOperator *E;
3556 AccessKinds AccessKind;
3557 APValue *Old;
3558
Richard Smith243ef902013-05-05 23:31:59 +00003559 typedef bool result_type;
3560
3561 bool checkConst(QualType QT) {
3562 // Assigning to a const object has undefined behavior.
3563 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003564 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003565 return false;
3566 }
3567 return true;
3568 }
3569
3570 bool failed() { return false; }
3571 bool found(APValue &Subobj, QualType SubobjType) {
3572 // Stash the old value. Also clear Old, so we don't clobber it later
3573 // if we're post-incrementing a complex.
3574 if (Old) {
3575 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003576 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003577 }
3578
3579 switch (Subobj.getKind()) {
3580 case APValue::Int:
3581 return found(Subobj.getInt(), SubobjType);
3582 case APValue::Float:
3583 return found(Subobj.getFloat(), SubobjType);
3584 case APValue::ComplexInt:
3585 return found(Subobj.getComplexIntReal(),
3586 SubobjType->castAs<ComplexType>()->getElementType()
3587 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3588 case APValue::ComplexFloat:
3589 return found(Subobj.getComplexFloatReal(),
3590 SubobjType->castAs<ComplexType>()->getElementType()
3591 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3592 case APValue::LValue:
3593 return foundPointer(Subobj, SubobjType);
3594 default:
3595 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003596 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003597 return false;
3598 }
3599 }
3600 bool found(APSInt &Value, QualType SubobjType) {
3601 if (!checkConst(SubobjType))
3602 return false;
3603
3604 if (!SubobjType->isIntegerType()) {
3605 // We don't support increment / decrement on integer-cast-to-pointer
3606 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003607 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003608 return false;
3609 }
3610
3611 if (Old) *Old = APValue(Value);
3612
3613 // bool arithmetic promotes to int, and the conversion back to bool
3614 // doesn't reduce mod 2^n, so special-case it.
3615 if (SubobjType->isBooleanType()) {
3616 if (AccessKind == AK_Increment)
3617 Value = 1;
3618 else
3619 Value = !Value;
3620 return true;
3621 }
3622
3623 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003624 if (AccessKind == AK_Increment) {
3625 ++Value;
3626
3627 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3628 APSInt ActualValue(Value, /*IsUnsigned*/true);
3629 return HandleOverflow(Info, E, ActualValue, SubobjType);
3630 }
3631 } else {
3632 --Value;
3633
3634 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3635 unsigned BitWidth = Value.getBitWidth();
3636 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3637 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003638 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003639 }
3640 }
3641 return true;
3642 }
3643 bool found(APFloat &Value, QualType SubobjType) {
3644 if (!checkConst(SubobjType))
3645 return false;
3646
3647 if (Old) *Old = APValue(Value);
3648
3649 APFloat One(Value.getSemantics(), 1);
3650 if (AccessKind == AK_Increment)
3651 Value.add(One, APFloat::rmNearestTiesToEven);
3652 else
3653 Value.subtract(One, APFloat::rmNearestTiesToEven);
3654 return true;
3655 }
3656 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3657 if (!checkConst(SubobjType))
3658 return false;
3659
3660 QualType PointeeType;
3661 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3662 PointeeType = PT->getPointeeType();
3663 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003664 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003665 return false;
3666 }
3667
3668 LValue LVal;
3669 LVal.setFrom(Info.Ctx, Subobj);
3670 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3671 AccessKind == AK_Increment ? 1 : -1))
3672 return false;
3673 LVal.moveInto(Subobj);
3674 return true;
3675 }
Richard Smith243ef902013-05-05 23:31:59 +00003676};
3677} // end anonymous namespace
3678
3679/// Perform an increment or decrement on LVal.
3680static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3681 QualType LValType, bool IsIncrement, APValue *Old) {
3682 if (LVal.Designator.Invalid)
3683 return false;
3684
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003685 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003686 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003687 return false;
3688 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003689
3690 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3691 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3692 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3693 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3694}
3695
Richard Smithe97cbd72011-11-11 04:05:33 +00003696/// Build an lvalue for the object argument of a member function call.
3697static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3698 LValue &This) {
3699 if (Object->getType()->isPointerType())
3700 return EvaluatePointer(Object, This, Info);
3701
3702 if (Object->isGLValue())
3703 return EvaluateLValue(Object, This, Info);
3704
Richard Smithd9f663b2013-04-22 15:31:51 +00003705 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003706 return EvaluateTemporary(Object, This, Info);
3707
Faisal Valie690b7a2016-07-02 22:34:24 +00003708 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003709 return false;
3710}
3711
3712/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3713/// lvalue referring to the result.
3714///
3715/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003716/// \param LV - An lvalue referring to the base of the member pointer.
3717/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003718/// \param IncludeMember - Specifies whether the member itself is included in
3719/// the resulting LValue subobject designator. This is not possible when
3720/// creating a bound member function.
3721/// \return The field or method declaration to which the member pointer refers,
3722/// or 0 if evaluation fails.
3723static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003724 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003725 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003726 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003727 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003728 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003729 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003730 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003731
3732 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3733 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003734 if (!MemPtr.getDecl()) {
3735 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003736 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003737 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003738 }
Richard Smith253c2a32012-01-27 01:14:48 +00003739
Richard Smith027bf112011-11-17 22:56:20 +00003740 if (MemPtr.isDerivedMember()) {
3741 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003742 // The end of the derived-to-base path for the base object must match the
3743 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003744 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003745 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003746 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003747 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003748 }
Richard Smith027bf112011-11-17 22:56:20 +00003749 unsigned PathLengthToMember =
3750 LV.Designator.Entries.size() - MemPtr.Path.size();
3751 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3752 const CXXRecordDecl *LVDecl = getAsBaseClass(
3753 LV.Designator.Entries[PathLengthToMember + I]);
3754 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003755 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003756 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003757 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003758 }
Richard Smith027bf112011-11-17 22:56:20 +00003759 }
3760
3761 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003762 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003763 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003764 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003765 } else if (!MemPtr.Path.empty()) {
3766 // Extend the LValue path with the member pointer's path.
3767 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3768 MemPtr.Path.size() + IncludeMember);
3769
3770 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003771 if (const PointerType *PT = LVType->getAs<PointerType>())
3772 LVType = PT->getPointeeType();
3773 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3774 assert(RD && "member pointer access on non-class-type expression");
3775 // The first class in the path is that of the lvalue.
3776 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3777 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003778 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003779 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003780 RD = Base;
3781 }
3782 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003783 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3784 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003785 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003786 }
3787
3788 // Add the member. Note that we cannot build bound member functions here.
3789 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003790 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003791 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003792 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003793 } else if (const IndirectFieldDecl *IFD =
3794 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003795 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003796 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003797 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003798 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003799 }
Richard Smith027bf112011-11-17 22:56:20 +00003800 }
3801
3802 return MemPtr.getDecl();
3803}
3804
Richard Smith84401042013-06-03 05:03:02 +00003805static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3806 const BinaryOperator *BO,
3807 LValue &LV,
3808 bool IncludeMember = true) {
3809 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3810
3811 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003812 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003813 MemberPtr MemPtr;
3814 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3815 }
Craig Topper36250ad2014-05-12 05:36:57 +00003816 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003817 }
3818
3819 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3820 BO->getRHS(), IncludeMember);
3821}
3822
Richard Smith027bf112011-11-17 22:56:20 +00003823/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3824/// the provided lvalue, which currently refers to the base object.
3825static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3826 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003827 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003828 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003829 return false;
3830
Richard Smitha8105bc2012-01-06 16:39:00 +00003831 QualType TargetQT = E->getType();
3832 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3833 TargetQT = PT->getPointeeType();
3834
3835 // Check this cast lands within the final derived-to-base subobject path.
3836 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003837 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003838 << D.MostDerivedType << TargetQT;
3839 return false;
3840 }
3841
Richard Smith027bf112011-11-17 22:56:20 +00003842 // Check the type of the final cast. We don't need to check the path,
3843 // since a cast can only be formed if the path is unique.
3844 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003845 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3846 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003847 if (NewEntriesSize == D.MostDerivedPathLength)
3848 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3849 else
Richard Smith027bf112011-11-17 22:56:20 +00003850 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003851 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003852 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003853 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003854 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003855 }
Richard Smith027bf112011-11-17 22:56:20 +00003856
3857 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003858 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003859}
3860
Mike Stump876387b2009-10-27 22:09:17 +00003861namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003862enum EvalStmtResult {
3863 /// Evaluation failed.
3864 ESR_Failed,
3865 /// Hit a 'return' statement.
3866 ESR_Returned,
3867 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003868 ESR_Succeeded,
3869 /// Hit a 'continue' statement.
3870 ESR_Continue,
3871 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003872 ESR_Break,
3873 /// Still scanning for 'case' or 'default' statement.
3874 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003875};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003876}
Richard Smith254a73d2011-10-28 22:34:42 +00003877
Richard Smith97fcf4b2016-08-14 23:15:52 +00003878static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3879 // We don't need to evaluate the initializer for a static local.
3880 if (!VD->hasLocalStorage())
3881 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003882
Richard Smith97fcf4b2016-08-14 23:15:52 +00003883 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003884 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00003885
Richard Smith97fcf4b2016-08-14 23:15:52 +00003886 const Expr *InitE = VD->getInit();
3887 if (!InitE) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003888 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
3889 << false << VD->getType();
Richard Smith97fcf4b2016-08-14 23:15:52 +00003890 Val = APValue();
3891 return false;
3892 }
Richard Smith51f03172013-06-20 03:00:05 +00003893
Richard Smith97fcf4b2016-08-14 23:15:52 +00003894 if (InitE->isValueDependent())
3895 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003896
Richard Smith97fcf4b2016-08-14 23:15:52 +00003897 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3898 // Wipe out any partially-computed value, to allow tracking that this
3899 // evaluation failed.
3900 Val = APValue();
3901 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003902 }
3903
3904 return true;
3905}
3906
Richard Smith97fcf4b2016-08-14 23:15:52 +00003907static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3908 bool OK = true;
3909
3910 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3911 OK &= EvaluateVarDecl(Info, VD);
3912
3913 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3914 for (auto *BD : DD->bindings())
3915 if (auto *VD = BD->getHoldingVar())
3916 OK &= EvaluateDecl(Info, VD);
3917
3918 return OK;
3919}
3920
3921
Richard Smith4e18ca52013-05-06 05:56:11 +00003922/// Evaluate a condition (either a variable declaration or an expression).
3923static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3924 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003925 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003926 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3927 return false;
3928 return EvaluateAsBooleanCondition(Cond, Result, Info);
3929}
3930
Richard Smith89210072016-04-04 23:29:43 +00003931namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003932/// A location where the result (returned value) of evaluating a
Richard Smith52a980a2015-08-28 02:43:42 +00003933/// statement should be stored.
3934struct StmtResult {
3935 /// The APValue that should be filled in with the returned value.
3936 APValue &Value;
3937 /// The location containing the result, if any (used to support RVO).
3938 const LValue *Slot;
3939};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003940
3941struct TempVersionRAII {
3942 CallStackFrame &Frame;
3943
3944 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3945 Frame.pushTempVersion();
3946 }
3947
3948 ~TempVersionRAII() {
3949 Frame.popTempVersion();
3950 }
3951};
3952
Richard Smith89210072016-04-04 23:29:43 +00003953}
Richard Smith52a980a2015-08-28 02:43:42 +00003954
3955static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003956 const Stmt *S,
3957 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003958
3959/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003960static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003961 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003962 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003963 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003964 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003965 case ESR_Break:
3966 return ESR_Succeeded;
3967 case ESR_Succeeded:
3968 case ESR_Continue:
3969 return ESR_Continue;
3970 case ESR_Failed:
3971 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003972 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003973 return ESR;
3974 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003975 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003976}
3977
Richard Smith496ddcf2013-05-12 17:32:42 +00003978/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003979static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003980 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003981 BlockScopeRAII Scope(Info);
3982
Richard Smith496ddcf2013-05-12 17:32:42 +00003983 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003984 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003985 {
3986 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003987 if (const Stmt *Init = SS->getInit()) {
3988 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3989 if (ESR != ESR_Succeeded)
3990 return ESR;
3991 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003992 if (SS->getConditionVariable() &&
3993 !EvaluateDecl(Info, SS->getConditionVariable()))
3994 return ESR_Failed;
3995 if (!EvaluateInteger(SS->getCond(), Value, Info))
3996 return ESR_Failed;
3997 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003998
3999 // Find the switch case corresponding to the value of the condition.
4000 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00004001 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004002 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4003 SC = SC->getNextSwitchCase()) {
4004 if (isa<DefaultStmt>(SC)) {
4005 Found = SC;
4006 continue;
4007 }
4008
4009 const CaseStmt *CS = cast<CaseStmt>(SC);
4010 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4011 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4012 : LHS;
4013 if (LHS <= Value && Value <= RHS) {
4014 Found = SC;
4015 break;
4016 }
4017 }
4018
4019 if (!Found)
4020 return ESR_Succeeded;
4021
4022 // Search the switch body for the switch case and evaluate it from there.
4023 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4024 case ESR_Break:
4025 return ESR_Succeeded;
4026 case ESR_Succeeded:
4027 case ESR_Continue:
4028 case ESR_Failed:
4029 case ESR_Returned:
4030 return ESR;
4031 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00004032 // This can only happen if the switch case is nested within a statement
4033 // expression. We have no intention of supporting that.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004034 Info.FFDiag(Found->getBeginLoc(),
4035 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00004036 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00004037 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00004038 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00004039}
4040
Richard Smith254a73d2011-10-28 22:34:42 +00004041// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00004042static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00004043 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00004044 if (!Info.nextStep(S))
4045 return ESR_Failed;
4046
Richard Smith496ddcf2013-05-12 17:32:42 +00004047 // If we're hunting down a 'case' or 'default' label, recurse through
4048 // substatements until we hit the label.
4049 if (Case) {
4050 // FIXME: We don't start the lifetime of objects whose initialization we
4051 // jump over. However, such objects must be of class type with a trivial
4052 // default constructor that initialize all subobjects, so must be empty,
4053 // so this almost never matters.
4054 switch (S->getStmtClass()) {
4055 case Stmt::CompoundStmtClass:
4056 // FIXME: Precompute which substatement of a compound statement we
4057 // would jump to, and go straight there rather than performing a
4058 // linear scan each time.
4059 case Stmt::LabelStmtClass:
4060 case Stmt::AttributedStmtClass:
4061 case Stmt::DoStmtClass:
4062 break;
4063
4064 case Stmt::CaseStmtClass:
4065 case Stmt::DefaultStmtClass:
4066 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00004067 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004068 break;
4069
4070 case Stmt::IfStmtClass: {
4071 // FIXME: Precompute which side of an 'if' we would jump to, and go
4072 // straight there rather than scanning both sides.
4073 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004074
4075 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4076 // preceded by our switch label.
4077 BlockScopeRAII Scope(Info);
4078
Richard Smith496ddcf2013-05-12 17:32:42 +00004079 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4080 if (ESR != ESR_CaseNotFound || !IS->getElse())
4081 return ESR;
4082 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4083 }
4084
4085 case Stmt::WhileStmtClass: {
4086 EvalStmtResult ESR =
4087 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4088 if (ESR != ESR_Continue)
4089 return ESR;
4090 break;
4091 }
4092
4093 case Stmt::ForStmtClass: {
4094 const ForStmt *FS = cast<ForStmt>(S);
4095 EvalStmtResult ESR =
4096 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4097 if (ESR != ESR_Continue)
4098 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004099 if (FS->getInc()) {
4100 FullExpressionRAII IncScope(Info);
4101 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4102 return ESR_Failed;
4103 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004104 break;
4105 }
4106
4107 case Stmt::DeclStmtClass:
4108 // FIXME: If the variable has initialization that can't be jumped over,
4109 // bail out of any immediately-surrounding compound-statement too.
4110 default:
4111 return ESR_CaseNotFound;
4112 }
4113 }
4114
Richard Smith254a73d2011-10-28 22:34:42 +00004115 switch (S->getStmtClass()) {
4116 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004117 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004118 // Don't bother evaluating beyond an expression-statement which couldn't
4119 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004120 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004121 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004122 return ESR_Failed;
4123 return ESR_Succeeded;
4124 }
4125
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004126 Info.FFDiag(S->getBeginLoc());
Richard Smith254a73d2011-10-28 22:34:42 +00004127 return ESR_Failed;
4128
4129 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004130 return ESR_Succeeded;
4131
Richard Smithd9f663b2013-04-22 15:31:51 +00004132 case Stmt::DeclStmtClass: {
4133 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004134 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004135 // Each declaration initialization is its own full-expression.
4136 // FIXME: This isn't quite right; if we're performing aggregate
4137 // initialization, each braced subexpression is its own full-expression.
4138 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004139 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004140 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004141 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004142 return ESR_Succeeded;
4143 }
4144
Richard Smith357362d2011-12-13 06:39:58 +00004145 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004146 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004147 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004148 if (RetExpr &&
4149 !(Result.Slot
4150 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4151 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004152 return ESR_Failed;
4153 return ESR_Returned;
4154 }
Richard Smith254a73d2011-10-28 22:34:42 +00004155
4156 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004157 BlockScopeRAII Scope(Info);
4158
Richard Smith254a73d2011-10-28 22:34:42 +00004159 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004160 for (const auto *BI : CS->body()) {
4161 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004162 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004163 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004164 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004165 return ESR;
4166 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004167 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004168 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004169
4170 case Stmt::IfStmtClass: {
4171 const IfStmt *IS = cast<IfStmt>(S);
4172
4173 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004174 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004175 if (const Stmt *Init = IS->getInit()) {
4176 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4177 if (ESR != ESR_Succeeded)
4178 return ESR;
4179 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004180 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004181 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004182 return ESR_Failed;
4183
4184 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4185 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4186 if (ESR != ESR_Succeeded)
4187 return ESR;
4188 }
4189 return ESR_Succeeded;
4190 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004191
4192 case Stmt::WhileStmtClass: {
4193 const WhileStmt *WS = cast<WhileStmt>(S);
4194 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004195 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004196 bool Continue;
4197 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4198 Continue))
4199 return ESR_Failed;
4200 if (!Continue)
4201 break;
4202
4203 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4204 if (ESR != ESR_Continue)
4205 return ESR;
4206 }
4207 return ESR_Succeeded;
4208 }
4209
4210 case Stmt::DoStmtClass: {
4211 const DoStmt *DS = cast<DoStmt>(S);
4212 bool Continue;
4213 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004214 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004215 if (ESR != ESR_Continue)
4216 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004217 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004218
Richard Smith08d6a2c2013-07-24 07:11:57 +00004219 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004220 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4221 return ESR_Failed;
4222 } while (Continue);
4223 return ESR_Succeeded;
4224 }
4225
4226 case Stmt::ForStmtClass: {
4227 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004228 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004229 if (FS->getInit()) {
4230 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4231 if (ESR != ESR_Succeeded)
4232 return ESR;
4233 }
4234 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004235 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004236 bool Continue = true;
4237 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4238 FS->getCond(), Continue))
4239 return ESR_Failed;
4240 if (!Continue)
4241 break;
4242
4243 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4244 if (ESR != ESR_Continue)
4245 return ESR;
4246
Richard Smith08d6a2c2013-07-24 07:11:57 +00004247 if (FS->getInc()) {
4248 FullExpressionRAII IncScope(Info);
4249 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4250 return ESR_Failed;
4251 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004252 }
4253 return ESR_Succeeded;
4254 }
4255
Richard Smith896e0d72013-05-06 06:51:17 +00004256 case Stmt::CXXForRangeStmtClass: {
4257 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004258 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004259
Richard Smith8baa5002018-09-28 18:44:09 +00004260 // Evaluate the init-statement if present.
4261 if (FS->getInit()) {
4262 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4263 if (ESR != ESR_Succeeded)
4264 return ESR;
4265 }
4266
Richard Smith896e0d72013-05-06 06:51:17 +00004267 // Initialize the __range variable.
4268 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4269 if (ESR != ESR_Succeeded)
4270 return ESR;
4271
4272 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004273 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4274 if (ESR != ESR_Succeeded)
4275 return ESR;
4276 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004277 if (ESR != ESR_Succeeded)
4278 return ESR;
4279
4280 while (true) {
4281 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004282 {
4283 bool Continue = true;
4284 FullExpressionRAII CondExpr(Info);
4285 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4286 return ESR_Failed;
4287 if (!Continue)
4288 break;
4289 }
Richard Smith896e0d72013-05-06 06:51:17 +00004290
4291 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004292 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004293 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4294 if (ESR != ESR_Succeeded)
4295 return ESR;
4296
4297 // Loop body.
4298 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4299 if (ESR != ESR_Continue)
4300 return ESR;
4301
4302 // Increment: ++__begin
4303 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4304 return ESR_Failed;
4305 }
4306
4307 return ESR_Succeeded;
4308 }
4309
Richard Smith496ddcf2013-05-12 17:32:42 +00004310 case Stmt::SwitchStmtClass:
4311 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4312
Richard Smith4e18ca52013-05-06 05:56:11 +00004313 case Stmt::ContinueStmtClass:
4314 return ESR_Continue;
4315
4316 case Stmt::BreakStmtClass:
4317 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004318
4319 case Stmt::LabelStmtClass:
4320 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4321
4322 case Stmt::AttributedStmtClass:
4323 // As a general principle, C++11 attributes can be ignored without
4324 // any semantic impact.
4325 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4326 Case);
4327
4328 case Stmt::CaseStmtClass:
4329 case Stmt::DefaultStmtClass:
4330 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Bruno Cardoso Lopes5c1399a2018-12-10 19:03:12 +00004331 case Stmt::CXXTryStmtClass:
4332 // Evaluate try blocks by evaluating all sub statements.
4333 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004334 }
4335}
4336
Richard Smithcc36f692011-12-22 02:22:31 +00004337/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4338/// default constructor. If so, we'll fold it whether or not it's marked as
4339/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4340/// so we need special handling.
4341static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004342 const CXXConstructorDecl *CD,
4343 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004344 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4345 return false;
4346
Richard Smith66e05fe2012-01-18 05:21:49 +00004347 // Value-initialization does not call a trivial default constructor, so such a
4348 // call is a core constant expression whether or not the constructor is
4349 // constexpr.
4350 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004351 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004352 // FIXME: If DiagDecl is an implicitly-declared special member function,
4353 // we should be much more explicit about why it's not constexpr.
4354 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4355 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4356 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004357 } else {
4358 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4359 }
4360 }
4361 return true;
4362}
4363
Richard Smith357362d2011-12-13 06:39:58 +00004364/// CheckConstexprFunction - Check that a function can be called in a constant
4365/// expression.
4366static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4367 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004368 const FunctionDecl *Definition,
4369 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004370 // Potential constant expressions can contain calls to declared, but not yet
4371 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004372 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004373 Declaration->isConstexpr())
4374 return false;
4375
James Y Knightc7d3e602018-10-05 17:49:48 +00004376 // Bail out if the function declaration itself is invalid. We will
4377 // have produced a relevant diagnostic while parsing it, so just
4378 // note the problematic sub-expression.
4379 if (Declaration->isInvalidDecl()) {
4380 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0838f3a2013-05-14 05:18:44 +00004381 return false;
James Y Knightc7d3e602018-10-05 17:49:48 +00004382 }
Richard Smith0838f3a2013-05-14 05:18:44 +00004383
Richard Smithd9c6b032019-05-09 19:45:49 +00004384 // DR1872: An instantiated virtual constexpr function can't be called in a
4385 // constant expression.
4386 if (isa<CXXMethodDecl>(Declaration) &&
4387 cast<CXXMethodDecl>(Declaration)->isVirtual()) {
4388 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_call);
4389 return false;
4390 }
4391
Richard Smith357362d2011-12-13 06:39:58 +00004392 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004393 if (Definition && Definition->isConstexpr() &&
4394 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004395 return true;
4396
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004397 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004398 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Fangrui Song6907ce22018-07-30 19:24:48 +00004399
Richard Smith5179eb72016-06-28 19:03:57 +00004400 // If this function is not constexpr because it is an inherited
4401 // non-constexpr constructor, diagnose that directly.
4402 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4403 if (CD && CD->isInheritingConstructor()) {
4404 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Fangrui Song6907ce22018-07-30 19:24:48 +00004405 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004406 DiagDecl = CD = Inherited;
4407 }
4408
4409 // FIXME: If DiagDecl is an implicitly-declared special member function
4410 // or an inheriting constructor, we should be much more explicit about why
4411 // it's not constexpr.
4412 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004413 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004414 << CD->getInheritedConstructor().getConstructor()->getParent();
4415 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004416 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004417 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004418 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4419 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004420 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004421 }
4422 return false;
4423}
4424
Richard Smithbe6dd812014-11-19 21:27:17 +00004425/// Determine if a class has any fields that might need to be copied by a
4426/// trivial copy or move operation.
4427static bool hasFields(const CXXRecordDecl *RD) {
4428 if (!RD || RD->isEmpty())
4429 return false;
4430 for (auto *FD : RD->fields()) {
4431 if (FD->isUnnamedBitfield())
4432 continue;
4433 return true;
4434 }
4435 for (auto &Base : RD->bases())
4436 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4437 return true;
4438 return false;
4439}
4440
Richard Smithd62306a2011-11-10 06:34:14 +00004441namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004442typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004443}
4444
4445/// EvaluateArgs - Evaluate the arguments to a function call.
4446static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4447 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004448 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004449 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004450 I != E; ++I) {
4451 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4452 // If we're checking for a potential constant expression, evaluate all
4453 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004454 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004455 return false;
4456 Success = false;
4457 }
4458 }
4459 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004460}
4461
Richard Smith254a73d2011-10-28 22:34:42 +00004462/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004463static bool HandleFunctionCall(SourceLocation CallLoc,
4464 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004465 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004466 EvalInfo &Info, APValue &Result,
4467 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004468 ArgVector ArgValues(Args.size());
4469 if (!EvaluateArgs(Args, ArgValues, Info))
4470 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004471
Richard Smith253c2a32012-01-27 01:14:48 +00004472 if (!Info.CheckCallLimit(CallLoc))
4473 return false;
4474
4475 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004476
4477 // For a trivial copy or move assignment, perform an APValue copy. This is
4478 // essential for unions, where the operations performed by the assignment
4479 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004480 //
4481 // Skip this for non-union classes with no fields; in that case, the defaulted
4482 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004483 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004484 if (MD && MD->isDefaulted() &&
4485 (MD->getParent()->isUnion() ||
4486 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004487 assert(This &&
4488 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4489 LValue RHS;
4490 RHS.setFrom(Info.Ctx, ArgValues[0]);
4491 APValue RHSValue;
4492 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4493 RHS, RHSValue))
4494 return false;
Brian Gesiak5488ab42019-01-11 01:54:53 +00004495 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
Richard Smith99005e62013-05-07 03:19:20 +00004496 RHSValue))
4497 return false;
4498 This->moveInto(Result);
4499 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004500 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00004501 // We're in a lambda; determine the lambda capture field maps unless we're
4502 // just constexpr checking a lambda's call operator. constexpr checking is
4503 // done before the captures have been added to the closure object (unless
4504 // we're inferring constexpr-ness), so we don't have access to them in this
4505 // case. But since we don't need the captures to constexpr check, we can
4506 // just ignore them.
4507 if (!Info.checkingPotentialConstantExpression())
4508 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4509 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004510 }
4511
Richard Smith52a980a2015-08-28 02:43:42 +00004512 StmtResult Ret = {Result, ResultSlot};
4513 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004514 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004515 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004516 return true;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004517 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004518 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004519 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004520}
4521
Richard Smithd62306a2011-11-10 06:34:14 +00004522/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004523static bool HandleConstructorCall(const Expr *E, const LValue &This,
4524 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004525 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004526 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004527 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004528 if (!Info.CheckCallLimit(CallLoc))
4529 return false;
4530
Richard Smith3607ffe2012-02-13 03:54:03 +00004531 const CXXRecordDecl *RD = Definition->getParent();
4532 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004533 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004534 return false;
4535 }
4536
Erik Pilkington42925492017-10-04 00:18:55 +00004537 EvalInfo::EvaluatingConstructorRAII EvalObj(
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004538 Info, {This.getLValueBase(),
4539 {This.getLValueCallIndex(), This.getLValueVersion()}});
Richard Smith5179eb72016-06-28 19:03:57 +00004540 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004541
Richard Smith52a980a2015-08-28 02:43:42 +00004542 // FIXME: Creating an APValue just to hold a nonexistent return value is
4543 // wasteful.
4544 APValue RetVal;
4545 StmtResult Ret = {RetVal, nullptr};
4546
Richard Smith5179eb72016-06-28 19:03:57 +00004547 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004548 if (Definition->isDelegatingConstructor()) {
4549 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004550 {
4551 FullExpressionRAII InitScope(Info);
4552 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4553 return false;
4554 }
Richard Smith52a980a2015-08-28 02:43:42 +00004555 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004556 }
4557
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004558 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004559 // essential for unions (or classes with anonymous union members), where the
4560 // operations performed by the constructor cannot be represented by
4561 // ctor-initializers.
4562 //
4563 // Skip this for empty non-union classes; we should not perform an
4564 // lvalue-to-rvalue conversion on them because their copy constructor does not
4565 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004566 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004567 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004568 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004569 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004570 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004571 return handleLValueToRValueConversion(
4572 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4573 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004574 }
4575
4576 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004577 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004578 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004579 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004580
John McCalld7bca762012-05-01 00:38:49 +00004581 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004582 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4583
Richard Smith08d6a2c2013-07-24 07:11:57 +00004584 // A scope for temporaries lifetime-extended by reference members.
4585 BlockScopeRAII LifetimeExtendedScope(Info);
4586
Richard Smith253c2a32012-01-27 01:14:48 +00004587 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004588 unsigned BasesSeen = 0;
4589#ifndef NDEBUG
4590 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4591#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004592 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004593 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004594 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004595 APValue *Value = &Result;
4596
4597 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004598 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004599 if (I->isBaseInitializer()) {
4600 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004601#ifndef NDEBUG
4602 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004603 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004604 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4605 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4606 "base class initializers not in expected order");
4607 ++BaseIt;
4608#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004609 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004610 BaseType->getAsCXXRecordDecl(), &Layout))
4611 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004612 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004613 } else if ((FD = I->getMember())) {
4614 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004615 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004616 if (RD->isUnion()) {
4617 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004618 Value = &Result.getUnionValue();
4619 } else {
4620 Value = &Result.getStructField(FD->getFieldIndex());
4621 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004622 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004623 // Walk the indirect field decl's chain to find the object to initialize,
4624 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004625 auto IndirectFieldChain = IFD->chain();
4626 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004627 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004628 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4629 // Switch the union field if it differs. This happens if we had
4630 // preceding zero-initialization, and we're now initializing a union
4631 // subobject other than the first.
4632 // FIXME: In this case, the values of the other subobjects are
4633 // specified, since zero-initialization sets all padding bits to zero.
4634 if (Value->isUninit() ||
4635 (Value->isUnion() && Value->getUnionField() != FD)) {
4636 if (CD->isUnion())
4637 *Value = APValue(FD);
4638 else
4639 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004640 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004641 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004642 // Store Subobject as its parent before updating it for the last element
4643 // in the chain.
4644 if (C == IndirectFieldChain.back())
4645 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004646 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004647 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004648 if (CD->isUnion())
4649 Value = &Value->getUnionValue();
4650 else
4651 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004652 }
Richard Smithd62306a2011-11-10 06:34:14 +00004653 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004654 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004655 }
Richard Smith253c2a32012-01-27 01:14:48 +00004656
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004657 // Need to override This for implicit field initializers as in this case
4658 // This refers to innermost anonymous struct/union containing initializer,
4659 // not to currently constructed class.
4660 const Expr *Init = I->getInit();
4661 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4662 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004663 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004664 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4665 (FD && FD->isBitField() &&
4666 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004667 // If we're checking for a potential constant expression, evaluate all
4668 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004669 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004670 return false;
4671 Success = false;
4672 }
Richard Smithd62306a2011-11-10 06:34:14 +00004673 }
4674
Richard Smithd9f663b2013-04-22 15:31:51 +00004675 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004676 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004677}
4678
Richard Smith5179eb72016-06-28 19:03:57 +00004679static bool HandleConstructorCall(const Expr *E, const LValue &This,
4680 ArrayRef<const Expr*> Args,
4681 const CXXConstructorDecl *Definition,
4682 EvalInfo &Info, APValue &Result) {
4683 ArgVector ArgValues(Args.size());
4684 if (!EvaluateArgs(Args, ArgValues, Info))
4685 return false;
4686
4687 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4688 Info, Result);
4689}
4690
Eli Friedman9a156e52008-11-12 09:44:48 +00004691//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004692// Generic Evaluation
4693//===----------------------------------------------------------------------===//
4694namespace {
4695
Aaron Ballman68af21c2014-01-03 19:26:43 +00004696template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004697class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004698 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004699private:
Richard Smith52a980a2015-08-28 02:43:42 +00004700 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004701 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004702 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004703 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004704 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004705 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004706 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004707
Richard Smith17100ba2012-02-16 02:46:34 +00004708 // Check whether a conditional operator with a non-constant condition is a
4709 // potential constant expression. If neither arm is a potential constant
4710 // expression, then the conditional operator is not either.
4711 template<typename ConditionalOperator>
4712 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004713 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004714
4715 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004716 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004717 {
Richard Smith17100ba2012-02-16 02:46:34 +00004718 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004719 StmtVisitorTy::Visit(E->getFalseExpr());
4720 if (Diag.empty())
4721 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004722 }
Richard Smith17100ba2012-02-16 02:46:34 +00004723
George Burgess IV8c892b52016-05-25 22:31:54 +00004724 {
4725 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004726 Diag.clear();
4727 StmtVisitorTy::Visit(E->getTrueExpr());
4728 if (Diag.empty())
4729 return;
4730 }
4731
4732 Error(E, diag::note_constexpr_conditional_never_const);
4733 }
4734
4735
4736 template<typename ConditionalOperator>
4737 bool HandleConditionalOperator(const ConditionalOperator *E) {
4738 bool BoolResult;
4739 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004740 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004741 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004742 return false;
4743 }
4744 if (Info.noteFailure()) {
4745 StmtVisitorTy::Visit(E->getTrueExpr());
4746 StmtVisitorTy::Visit(E->getFalseExpr());
4747 }
Richard Smith17100ba2012-02-16 02:46:34 +00004748 return false;
4749 }
4750
4751 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4752 return StmtVisitorTy::Visit(EvalExpr);
4753 }
4754
Peter Collingbournee9200682011-05-13 03:29:01 +00004755protected:
4756 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004757 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004758 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4759
Richard Smith92b1ce02011-12-12 09:28:41 +00004760 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004761 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004762 }
4763
Aaron Ballman68af21c2014-01-03 19:26:43 +00004764 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004765
4766public:
4767 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4768
4769 EvalInfo &getEvalInfo() { return Info; }
4770
Richard Smithf57d8cb2011-12-09 22:58:01 +00004771 /// Report an evaluation error. This should only be called when an error is
4772 /// first discovered. When propagating an error, just return false.
4773 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004774 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004775 return false;
4776 }
4777 bool Error(const Expr *E) {
4778 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4779 }
4780
Aaron Ballman68af21c2014-01-03 19:26:43 +00004781 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004782 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004783 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004784 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004785 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004786 }
4787
Bill Wendling8003edc2018-11-09 00:41:36 +00004788 bool VisitConstantExpr(const ConstantExpr *E)
4789 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004790 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004791 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004792 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004793 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004794 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004795 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004796 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004797 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004798 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004799 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004800 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004801 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004802 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4803 TempVersionRAII RAII(*Info.CurrentCall);
4804 return StmtVisitorTy::Visit(E->getExpr());
4805 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004806 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004807 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00004808 // The initializer may not have been parsed yet, or might be erroneous.
4809 if (!E->getExpr())
4810 return Error(E);
4811 return StmtVisitorTy::Visit(E->getExpr());
4812 }
Richard Smith5894a912011-12-19 22:12:41 +00004813 // We cannot create any objects for which cleanups are required, so there is
4814 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004815 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004816 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004817
Aaron Ballman68af21c2014-01-03 19:26:43 +00004818 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004819 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4820 return static_cast<Derived*>(this)->VisitCastExpr(E);
4821 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004822 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004823 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4824 return static_cast<Derived*>(this)->VisitCastExpr(E);
4825 }
4826
Aaron Ballman68af21c2014-01-03 19:26:43 +00004827 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004828 switch (E->getOpcode()) {
4829 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004830 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004831
4832 case BO_Comma:
4833 VisitIgnoredValue(E->getLHS());
4834 return StmtVisitorTy::Visit(E->getRHS());
4835
4836 case BO_PtrMemD:
4837 case BO_PtrMemI: {
4838 LValue Obj;
4839 if (!HandleMemberPointerAccess(Info, E, Obj))
4840 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004841 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004842 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004843 return false;
4844 return DerivedSuccess(Result, E);
4845 }
4846 }
4847 }
4848
Aaron Ballman68af21c2014-01-03 19:26:43 +00004849 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004850 // Evaluate and cache the common expression. We treat it as a temporary,
4851 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004852 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004853 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004854 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004855
Richard Smith17100ba2012-02-16 02:46:34 +00004856 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004857 }
4858
Aaron Ballman68af21c2014-01-03 19:26:43 +00004859 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004860 bool IsBcpCall = false;
4861 // If the condition (ignoring parens) is a __builtin_constant_p call,
4862 // the result is a constant expression if it can be folded without
4863 // side-effects. This is an important GNU extension. See GCC PR38377
4864 // for discussion.
4865 if (const CallExpr *CallCE =
4866 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004867 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004868 IsBcpCall = true;
4869
4870 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4871 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004872 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004873 return false;
4874
Richard Smith6d4c6582013-11-05 22:18:15 +00004875 FoldConstant Fold(Info, IsBcpCall);
4876 if (!HandleConditionalOperator(E)) {
4877 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004878 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004879 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004880
4881 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004882 }
4883
Aaron Ballman68af21c2014-01-03 19:26:43 +00004884 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004885 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00004886 return DerivedSuccess(*Value, E);
4887
4888 const Expr *Source = E->getSourceExpr();
4889 if (!Source)
4890 return Error(E);
4891 if (Source == E) { // sanity checking.
4892 assert(0 && "OpaqueValueExpr recursively refers to itself");
4893 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004894 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004895 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004896 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004897
Aaron Ballman68af21c2014-01-03 19:26:43 +00004898 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004899 APValue Result;
4900 if (!handleCallExpr(E, Result, nullptr))
4901 return false;
4902 return DerivedSuccess(Result, E);
4903 }
4904
4905 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004906 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004907 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004908 QualType CalleeType = Callee->getType();
4909
Craig Topper36250ad2014-05-12 05:36:57 +00004910 const FunctionDecl *FD = nullptr;
4911 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004912 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004913 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004914
Richard Smithe97cbd72011-11-11 04:05:33 +00004915 // Extract function decl and 'this' pointer from the callee.
4916 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004917 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004918 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4919 // Explicit bound member calls, such as x.f() or p->g();
4920 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004921 return false;
4922 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004923 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004924 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004925 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4926 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004927 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4928 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004929 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004930 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004931 return Error(Callee);
4932
4933 FD = dyn_cast<FunctionDecl>(Member);
4934 if (!FD)
4935 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004936 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004937 LValue Call;
4938 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004939 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004940
Richard Smitha8105bc2012-01-06 16:39:00 +00004941 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004942 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004943 FD = dyn_cast_or_null<FunctionDecl>(
4944 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004945 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004946 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004947 // Don't call function pointers which have been cast to some other type.
4948 // Per DR (no number yet), the caller and callee can differ in noexcept.
4949 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4950 CalleeType->getPointeeType(), FD->getType())) {
4951 return Error(E);
4952 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004953
4954 // Overloaded operator calls to member functions are represented as normal
4955 // calls with '*this' as the first argument.
4956 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4957 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004958 // FIXME: When selecting an implicit conversion for an overloaded
4959 // operator delete, we sometimes try to evaluate calls to conversion
4960 // operators without a 'this' parameter!
4961 if (Args.empty())
4962 return Error(E);
4963
Nick Lewycky13073a62017-06-12 21:15:44 +00004964 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004965 return false;
4966 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004967 Args = Args.slice(1);
Fangrui Song6907ce22018-07-30 19:24:48 +00004968 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004969 // Map the static invoker for the lambda back to the call operator.
4970 // Conveniently, we don't have to slice out the 'this' argument (as is
4971 // being done for the non-static case), since a static member function
4972 // doesn't have an implicit argument passed in.
4973 const CXXRecordDecl *ClosureClass = MD->getParent();
4974 assert(
4975 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4976 "Number of captures must be zero for conversion to function-ptr");
4977
4978 const CXXMethodDecl *LambdaCallOp =
4979 ClosureClass->getLambdaCallOperator();
4980
4981 // Set 'FD', the function that will be called below, to the call
4982 // operator. If the closure object represents a generic lambda, find
4983 // the corresponding specialization of the call operator.
4984
4985 if (ClosureClass->isGenericLambda()) {
4986 assert(MD->isFunctionTemplateSpecialization() &&
4987 "A generic lambda's static-invoker function must be a "
4988 "template specialization");
4989 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4990 FunctionTemplateDecl *CallOpTemplate =
4991 LambdaCallOp->getDescribedFunctionTemplate();
4992 void *InsertPos = nullptr;
4993 FunctionDecl *CorrespondingCallOpSpecialization =
4994 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4995 assert(CorrespondingCallOpSpecialization &&
4996 "We must always have a function call operator specialization "
4997 "that corresponds to our static invoker specialization");
4998 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4999 } else
5000 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00005001 }
5002
Fangrui Song6907ce22018-07-30 19:24:48 +00005003
Richard Smithe97cbd72011-11-11 04:05:33 +00005004 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00005005 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00005006
Richard Smith47b34932012-02-01 02:39:43 +00005007 if (This && !This->checkSubobject(Info, E, CSK_This))
5008 return false;
5009
Craig Topper36250ad2014-05-12 05:36:57 +00005010 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00005011 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00005012
Nick Lewycky13073a62017-06-12 21:15:44 +00005013 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
5014 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00005015 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005016 return false;
5017
Richard Smith52a980a2015-08-28 02:43:42 +00005018 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00005019 }
5020
Aaron Ballman68af21c2014-01-03 19:26:43 +00005021 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005022 return StmtVisitorTy::Visit(E->getInitializer());
5023 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005024 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00005025 if (E->getNumInits() == 0)
5026 return DerivedZeroInitialization(E);
5027 if (E->getNumInits() == 1)
5028 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00005029 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005030 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005031 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005032 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005033 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005034 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005035 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00005036 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005037 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005038 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005039 }
Richard Smith4ce706a2011-10-11 21:43:33 +00005040
Richard Smithd62306a2011-11-10 06:34:14 +00005041 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00005042 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005043 assert(!E->isArrow() && "missing call to bound member function?");
5044
Richard Smith2e312c82012-03-03 22:46:17 +00005045 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00005046 if (!Evaluate(Val, Info, E->getBase()))
5047 return false;
5048
5049 QualType BaseTy = E->getBase()->getType();
5050
5051 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00005052 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005053 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00005054 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00005055 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5056
Richard Smith9defb7d2018-02-21 03:38:30 +00005057 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00005058 SubobjectDesignator Designator(BaseTy);
5059 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00005060
Richard Smith3229b742013-05-05 21:17:10 +00005061 APValue Result;
5062 return extractSubobject(Info, E, Obj, Designator, Result) &&
5063 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00005064 }
5065
Aaron Ballman68af21c2014-01-03 19:26:43 +00005066 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005067 switch (E->getCastKind()) {
5068 default:
5069 break;
5070
Richard Smitha23ab512013-05-23 00:30:41 +00005071 case CK_AtomicToNonAtomic: {
5072 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00005073 // This does not need to be done in place even for class/array types:
5074 // atomic-to-non-atomic conversion implies copying the object
5075 // representation.
5076 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00005077 return false;
5078 return DerivedSuccess(AtomicVal, E);
5079 }
5080
Richard Smith11562c52011-10-28 17:51:58 +00005081 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00005082 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00005083 return StmtVisitorTy::Visit(E->getSubExpr());
5084
5085 case CK_LValueToRValue: {
5086 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005087 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5088 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005089 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00005090 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00005091 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00005092 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005093 return false;
5094 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00005095 }
5096 }
5097
Richard Smithf57d8cb2011-12-09 22:58:01 +00005098 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005099 }
5100
Aaron Ballman68af21c2014-01-03 19:26:43 +00005101 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005102 return VisitUnaryPostIncDec(UO);
5103 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005104 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00005105 return VisitUnaryPostIncDec(UO);
5106 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00005107 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005108 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005109 return Error(UO);
5110
5111 LValue LVal;
5112 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5113 return false;
5114 APValue RVal;
5115 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5116 UO->isIncrementOp(), &RVal))
5117 return false;
5118 return DerivedSuccess(RVal, UO);
5119 }
5120
Aaron Ballman68af21c2014-01-03 19:26:43 +00005121 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00005122 // We will have checked the full-expressions inside the statement expression
5123 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00005124 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00005125 return Error(E);
5126
Richard Smith08d6a2c2013-07-24 07:11:57 +00005127 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00005128 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005129 if (CS->body_empty())
5130 return true;
5131
Richard Smith51f03172013-06-20 03:00:05 +00005132 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5133 BE = CS->body_end();
5134 /**/; ++BI) {
5135 if (BI + 1 == BE) {
5136 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5137 if (!FinalExpr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005138 Info.FFDiag((*BI)->getBeginLoc(),
5139 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005140 return false;
5141 }
5142 return this->Visit(FinalExpr);
5143 }
5144
5145 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00005146 StmtResult Result = { ReturnValue, nullptr };
5147 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00005148 if (ESR != ESR_Succeeded) {
5149 // FIXME: If the statement-expression terminated due to 'return',
5150 // 'break', or 'continue', it would be nice to propagate that to
5151 // the outer statement evaluation rather than bailing out.
5152 if (ESR != ESR_Failed)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005153 Info.FFDiag((*BI)->getBeginLoc(),
5154 diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00005155 return false;
5156 }
5157 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005158
5159 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00005160 }
5161
Richard Smith4a678122011-10-24 18:44:57 +00005162 /// Visit a value which is evaluated, but whose value is ignored.
5163 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00005164 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00005165 }
David Majnemere9807b22016-02-26 04:23:19 +00005166
5167 /// Potentially visit a MemberExpr's base expression.
5168 void VisitIgnoredBaseExpression(const Expr *E) {
5169 // While MSVC doesn't evaluate the base expression, it does diagnose the
5170 // presence of side-effecting behavior.
5171 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5172 return;
5173 VisitIgnoredValue(E);
5174 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005175};
5176
Eric Fiselier0683c0e2018-05-07 21:07:10 +00005177} // namespace
Peter Collingbournee9200682011-05-13 03:29:01 +00005178
5179//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005180// Common base class for lvalue and temporary evaluation.
5181//===----------------------------------------------------------------------===//
5182namespace {
5183template<class Derived>
5184class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005185 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00005186protected:
5187 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005188 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005189 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005190 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005191
5192 bool Success(APValue::LValueBase B) {
5193 Result.set(B);
5194 return true;
5195 }
5196
George Burgess IVf9013bf2017-02-10 22:52:29 +00005197 bool evaluatePointer(const Expr *E, LValue &Result) {
5198 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5199 }
5200
Richard Smith027bf112011-11-17 22:56:20 +00005201public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005202 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5203 : ExprEvaluatorBaseTy(Info), Result(Result),
5204 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005205
Richard Smith2e312c82012-03-03 22:46:17 +00005206 bool Success(const APValue &V, const Expr *E) {
5207 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005208 return true;
5209 }
Richard Smith027bf112011-11-17 22:56:20 +00005210
Richard Smith027bf112011-11-17 22:56:20 +00005211 bool VisitMemberExpr(const MemberExpr *E) {
5212 // Handle non-static data members.
5213 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005214 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005215 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005216 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005217 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005218 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005219 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005220 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005221 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005222 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005223 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005224 BaseTy = E->getBase()->getType();
5225 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005226 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005227 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005228 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005229 Result.setInvalid(E);
5230 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005231 }
Richard Smith027bf112011-11-17 22:56:20 +00005232
Richard Smith1b78b3d2012-01-25 22:15:11 +00005233 const ValueDecl *MD = E->getMemberDecl();
5234 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5235 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5236 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5237 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005238 if (!HandleLValueMember(this->Info, E, Result, FD))
5239 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005240 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005241 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5242 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005243 } else
5244 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005245
Richard Smith1b78b3d2012-01-25 22:15:11 +00005246 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005247 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005248 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005249 RefValue))
5250 return false;
5251 return Success(RefValue, E);
5252 }
5253 return true;
5254 }
5255
5256 bool VisitBinaryOperator(const BinaryOperator *E) {
5257 switch (E->getOpcode()) {
5258 default:
5259 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5260
5261 case BO_PtrMemD:
5262 case BO_PtrMemI:
5263 return HandleMemberPointerAccess(this->Info, E, Result);
5264 }
5265 }
5266
5267 bool VisitCastExpr(const CastExpr *E) {
5268 switch (E->getCastKind()) {
5269 default:
5270 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5271
5272 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005273 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005274 if (!this->Visit(E->getSubExpr()))
5275 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005276
5277 // Now figure out the necessary offset to add to the base LV to get from
5278 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005279 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5280 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005281 }
5282 }
5283};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005284}
Richard Smith027bf112011-11-17 22:56:20 +00005285
5286//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005287// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005288//
5289// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5290// function designators (in C), decl references to void objects (in C), and
5291// temporaries (if building with -Wno-address-of-temporary).
5292//
5293// LValue evaluation produces values comprising a base expression of one of the
5294// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005295// - Declarations
5296// * VarDecl
5297// * FunctionDecl
5298// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005299// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005300// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005301// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005302// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005303// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005304// * ObjCEncodeExpr
5305// * AddrLabelExpr
5306// * BlockExpr
5307// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005308// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005309// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005310// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005311// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5312// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005313// * A MaterializeTemporaryExpr that has static storage duration, with no
5314// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005315// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005316//===----------------------------------------------------------------------===//
5317namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005318class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005319 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005320public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005321 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5322 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005323
Richard Smith11562c52011-10-28 17:51:58 +00005324 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005325 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005326
Peter Collingbournee9200682011-05-13 03:29:01 +00005327 bool VisitDeclRefExpr(const DeclRefExpr *E);
5328 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005329 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005330 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5331 bool VisitMemberExpr(const MemberExpr *E);
5332 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5333 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005334 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005335 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005336 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5337 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005338 bool VisitUnaryReal(const UnaryOperator *E);
5339 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005340 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5341 return VisitUnaryPreIncDec(UO);
5342 }
5343 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5344 return VisitUnaryPreIncDec(UO);
5345 }
Richard Smith3229b742013-05-05 21:17:10 +00005346 bool VisitBinAssign(const BinaryOperator *BO);
5347 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005348
Peter Collingbournee9200682011-05-13 03:29:01 +00005349 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005350 switch (E->getCastKind()) {
5351 default:
Richard Smith027bf112011-11-17 22:56:20 +00005352 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005353
Eli Friedmance3e02a2011-10-11 00:13:24 +00005354 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005355 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005356 if (!Visit(E->getSubExpr()))
5357 return false;
5358 Result.Designator.setInvalid();
5359 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005360
Richard Smith027bf112011-11-17 22:56:20 +00005361 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005362 if (!Visit(E->getSubExpr()))
5363 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005364 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005365 }
5366 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005367};
5368} // end anonymous namespace
5369
Richard Smith11562c52011-10-28 17:51:58 +00005370/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005371/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005372/// * function designators in C, and
5373/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005374/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005375static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5376 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005377 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005378 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005379 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005380}
5381
Peter Collingbournee9200682011-05-13 03:29:01 +00005382bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005383 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005384 return Success(FD);
5385 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005386 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005387 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005388 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005389 return Error(E);
5390}
Richard Smith733237d2011-10-24 23:14:33 +00005391
Faisal Vali0528a312016-11-13 06:09:16 +00005392
Richard Smith11562c52011-10-28 17:51:58 +00005393bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005394
5395 // If we are within a lambda's call operator, check whether the 'VD' referred
5396 // to within 'E' actually represents a lambda-capture that maps to a
5397 // data-member/field within the closure object, and if so, evaluate to the
5398 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00005399 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5400 isa<DeclRefExpr>(E) &&
5401 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5402 // We don't always have a complete capture-map when checking or inferring if
5403 // the function call operator meets the requirements of a constexpr function
5404 // - but we don't need to evaluate the captures to determine constexprness
5405 // (dcl.constexpr C++17).
5406 if (Info.checkingPotentialConstantExpression())
5407 return false;
5408
Faisal Vali051e3a22017-02-16 04:12:21 +00005409 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005410 // Start with 'Result' referring to the complete closure object...
5411 Result = *Info.CurrentCall->This;
5412 // ... then update it to refer to the field of the closure object
5413 // that represents the capture.
5414 if (!HandleLValueMember(Info, E, Result, FD))
5415 return false;
5416 // And if the field is of reference type, update 'Result' to refer to what
5417 // the field refers to.
5418 if (FD->getType()->isReferenceType()) {
5419 APValue RVal;
5420 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5421 RVal))
5422 return false;
5423 Result.setFrom(Info.Ctx, RVal);
5424 }
5425 return true;
5426 }
5427 }
Craig Topper36250ad2014-05-12 05:36:57 +00005428 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005429 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5430 // Only if a local variable was declared in the function currently being
5431 // evaluated, do we expect to be able to find its value in the current
5432 // frame. (Otherwise it was likely declared in an enclosing context and
5433 // could either have a valid evaluatable value (for e.g. a constexpr
5434 // variable) or be ill-formed (and trigger an appropriate evaluation
5435 // diagnostic)).
5436 if (Info.CurrentCall->Callee &&
5437 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5438 Frame = Info.CurrentCall;
5439 }
5440 }
Richard Smith3229b742013-05-05 21:17:10 +00005441
Richard Smithfec09922011-11-01 16:57:24 +00005442 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005443 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005444 Result.set({VD, Frame->Index,
5445 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00005446 return true;
5447 }
Richard Smithce40ad62011-11-12 22:28:03 +00005448 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005449 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005450
Richard Smith3229b742013-05-05 21:17:10 +00005451 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005452 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005453 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005454 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005455 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005456 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005457 return false;
5458 }
Richard Smith3229b742013-05-05 21:17:10 +00005459 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005460}
5461
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005462bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5463 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005464 // Walk through the expression to find the materialized temporary itself.
5465 SmallVector<const Expr *, 2> CommaLHSs;
5466 SmallVector<SubobjectAdjustment, 2> Adjustments;
5467 const Expr *Inner = E->GetTemporaryExpr()->
5468 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005469
Richard Smith84401042013-06-03 05:03:02 +00005470 // If we passed any comma operators, evaluate their LHSs.
5471 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5472 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5473 return false;
5474
Richard Smithe6c01442013-06-05 00:46:14 +00005475 // A materialized temporary with static storage duration can appear within the
5476 // result of a constant expression evaluation, so we need to preserve its
5477 // value for use outside this evaluation.
5478 APValue *Value;
5479 if (E->getStorageDuration() == SD_Static) {
5480 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005481 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005482 Result.set(E);
5483 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005484 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5485 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00005486 }
5487
Richard Smithea4ad5d2013-06-06 08:19:16 +00005488 QualType Type = Inner->getType();
5489
Richard Smith84401042013-06-03 05:03:02 +00005490 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005491 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5492 (E->getStorageDuration() == SD_Static &&
5493 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5494 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005495 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005496 }
Richard Smith84401042013-06-03 05:03:02 +00005497
5498 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005499 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5500 --I;
5501 switch (Adjustments[I].Kind) {
5502 case SubobjectAdjustment::DerivedToBaseAdjustment:
5503 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5504 Type, Result))
5505 return false;
5506 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5507 break;
5508
5509 case SubobjectAdjustment::FieldAdjustment:
5510 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5511 return false;
5512 Type = Adjustments[I].Field->getType();
5513 break;
5514
5515 case SubobjectAdjustment::MemberPointerAdjustment:
5516 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5517 Adjustments[I].Ptr.RHS))
5518 return false;
5519 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5520 break;
5521 }
5522 }
5523
5524 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005525}
5526
Peter Collingbournee9200682011-05-13 03:29:01 +00005527bool
5528LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005529 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5530 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005531 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5532 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005533 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005534}
5535
Richard Smith6e525142011-12-27 12:18:28 +00005536bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005537 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005538 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005539
Faisal Valie690b7a2016-07-02 22:34:24 +00005540 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005541 << E->getExprOperand()->getType()
5542 << E->getExprOperand()->getSourceRange();
5543 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005544}
5545
Francois Pichet0066db92012-04-16 04:08:35 +00005546bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5547 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005548}
Francois Pichet0066db92012-04-16 04:08:35 +00005549
Peter Collingbournee9200682011-05-13 03:29:01 +00005550bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005551 // Handle static data members.
5552 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005553 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005554 return VisitVarDecl(E, VD);
5555 }
5556
Richard Smith254a73d2011-10-28 22:34:42 +00005557 // Handle static member functions.
5558 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5559 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005560 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005561 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005562 }
5563 }
5564
Richard Smithd62306a2011-11-10 06:34:14 +00005565 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005566 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005567}
5568
Peter Collingbournee9200682011-05-13 03:29:01 +00005569bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005570 // FIXME: Deal with vectors as array subscript bases.
5571 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005572 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005573
Nick Lewyckyad888682017-04-27 07:27:36 +00005574 bool Success = true;
5575 if (!evaluatePointer(E->getBase(), Result)) {
5576 if (!Info.noteFailure())
5577 return false;
5578 Success = false;
5579 }
Mike Stump11289f42009-09-09 15:08:12 +00005580
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005581 APSInt Index;
5582 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005583 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005584
Nick Lewyckyad888682017-04-27 07:27:36 +00005585 return Success &&
5586 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005587}
Eli Friedman9a156e52008-11-12 09:44:48 +00005588
Peter Collingbournee9200682011-05-13 03:29:01 +00005589bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005590 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005591}
5592
Richard Smith66c96992012-02-18 22:04:06 +00005593bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5594 if (!Visit(E->getSubExpr()))
5595 return false;
5596 // __real is a no-op on scalar lvalues.
5597 if (E->getSubExpr()->getType()->isAnyComplexType())
5598 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5599 return true;
5600}
5601
5602bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5603 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5604 "lvalue __imag__ on scalar?");
5605 if (!Visit(E->getSubExpr()))
5606 return false;
5607 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5608 return true;
5609}
5610
Richard Smith243ef902013-05-05 23:31:59 +00005611bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005612 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005613 return Error(UO);
5614
5615 if (!this->Visit(UO->getSubExpr()))
5616 return false;
5617
Richard Smith243ef902013-05-05 23:31:59 +00005618 return handleIncDec(
5619 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005620 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005621}
5622
5623bool LValueExprEvaluator::VisitCompoundAssignOperator(
5624 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005625 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005626 return Error(CAO);
5627
Richard Smith3229b742013-05-05 21:17:10 +00005628 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005629
5630 // The overall lvalue result is the result of evaluating the LHS.
5631 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005632 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005633 Evaluate(RHS, this->Info, CAO->getRHS());
5634 return false;
5635 }
5636
Richard Smith3229b742013-05-05 21:17:10 +00005637 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5638 return false;
5639
Richard Smith43e77732013-05-07 04:50:00 +00005640 return handleCompoundAssignment(
5641 this->Info, CAO,
5642 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5643 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005644}
5645
5646bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005647 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005648 return Error(E);
5649
Richard Smith3229b742013-05-05 21:17:10 +00005650 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005651
5652 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005653 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005654 Evaluate(NewVal, this->Info, E->getRHS());
5655 return false;
5656 }
5657
Richard Smith3229b742013-05-05 21:17:10 +00005658 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5659 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005660
5661 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005662 NewVal);
5663}
5664
Eli Friedman9a156e52008-11-12 09:44:48 +00005665//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005666// Pointer Evaluation
5667//===----------------------------------------------------------------------===//
5668
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005669/// Attempts to compute the number of bytes available at the pointer
George Burgess IVe3763372016-12-22 02:50:20 +00005670/// returned by a function with the alloc_size attribute. Returns true if we
5671/// were successful. Places an unsigned number into `Result`.
5672///
5673/// This expects the given CallExpr to be a call to a function with an
5674/// alloc_size attribute.
5675static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5676 const CallExpr *Call,
5677 llvm::APInt &Result) {
5678 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5679
Joel E. Denny81508102018-03-13 14:51:22 +00005680 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5681 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005682 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5683 if (Call->getNumArgs() <= SizeArgNo)
5684 return false;
5685
5686 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
Fangrui Song407659a2018-11-30 23:41:18 +00005687 Expr::EvalResult ExprResult;
5688 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
George Burgess IVe3763372016-12-22 02:50:20 +00005689 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00005690 Into = ExprResult.Val.getInt();
George Burgess IVe3763372016-12-22 02:50:20 +00005691 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5692 return false;
5693 Into = Into.zextOrSelf(BitsInSizeT);
5694 return true;
5695 };
5696
5697 APSInt SizeOfElem;
5698 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5699 return false;
5700
Joel E. Denny81508102018-03-13 14:51:22 +00005701 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005702 Result = std::move(SizeOfElem);
5703 return true;
5704 }
5705
5706 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00005707 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005708 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5709 return false;
5710
5711 bool Overflow;
5712 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5713 if (Overflow)
5714 return false;
5715
5716 Result = std::move(BytesAvailable);
5717 return true;
5718}
5719
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005720/// Convenience function. LVal's base must be a call to an alloc_size
George Burgess IVe3763372016-12-22 02:50:20 +00005721/// function.
5722static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5723 const LValue &LVal,
5724 llvm::APInt &Result) {
5725 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5726 "Can't get the size of a non alloc_size function");
5727 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5728 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5729 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5730}
5731
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005732/// Attempts to evaluate the given LValueBase as the result of a call to
George Burgess IVe3763372016-12-22 02:50:20 +00005733/// a function with the alloc_size attribute. If it was possible to do so, this
5734/// function will return true, make Result's Base point to said function call,
5735/// and mark Result's Base as invalid.
5736static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5737 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005738 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005739 return false;
5740
5741 // Because we do no form of static analysis, we only support const variables.
5742 //
5743 // Additionally, we can't support parameters, nor can we support static
5744 // variables (in the latter case, use-before-assign isn't UB; in the former,
5745 // we have no clue what they'll be assigned to).
5746 const auto *VD =
5747 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5748 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5749 return false;
5750
5751 const Expr *Init = VD->getAnyInitializer();
5752 if (!Init)
5753 return false;
5754
5755 const Expr *E = Init->IgnoreParens();
5756 if (!tryUnwrapAllocSizeCall(E))
5757 return false;
5758
5759 // Store E instead of E unwrapped so that the type of the LValue's base is
5760 // what the user wanted.
5761 Result.setInvalid(E);
5762
5763 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005764 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005765 return true;
5766}
5767
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005768namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005769class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005770 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005771 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005772 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005773
Peter Collingbournee9200682011-05-13 03:29:01 +00005774 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005775 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005776 return true;
5777 }
George Burgess IVe3763372016-12-22 02:50:20 +00005778
George Burgess IVf9013bf2017-02-10 22:52:29 +00005779 bool evaluateLValue(const Expr *E, LValue &Result) {
5780 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5781 }
5782
5783 bool evaluatePointer(const Expr *E, LValue &Result) {
5784 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5785 }
5786
George Burgess IVe3763372016-12-22 02:50:20 +00005787 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005788public:
Mike Stump11289f42009-09-09 15:08:12 +00005789
George Burgess IVf9013bf2017-02-10 22:52:29 +00005790 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5791 : ExprEvaluatorBaseTy(info), Result(Result),
5792 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005793
Richard Smith2e312c82012-03-03 22:46:17 +00005794 bool Success(const APValue &V, const Expr *E) {
5795 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005796 return true;
5797 }
Richard Smithfddd3842011-12-30 21:15:51 +00005798 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005799 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5800 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005801 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005802 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005803
John McCall45d55e42010-05-07 21:00:08 +00005804 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005805 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005806 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005807 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005808 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005809 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00005810 if (E->isExpressibleAsConstantInitializer())
5811 return Success(E);
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005812 if (Info.noteFailure())
5813 EvaluateIgnoredValue(Info, E->getSubExpr());
5814 return Error(E);
5815 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005816 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005817 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005818 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005819 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005820 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005821 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005822 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005823 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005824 }
Richard Smithd62306a2011-11-10 06:34:14 +00005825 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005826 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005827 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005828 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005829 if (!Info.CurrentCall->This) {
5830 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005831 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005832 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005833 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005834 return false;
5835 }
Richard Smithd62306a2011-11-10 06:34:14 +00005836 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005837 // If we are inside a lambda's call operator, the 'this' expression refers
5838 // to the enclosing '*this' object (either by value or reference) which is
5839 // either copied into the closure object's field that represents the '*this'
5840 // or refers to '*this'.
5841 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5842 // Update 'Result' to refer to the data member/field of the closure object
5843 // that represents the '*this' capture.
5844 if (!HandleLValueMember(Info, E, Result,
Fangrui Song6907ce22018-07-30 19:24:48 +00005845 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005846 return false;
5847 // If we captured '*this' by reference, replace the field with its referent.
5848 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5849 ->isPointerType()) {
5850 APValue RVal;
5851 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5852 RVal))
5853 return false;
5854
5855 Result.setFrom(Info.Ctx, RVal);
5856 }
5857 }
Richard Smithd62306a2011-11-10 06:34:14 +00005858 return true;
5859 }
John McCallc07a0c72011-02-17 10:25:35 +00005860
Eli Friedman449fe542009-03-23 04:56:01 +00005861 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005862};
Chris Lattner05706e882008-07-11 18:11:29 +00005863} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005864
George Burgess IVf9013bf2017-02-10 22:52:29 +00005865static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5866 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005867 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005868 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005869}
5870
John McCall45d55e42010-05-07 21:00:08 +00005871bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005872 if (E->getOpcode() != BO_Add &&
5873 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005874 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005875
Chris Lattner05706e882008-07-11 18:11:29 +00005876 const Expr *PExp = E->getLHS();
5877 const Expr *IExp = E->getRHS();
5878 if (IExp->getType()->isPointerType())
5879 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005880
George Burgess IVf9013bf2017-02-10 22:52:29 +00005881 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005882 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005883 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005884
John McCall45d55e42010-05-07 21:00:08 +00005885 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005886 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005887 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005888
Richard Smith96e0c102011-11-04 02:25:55 +00005889 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005890 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005891
Ted Kremenek28831752012-08-23 20:46:57 +00005892 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005893 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005894}
Eli Friedman9a156e52008-11-12 09:44:48 +00005895
John McCall45d55e42010-05-07 21:00:08 +00005896bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005897 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005898}
Mike Stump11289f42009-09-09 15:08:12 +00005899
Richard Smith81dfef92018-07-11 00:29:05 +00005900bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5901 const Expr *SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005902
Eli Friedman847a2bc2009-12-27 05:43:15 +00005903 switch (E->getCastKind()) {
5904 default:
5905 break;
5906
John McCalle3027922010-08-25 11:45:40 +00005907 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005908 case CK_CPointerToObjCPointerCast:
5909 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005910 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005911 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005912 if (!Visit(SubExpr))
5913 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005914 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5915 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5916 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005917 if (!E->getType()->isVoidPointerType()) {
James Y Knight49bf3702018-10-05 21:53:51 +00005918 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005919 if (SubExpr->getType()->isVoidPointerType())
5920 CCEDiag(E, diag::note_constexpr_invalid_cast)
5921 << 3 << SubExpr->getType();
5922 else
5923 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5924 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005925 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5926 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005927 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005928
Anders Carlsson18275092010-10-31 20:41:46 +00005929 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005930 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005931 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005932 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005933 if (!Result.Base && Result.Offset.isZero())
5934 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005935
Richard Smithd62306a2011-11-10 06:34:14 +00005936 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005937 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005938 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5939 castAs<PointerType>()->getPointeeType(),
5940 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005941
Richard Smith027bf112011-11-17 22:56:20 +00005942 case CK_BaseToDerived:
5943 if (!Visit(E->getSubExpr()))
5944 return false;
5945 if (!Result.Base && Result.Offset.isZero())
5946 return true;
5947 return HandleBaseToDerivedCast(Info, E, Result);
5948
Richard Smith0b0a0b62011-10-29 20:57:55 +00005949 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005950 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005951 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005952
John McCalle3027922010-08-25 11:45:40 +00005953 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005954 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5955
Richard Smith2e312c82012-03-03 22:46:17 +00005956 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005957 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005958 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005959
John McCall45d55e42010-05-07 21:00:08 +00005960 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005961 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5962 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005963 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005964 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005965 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00005966 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005967 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005968 return true;
5969 } else {
5970 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005971 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005972 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005973 }
5974 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005975
5976 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005977 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005978 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005979 return false;
5980 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005981 APValue &Value = createTemporary(SubExpr, false, Result,
5982 *Info.CurrentCall);
5983 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005984 return false;
5985 }
Richard Smith96e0c102011-11-04 02:25:55 +00005986 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005987 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5988 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005989 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005990 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005991 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005992 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005993 }
Richard Smithdd785442011-10-31 20:57:44 +00005994
John McCalle3027922010-08-25 11:45:40 +00005995 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005996 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005997
5998 case CK_LValueToRValue: {
5999 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00006000 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00006001 return false;
6002
6003 APValue RVal;
6004 // Note, we use the subexpression's type in order to retain cv-qualifiers.
6005 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6006 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00006007 return InvalidBaseOK &&
6008 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00006009 return Success(RVal, E);
6010 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006011 }
6012
Richard Smith11562c52011-10-28 17:51:58 +00006013 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00006014}
Chris Lattner05706e882008-07-11 18:11:29 +00006015
Richard Smith6822bd72018-10-26 19:26:45 +00006016static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
6017 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006018 // C++ [expr.alignof]p3:
6019 // When alignof is applied to a reference type, the result is the
6020 // alignment of the referenced type.
6021 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6022 T = Ref->getPointeeType();
6023
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00006024 if (T.getQualifiers().hasUnaligned())
6025 return CharUnits::One();
Richard Smith6822bd72018-10-26 19:26:45 +00006026
6027 const bool AlignOfReturnsPreferred =
6028 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
6029
6030 // __alignof is defined to return the preferred alignment.
6031 // Before 8, clang returned the preferred alignment for alignof and _Alignof
6032 // as well.
6033 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
6034 return Info.Ctx.toCharUnitsFromBits(
6035 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6036 // alignof and _Alignof are defined to return the ABI alignment.
6037 else if (ExprKind == UETT_AlignOf)
6038 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
6039 else
6040 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
Hal Finkel0dd05d42014-10-03 17:18:37 +00006041}
6042
Richard Smith6822bd72018-10-26 19:26:45 +00006043static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
6044 UnaryExprOrTypeTrait ExprKind) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006045 E = E->IgnoreParens();
6046
6047 // The kinds of expressions that we have special-case logic here for
6048 // should be kept up to date with the special checks for those
6049 // expressions in Sema.
6050
6051 // alignof decl is always accepted, even if it doesn't make sense: we default
6052 // to 1 in those cases.
6053 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6054 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6055 /*RefAsPointee*/true);
6056
6057 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6058 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6059 /*RefAsPointee*/true);
6060
Richard Smith6822bd72018-10-26 19:26:45 +00006061 return GetAlignOfType(Info, E->getType(), ExprKind);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006062}
6063
George Burgess IVe3763372016-12-22 02:50:20 +00006064// To be clear: this happily visits unsupported builtins. Better name welcomed.
6065bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6066 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6067 return true;
6068
George Burgess IVf9013bf2017-02-10 22:52:29 +00006069 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00006070 return false;
6071
6072 Result.setInvalid(E);
6073 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00006074 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00006075 return true;
6076}
6077
Peter Collingbournee9200682011-05-13 03:29:01 +00006078bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006079 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00006080 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00006081
Richard Smith6328cbd2016-11-16 00:57:23 +00006082 if (unsigned BuiltinOp = E->getBuiltinCallee())
6083 return VisitBuiltinCallExpr(E, BuiltinOp);
6084
George Burgess IVe3763372016-12-22 02:50:20 +00006085 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00006086}
6087
6088bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6089 unsigned BuiltinOp) {
6090 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00006091 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00006092 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006093 case Builtin::BI__builtin_assume_aligned: {
6094 // We need to be very careful here because: if the pointer does not have the
6095 // asserted alignment, then the behavior is undefined, and undefined
6096 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00006097 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00006098 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00006099
Hal Finkel0dd05d42014-10-03 17:18:37 +00006100 LValue OffsetResult(Result);
6101 APSInt Alignment;
6102 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6103 return false;
Richard Smith642a2362017-01-30 23:30:26 +00006104 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00006105
6106 if (E->getNumArgs() > 2) {
6107 APSInt Offset;
6108 if (!EvaluateInteger(E->getArg(2), Offset, Info))
6109 return false;
6110
Richard Smith642a2362017-01-30 23:30:26 +00006111 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006112 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6113 }
6114
6115 // If there is a base object, then it must have the correct alignment.
6116 if (OffsetResult.Base) {
6117 CharUnits BaseAlignment;
6118 if (const ValueDecl *VD =
6119 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6120 BaseAlignment = Info.Ctx.getDeclAlign(VD);
6121 } else {
Richard Smith6822bd72018-10-26 19:26:45 +00006122 BaseAlignment = GetAlignOfExpr(
6123 Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf);
Hal Finkel0dd05d42014-10-03 17:18:37 +00006124 }
6125
6126 if (BaseAlignment < Align) {
6127 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00006128 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00006129 CCEDiag(E->getArg(0),
6130 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00006131 << (unsigned)BaseAlignment.getQuantity()
6132 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006133 return false;
6134 }
6135 }
6136
6137 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006138 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006139 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006140
Richard Smith642a2362017-01-30 23:30:26 +00006141 (OffsetResult.Base
6142 ? CCEDiag(E->getArg(0),
6143 diag::note_constexpr_baa_insufficient_alignment) << 1
6144 : CCEDiag(E->getArg(0),
6145 diag::note_constexpr_baa_value_insufficient_alignment))
6146 << (int)OffsetResult.Offset.getQuantity()
6147 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006148 return false;
6149 }
6150
6151 return true;
6152 }
Eric Fiselier26187502018-12-14 21:11:28 +00006153 case Builtin::BI__builtin_launder:
6154 return evaluatePointer(E->getArg(0), Result);
Richard Smithe9507952016-11-12 01:39:56 +00006155 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006156 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00006157 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006158 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00006159 if (Info.getLangOpts().CPlusPlus11)
6160 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6161 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00006162 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00006163 else
6164 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006165 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00006166 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006167 case Builtin::BI__builtin_wcschr:
6168 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006169 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006170 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00006171 if (!Visit(E->getArg(0)))
6172 return false;
6173 APSInt Desired;
6174 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6175 return false;
6176 uint64_t MaxLength = uint64_t(-1);
6177 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00006178 BuiltinOp != Builtin::BIwcschr &&
6179 BuiltinOp != Builtin::BI__builtin_strchr &&
6180 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00006181 APSInt N;
6182 if (!EvaluateInteger(E->getArg(2), N, Info))
6183 return false;
6184 MaxLength = N.getExtValue();
6185 }
Hubert Tong147b7432018-12-12 16:53:43 +00006186 // We cannot find the value if there are no candidates to match against.
6187 if (MaxLength == 0u)
6188 return ZeroInitialization(E);
6189 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
6190 Result.Designator.Invalid)
6191 return false;
6192 QualType CharTy = Result.Designator.getType(Info.Ctx);
6193 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
6194 BuiltinOp == Builtin::BI__builtin_memchr;
6195 assert(IsRawByte ||
6196 Info.Ctx.hasSameUnqualifiedType(
6197 CharTy, E->getArg(0)->getType()->getPointeeType()));
6198 // Pointers to const void may point to objects of incomplete type.
6199 if (IsRawByte && CharTy->isIncompleteType()) {
6200 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
6201 return false;
6202 }
6203 // Give up on byte-oriented matching against multibyte elements.
6204 // FIXME: We can compare the bytes in the correct order.
6205 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
6206 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00006207 // Figure out what value we're actually looking for (after converting to
6208 // the corresponding unsigned type if necessary).
6209 uint64_t DesiredVal;
6210 bool StopAtNull = false;
6211 switch (BuiltinOp) {
6212 case Builtin::BIstrchr:
6213 case Builtin::BI__builtin_strchr:
6214 // strchr compares directly to the passed integer, and therefore
6215 // always fails if given an int that is not a char.
6216 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6217 E->getArg(1)->getType(),
6218 Desired),
6219 Desired))
6220 return ZeroInitialization(E);
6221 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006222 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006223 case Builtin::BImemchr:
6224 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006225 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006226 // memchr compares by converting both sides to unsigned char. That's also
6227 // correct for strchr if we get this far (to cope with plain char being
6228 // unsigned in the strchr case).
6229 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6230 break;
Richard Smithe9507952016-11-12 01:39:56 +00006231
Richard Smith8110c9d2016-11-29 19:45:17 +00006232 case Builtin::BIwcschr:
6233 case Builtin::BI__builtin_wcschr:
6234 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006235 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006236 case Builtin::BIwmemchr:
6237 case Builtin::BI__builtin_wmemchr:
6238 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6239 DesiredVal = Desired.getZExtValue();
6240 break;
6241 }
Richard Smithe9507952016-11-12 01:39:56 +00006242
6243 for (; MaxLength; --MaxLength) {
6244 APValue Char;
6245 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6246 !Char.isInt())
6247 return false;
6248 if (Char.getInt().getZExtValue() == DesiredVal)
6249 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006250 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006251 break;
6252 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6253 return false;
6254 }
6255 // Not found: return nullptr.
6256 return ZeroInitialization(E);
6257 }
6258
Richard Smith06f71b52018-08-04 00:57:17 +00006259 case Builtin::BImemcpy:
6260 case Builtin::BImemmove:
6261 case Builtin::BIwmemcpy:
6262 case Builtin::BIwmemmove:
6263 if (Info.getLangOpts().CPlusPlus11)
6264 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6265 << /*isConstexpr*/0 << /*isConstructor*/0
6266 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6267 else
6268 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6269 LLVM_FALLTHROUGH;
6270 case Builtin::BI__builtin_memcpy:
6271 case Builtin::BI__builtin_memmove:
6272 case Builtin::BI__builtin_wmemcpy:
6273 case Builtin::BI__builtin_wmemmove: {
6274 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6275 BuiltinOp == Builtin::BIwmemmove ||
6276 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6277 BuiltinOp == Builtin::BI__builtin_wmemmove;
6278 bool Move = BuiltinOp == Builtin::BImemmove ||
6279 BuiltinOp == Builtin::BIwmemmove ||
6280 BuiltinOp == Builtin::BI__builtin_memmove ||
6281 BuiltinOp == Builtin::BI__builtin_wmemmove;
6282
6283 // The result of mem* is the first argument.
Richard Smith128719c2018-09-13 22:47:33 +00006284 if (!Visit(E->getArg(0)))
Richard Smith06f71b52018-08-04 00:57:17 +00006285 return false;
6286 LValue Dest = Result;
6287
6288 LValue Src;
Richard Smith128719c2018-09-13 22:47:33 +00006289 if (!EvaluatePointer(E->getArg(1), Src, Info))
Richard Smith06f71b52018-08-04 00:57:17 +00006290 return false;
6291
6292 APSInt N;
6293 if (!EvaluateInteger(E->getArg(2), N, Info))
6294 return false;
6295 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6296
6297 // If the size is zero, we treat this as always being a valid no-op.
6298 // (Even if one of the src and dest pointers is null.)
6299 if (!N)
6300 return true;
6301
Richard Smith128719c2018-09-13 22:47:33 +00006302 // Otherwise, if either of the operands is null, we can't proceed. Don't
6303 // try to determine the type of the copied objects, because there aren't
6304 // any.
6305 if (!Src.Base || !Dest.Base) {
6306 APValue Val;
6307 (!Src.Base ? Src : Dest).moveInto(Val);
6308 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6309 << Move << WChar << !!Src.Base
6310 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6311 return false;
6312 }
6313 if (Src.Designator.Invalid || Dest.Designator.Invalid)
6314 return false;
6315
Richard Smith06f71b52018-08-04 00:57:17 +00006316 // We require that Src and Dest are both pointers to arrays of
6317 // trivially-copyable type. (For the wide version, the designator will be
6318 // invalid if the designated object is not a wchar_t.)
6319 QualType T = Dest.Designator.getType(Info.Ctx);
6320 QualType SrcT = Src.Designator.getType(Info.Ctx);
6321 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6322 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6323 return false;
6324 }
Petr Pavlued083f22018-10-04 09:25:44 +00006325 if (T->isIncompleteType()) {
6326 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6327 return false;
6328 }
Richard Smith06f71b52018-08-04 00:57:17 +00006329 if (!T.isTriviallyCopyableType(Info.Ctx)) {
6330 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6331 return false;
6332 }
6333
6334 // Figure out how many T's we're copying.
6335 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6336 if (!WChar) {
6337 uint64_t Remainder;
6338 llvm::APInt OrigN = N;
6339 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6340 if (Remainder) {
6341 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6342 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6343 << (unsigned)TSize;
6344 return false;
6345 }
6346 }
6347
6348 // Check that the copying will remain within the arrays, just so that we
6349 // can give a more meaningful diagnostic. This implicitly also checks that
6350 // N fits into 64 bits.
6351 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6352 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6353 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6354 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6355 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6356 << N.toString(10, /*Signed*/false);
6357 return false;
6358 }
6359 uint64_t NElems = N.getZExtValue();
6360 uint64_t NBytes = NElems * TSize;
6361
6362 // Check for overlap.
6363 int Direction = 1;
6364 if (HasSameBase(Src, Dest)) {
6365 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6366 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6367 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6368 // Dest is inside the source region.
6369 if (!Move) {
6370 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6371 return false;
6372 }
6373 // For memmove and friends, copy backwards.
6374 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6375 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6376 return false;
6377 Direction = -1;
6378 } else if (!Move && SrcOffset >= DestOffset &&
6379 SrcOffset - DestOffset < NBytes) {
6380 // Src is inside the destination region for memcpy: invalid.
6381 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6382 return false;
6383 }
6384 }
6385
6386 while (true) {
6387 APValue Val;
6388 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6389 !handleAssignment(Info, E, Dest, T, Val))
6390 return false;
6391 // Do not iterate past the last element; if we're copying backwards, that
6392 // might take us off the start of the array.
6393 if (--NElems == 0)
6394 return true;
6395 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6396 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6397 return false;
6398 }
6399 }
6400
Richard Smith6cbd65d2013-07-11 02:27:57 +00006401 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006402 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006403 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006404}
Chris Lattner05706e882008-07-11 18:11:29 +00006405
6406//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006407// Member Pointer Evaluation
6408//===----------------------------------------------------------------------===//
6409
6410namespace {
6411class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006412 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006413 MemberPtr &Result;
6414
6415 bool Success(const ValueDecl *D) {
6416 Result = MemberPtr(D);
6417 return true;
6418 }
6419public:
6420
6421 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6422 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6423
Richard Smith2e312c82012-03-03 22:46:17 +00006424 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006425 Result.setFrom(V);
6426 return true;
6427 }
Richard Smithfddd3842011-12-30 21:15:51 +00006428 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006429 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006430 }
6431
6432 bool VisitCastExpr(const CastExpr *E);
6433 bool VisitUnaryAddrOf(const UnaryOperator *E);
6434};
6435} // end anonymous namespace
6436
6437static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6438 EvalInfo &Info) {
6439 assert(E->isRValue() && E->getType()->isMemberPointerType());
6440 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6441}
6442
6443bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6444 switch (E->getCastKind()) {
6445 default:
6446 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6447
6448 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006449 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006450 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006451
6452 case CK_BaseToDerivedMemberPointer: {
6453 if (!Visit(E->getSubExpr()))
6454 return false;
6455 if (E->path_empty())
6456 return true;
6457 // Base-to-derived member pointer casts store the path in derived-to-base
6458 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6459 // the wrong end of the derived->base arc, so stagger the path by one class.
6460 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6461 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6462 PathI != PathE; ++PathI) {
6463 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6464 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6465 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006466 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006467 }
6468 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6469 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006470 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006471 return true;
6472 }
6473
6474 case CK_DerivedToBaseMemberPointer:
6475 if (!Visit(E->getSubExpr()))
6476 return false;
6477 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6478 PathE = E->path_end(); PathI != PathE; ++PathI) {
6479 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6480 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6481 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006482 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006483 }
6484 return true;
6485 }
6486}
6487
6488bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6489 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6490 // member can be formed.
6491 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6492}
6493
6494//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006495// Record Evaluation
6496//===----------------------------------------------------------------------===//
6497
6498namespace {
6499 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006500 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006501 const LValue &This;
6502 APValue &Result;
6503 public:
6504
6505 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6506 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6507
Richard Smith2e312c82012-03-03 22:46:17 +00006508 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006509 Result = V;
6510 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006511 }
Richard Smithb8348f52016-05-12 22:16:28 +00006512 bool ZeroInitialization(const Expr *E) {
6513 return ZeroInitialization(E, E->getType());
6514 }
6515 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006516
Richard Smith52a980a2015-08-28 02:43:42 +00006517 bool VisitCallExpr(const CallExpr *E) {
6518 return handleCallExpr(E, Result, &This);
6519 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006520 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006521 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006522 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6523 return VisitCXXConstructExpr(E, E->getType());
6524 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006525 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006526 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006527 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006528 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Eric Fiselier0683c0e2018-05-07 21:07:10 +00006529
6530 bool VisitBinCmp(const BinaryOperator *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006531 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006532}
Richard Smithd62306a2011-11-10 06:34:14 +00006533
Richard Smithfddd3842011-12-30 21:15:51 +00006534/// Perform zero-initialization on an object of non-union class type.
6535/// C++11 [dcl.init]p5:
6536/// To zero-initialize an object or reference of type T means:
6537/// [...]
6538/// -- if T is a (possibly cv-qualified) non-union class type,
6539/// each non-static data member and each base-class subobject is
6540/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006541static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6542 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006543 const LValue &This, APValue &Result) {
6544 assert(!RD->isUnion() && "Expected non-union class type");
6545 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6546 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006547 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006548
John McCalld7bca762012-05-01 00:38:49 +00006549 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006550 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6551
6552 if (CD) {
6553 unsigned Index = 0;
6554 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006555 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006556 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6557 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006558 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6559 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006560 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006561 Result.getStructBase(Index)))
6562 return false;
6563 }
6564 }
6565
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006566 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006567 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006568 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006569 continue;
6570
6571 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006572 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006573 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006574
David Blaikie2d7c57e2012-04-30 02:36:29 +00006575 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006576 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006577 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006578 return false;
6579 }
6580
6581 return true;
6582}
6583
Richard Smithb8348f52016-05-12 22:16:28 +00006584bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6585 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006586 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006587 if (RD->isUnion()) {
6588 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6589 // object's first non-static named data member is zero-initialized
6590 RecordDecl::field_iterator I = RD->field_begin();
6591 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006592 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006593 return true;
6594 }
6595
6596 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006597 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006598 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006599 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006600 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006601 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006602 }
6603
Richard Smith5d108602012-02-17 00:44:16 +00006604 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006605 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006606 return false;
6607 }
6608
Richard Smitha8105bc2012-01-06 16:39:00 +00006609 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006610}
6611
Richard Smithe97cbd72011-11-11 04:05:33 +00006612bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6613 switch (E->getCastKind()) {
6614 default:
6615 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6616
6617 case CK_ConstructorConversion:
6618 return Visit(E->getSubExpr());
6619
6620 case CK_DerivedToBase:
6621 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006622 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006623 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006624 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006625 if (!DerivedObject.isStruct())
6626 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006627
6628 // Derived-to-base rvalue conversion: just slice off the derived part.
6629 APValue *Value = &DerivedObject;
6630 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6631 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6632 PathE = E->path_end(); PathI != PathE; ++PathI) {
6633 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6634 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6635 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6636 RD = Base;
6637 }
6638 Result = *Value;
6639 return true;
6640 }
6641 }
6642}
6643
Richard Smithd62306a2011-11-10 06:34:14 +00006644bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006645 if (E->isTransparent())
6646 return Visit(E->getInit(0));
6647
Richard Smithd62306a2011-11-10 06:34:14 +00006648 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006649 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006650 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6651
6652 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006653 const FieldDecl *Field = E->getInitializedFieldInUnion();
6654 Result = APValue(Field);
6655 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006656 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006657
6658 // If the initializer list for a union does not contain any elements, the
6659 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006660 // FIXME: The element should be initialized from an initializer list.
6661 // Is this difference ever observable for initializer lists which
6662 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006663 ImplicitValueInitExpr VIE(Field->getType());
6664 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6665
Richard Smithd62306a2011-11-10 06:34:14 +00006666 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006667 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6668 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006669
6670 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6671 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6672 isa<CXXDefaultInitExpr>(InitExpr));
6673
Richard Smithb228a862012-02-15 02:18:13 +00006674 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006675 }
6676
Richard Smith872307e2016-03-08 22:17:41 +00006677 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006678 if (Result.isUninit())
6679 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6680 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006681 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006682 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006683
6684 // Initialize base classes.
6685 if (CXXRD) {
6686 for (const auto &Base : CXXRD->bases()) {
6687 assert(ElementNo < E->getNumInits() && "missing init for base class");
6688 const Expr *Init = E->getInit(ElementNo);
6689
6690 LValue Subobject = This;
6691 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6692 return false;
6693
6694 APValue &FieldVal = Result.getStructBase(ElementNo);
6695 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006696 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006697 return false;
6698 Success = false;
6699 }
6700 ++ElementNo;
6701 }
6702 }
6703
6704 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006705 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006706 // Anonymous bit-fields are not considered members of the class for
6707 // purposes of aggregate initialization.
6708 if (Field->isUnnamedBitfield())
6709 continue;
6710
6711 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006712
Richard Smith253c2a32012-01-27 01:14:48 +00006713 bool HaveInit = ElementNo < E->getNumInits();
6714
6715 // FIXME: Diagnostics here should point to the end of the initializer
6716 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006717 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006718 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006719 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006720
6721 // Perform an implicit value-initialization for members beyond the end of
6722 // the initializer list.
6723 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006724 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006725
Richard Smith852c9db2013-04-20 22:23:05 +00006726 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6727 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6728 isa<CXXDefaultInitExpr>(Init));
6729
Richard Smith49ca8aa2013-08-06 07:09:20 +00006730 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6731 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6732 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006733 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006734 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006735 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006736 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006737 }
6738 }
6739
Richard Smith253c2a32012-01-27 01:14:48 +00006740 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006741}
6742
Richard Smithb8348f52016-05-12 22:16:28 +00006743bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6744 QualType T) {
6745 // Note that E's type is not necessarily the type of our class here; we might
6746 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006747 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006748 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6749
Richard Smithfddd3842011-12-30 21:15:51 +00006750 bool ZeroInit = E->requiresZeroInitialization();
6751 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006752 // If we've already performed zero-initialization, we're already done.
6753 if (!Result.isUninit())
6754 return true;
6755
Richard Smithda3f4fd2014-03-05 23:32:50 +00006756 // We can get here in two different ways:
6757 // 1) We're performing value-initialization, and should zero-initialize
6758 // the object, or
6759 // 2) We're performing default-initialization of an object with a trivial
6760 // constexpr default constructor, in which case we should start the
6761 // lifetimes of all the base subobjects (there can be no data member
6762 // subobjects in this case) per [basic.life]p1.
6763 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006764 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006765 }
6766
Craig Topper36250ad2014-05-12 05:36:57 +00006767 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006768 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006769
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006770 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006771 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006772
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006773 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006774 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006775 if (const MaterializeTemporaryExpr *ME
6776 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6777 return Visit(ME->GetTemporaryExpr());
6778
Richard Smithb8348f52016-05-12 22:16:28 +00006779 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006780 return false;
6781
Craig Topper5fc8fc22014-08-27 06:28:36 +00006782 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006783 return HandleConstructorCall(E, This, Args,
6784 cast<CXXConstructorDecl>(Definition), Info,
6785 Result);
6786}
6787
6788bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6789 const CXXInheritedCtorInitExpr *E) {
6790 if (!Info.CurrentCall) {
6791 assert(Info.checkingPotentialConstantExpression());
6792 return false;
6793 }
6794
6795 const CXXConstructorDecl *FD = E->getConstructor();
6796 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6797 return false;
6798
6799 const FunctionDecl *Definition = nullptr;
6800 auto Body = FD->getBody(Definition);
6801
6802 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6803 return false;
6804
6805 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006806 cast<CXXConstructorDecl>(Definition), Info,
6807 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006808}
6809
Richard Smithcc1b96d2013-06-12 22:31:48 +00006810bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6811 const CXXStdInitializerListExpr *E) {
6812 const ConstantArrayType *ArrayType =
6813 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6814
6815 LValue Array;
6816 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6817 return false;
6818
6819 // Get a pointer to the first element of the array.
6820 Array.addArray(Info, E, ArrayType);
6821
6822 // FIXME: Perform the checks on the field types in SemaInit.
6823 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6824 RecordDecl::field_iterator Field = Record->field_begin();
6825 if (Field == Record->field_end())
6826 return Error(E);
6827
6828 // Start pointer.
6829 if (!Field->getType()->isPointerType() ||
6830 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6831 ArrayType->getElementType()))
6832 return Error(E);
6833
6834 // FIXME: What if the initializer_list type has base classes, etc?
6835 Result = APValue(APValue::UninitStruct(), 0, 2);
6836 Array.moveInto(Result.getStructField(0));
6837
6838 if (++Field == Record->field_end())
6839 return Error(E);
6840
6841 if (Field->getType()->isPointerType() &&
6842 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6843 ArrayType->getElementType())) {
6844 // End pointer.
6845 if (!HandleLValueArrayAdjustment(Info, E, Array,
6846 ArrayType->getElementType(),
6847 ArrayType->getSize().getZExtValue()))
6848 return false;
6849 Array.moveInto(Result.getStructField(1));
6850 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6851 // Length.
6852 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6853 else
6854 return Error(E);
6855
6856 if (++Field != Record->field_end())
6857 return Error(E);
6858
6859 return true;
6860}
6861
Faisal Valic72a08c2017-01-09 03:02:53 +00006862bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6863 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6864 if (ClosureClass->isInvalidDecl()) return false;
6865
6866 if (Info.checkingPotentialConstantExpression()) return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00006867
Faisal Vali051e3a22017-02-16 04:12:21 +00006868 const size_t NumFields =
6869 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006870
6871 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6872 E->capture_init_end()) &&
6873 "The number of lambda capture initializers should equal the number of "
6874 "fields within the closure type");
6875
Faisal Vali051e3a22017-02-16 04:12:21 +00006876 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6877 // Iterate through all the lambda's closure object's fields and initialize
6878 // them.
6879 auto *CaptureInitIt = E->capture_init_begin();
6880 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6881 bool Success = true;
6882 for (const auto *Field : ClosureClass->fields()) {
6883 assert(CaptureInitIt != E->capture_init_end());
6884 // Get the initializer for this field
6885 Expr *const CurFieldInit = *CaptureInitIt++;
Fangrui Song6907ce22018-07-30 19:24:48 +00006886
Faisal Vali051e3a22017-02-16 04:12:21 +00006887 // If there is no initializer, either this is a VLA or an error has
6888 // occurred.
6889 if (!CurFieldInit)
6890 return Error(E);
6891
6892 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6893 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6894 if (!Info.keepEvaluatingAfterFailure())
6895 return false;
6896 Success = false;
6897 }
6898 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006899 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006900 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006901}
6902
Richard Smithd62306a2011-11-10 06:34:14 +00006903static bool EvaluateRecord(const Expr *E, const LValue &This,
6904 APValue &Result, EvalInfo &Info) {
6905 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006906 "can't evaluate expression as a record rvalue");
6907 return RecordExprEvaluator(Info, This, Result).Visit(E);
6908}
6909
6910//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006911// Temporary Evaluation
6912//
6913// Temporaries are represented in the AST as rvalues, but generally behave like
6914// lvalues. The full-object of which the temporary is a subobject is implicitly
6915// materialized so that a reference can bind to it.
6916//===----------------------------------------------------------------------===//
6917namespace {
6918class TemporaryExprEvaluator
6919 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6920public:
6921 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006922 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006923
6924 /// Visit an expression which constructs the value of this temporary.
6925 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006926 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6927 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006928 }
6929
6930 bool VisitCastExpr(const CastExpr *E) {
6931 switch (E->getCastKind()) {
6932 default:
6933 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6934
6935 case CK_ConstructorConversion:
6936 return VisitConstructExpr(E->getSubExpr());
6937 }
6938 }
6939 bool VisitInitListExpr(const InitListExpr *E) {
6940 return VisitConstructExpr(E);
6941 }
6942 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6943 return VisitConstructExpr(E);
6944 }
6945 bool VisitCallExpr(const CallExpr *E) {
6946 return VisitConstructExpr(E);
6947 }
Richard Smith513955c2014-12-17 19:24:30 +00006948 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6949 return VisitConstructExpr(E);
6950 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006951 bool VisitLambdaExpr(const LambdaExpr *E) {
6952 return VisitConstructExpr(E);
6953 }
Richard Smith027bf112011-11-17 22:56:20 +00006954};
6955} // end anonymous namespace
6956
6957/// Evaluate an expression of record type as a temporary.
6958static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006959 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006960 return TemporaryExprEvaluator(Info, Result).Visit(E);
6961}
6962
6963//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006964// Vector Evaluation
6965//===----------------------------------------------------------------------===//
6966
6967namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006968 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006969 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006970 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006971 public:
Mike Stump11289f42009-09-09 15:08:12 +00006972
Richard Smith2d406342011-10-22 21:10:00 +00006973 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6974 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006975
Craig Topper9798b932015-09-29 04:30:05 +00006976 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006977 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6978 // FIXME: remove this APValue copy.
6979 Result = APValue(V.data(), V.size());
6980 return true;
6981 }
Richard Smith2e312c82012-03-03 22:46:17 +00006982 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006983 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006984 Result = V;
6985 return true;
6986 }
Richard Smithfddd3842011-12-30 21:15:51 +00006987 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006988
Richard Smith2d406342011-10-22 21:10:00 +00006989 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006990 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006991 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006992 bool VisitInitListExpr(const InitListExpr *E);
6993 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006994 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006995 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006996 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006997 };
6998} // end anonymous namespace
6999
7000static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007001 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00007002 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007003}
7004
George Burgess IV533ff002015-12-11 00:23:35 +00007005bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007006 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00007007 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007008
Richard Smith161f09a2011-12-06 22:44:34 +00007009 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00007010 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007011
Eli Friedmanc757de22011-03-25 00:43:55 +00007012 switch (E->getCastKind()) {
7013 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00007014 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00007015 if (SETy->isIntegerType()) {
7016 APSInt IntResult;
7017 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00007018 return false;
7019 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00007020 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00007021 APFloat FloatResult(0.0);
7022 if (!EvaluateFloat(SE, FloatResult, Info))
7023 return false;
7024 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00007025 } else {
Richard Smith2d406342011-10-22 21:10:00 +00007026 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007027 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00007028
7029 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00007030 SmallVector<APValue, 4> Elts(NElts, Val);
7031 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00007032 }
Eli Friedman803acb32011-12-22 03:51:45 +00007033 case CK_BitCast: {
7034 // Evaluate the operand into an APInt we can extract from.
7035 llvm::APInt SValInt;
7036 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
7037 return false;
7038 // Extract the elements
7039 QualType EltTy = VTy->getElementType();
7040 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
7041 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7042 SmallVector<APValue, 4> Elts;
7043 if (EltTy->isRealFloatingType()) {
7044 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00007045 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00007046 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00007047 FloatEltSize = 80;
7048 for (unsigned i = 0; i < NElts; i++) {
7049 llvm::APInt Elt;
7050 if (BigEndian)
7051 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
7052 else
7053 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00007054 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00007055 }
7056 } else if (EltTy->isIntegerType()) {
7057 for (unsigned i = 0; i < NElts; i++) {
7058 llvm::APInt Elt;
7059 if (BigEndian)
7060 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
7061 else
7062 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
7063 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
7064 }
7065 } else {
7066 return Error(E);
7067 }
7068 return Success(Elts, E);
7069 }
Eli Friedmanc757de22011-03-25 00:43:55 +00007070 default:
Richard Smith11562c52011-10-28 17:51:58 +00007071 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007072 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007073}
7074
Richard Smith2d406342011-10-22 21:10:00 +00007075bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007076VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007077 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007078 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00007079 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00007080
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007081 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007082 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007083
Eli Friedmanb9c71292012-01-03 23:24:20 +00007084 // The number of initializers can be less than the number of
7085 // vector elements. For OpenCL, this can be due to nested vector
Fangrui Song6907ce22018-07-30 19:24:48 +00007086 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00007087 // should be initialized with zeroes.
7088 unsigned CountInits = 0, CountElts = 0;
7089 while (CountElts < NumElements) {
7090 // Handle nested vector initialization.
Fangrui Song6907ce22018-07-30 19:24:48 +00007091 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00007092 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00007093 APValue v;
7094 if (!EvaluateVector(E->getInit(CountInits), v, Info))
7095 return Error(E);
7096 unsigned vlen = v.getVectorLength();
Fangrui Song6907ce22018-07-30 19:24:48 +00007097 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00007098 Elements.push_back(v.getVectorElt(j));
7099 CountElts += vlen;
7100 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007101 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007102 if (CountInits < NumInits) {
7103 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007104 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007105 } else // trailing integer zero.
7106 sInt = Info.Ctx.MakeIntValue(0, EltTy);
7107 Elements.push_back(APValue(sInt));
7108 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007109 } else {
7110 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00007111 if (CountInits < NumInits) {
7112 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00007113 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00007114 } else // trailing float zero.
7115 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7116 Elements.push_back(APValue(f));
7117 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00007118 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00007119 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007120 }
Richard Smith2d406342011-10-22 21:10:00 +00007121 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007122}
7123
Richard Smith2d406342011-10-22 21:10:00 +00007124bool
Richard Smithfddd3842011-12-30 21:15:51 +00007125VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00007126 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00007127 QualType EltTy = VT->getElementType();
7128 APValue ZeroElement;
7129 if (EltTy->isIntegerType())
7130 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7131 else
7132 ZeroElement =
7133 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7134
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007135 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00007136 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007137}
7138
Richard Smith2d406342011-10-22 21:10:00 +00007139bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00007140 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00007141 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00007142}
7143
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00007144//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00007145// Array Evaluation
7146//===----------------------------------------------------------------------===//
7147
7148namespace {
7149 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007150 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00007151 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00007152 APValue &Result;
7153 public:
7154
Richard Smithd62306a2011-11-10 06:34:14 +00007155 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7156 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00007157
7158 bool Success(const APValue &V, const Expr *E) {
Eli Friedman3bf72d72019-02-08 21:18:46 +00007159 assert(V.isArray() && "expected array");
Richard Smithf3e9e432011-11-07 09:22:26 +00007160 Result = V;
7161 return true;
7162 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007163
Richard Smithfddd3842011-12-30 21:15:51 +00007164 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00007165 const ConstantArrayType *CAT =
7166 Info.Ctx.getAsConstantArrayType(E->getType());
7167 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007168 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00007169
7170 Result = APValue(APValue::UninitArray(), 0,
7171 CAT->getSize().getZExtValue());
7172 if (!Result.hasArrayFiller()) return true;
7173
Richard Smithfddd3842011-12-30 21:15:51 +00007174 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00007175 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007176 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00007177 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00007178 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00007179 }
7180
Richard Smith52a980a2015-08-28 02:43:42 +00007181 bool VisitCallExpr(const CallExpr *E) {
7182 return handleCallExpr(E, Result, &This);
7183 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007184 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00007185 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00007186 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00007187 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7188 const LValue &Subobject,
7189 APValue *Value, QualType Type);
Eli Friedman3bf72d72019-02-08 21:18:46 +00007190 bool VisitStringLiteral(const StringLiteral *E) {
7191 expandStringLiteral(Info, E, Result);
7192 return true;
7193 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007194 };
7195} // end anonymous namespace
7196
Richard Smithd62306a2011-11-10 06:34:14 +00007197static bool EvaluateArray(const Expr *E, const LValue &This,
7198 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00007199 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00007200 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007201}
7202
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007203// Return true iff the given array filler may depend on the element index.
7204static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7205 // For now, just whitelist non-class value-initialization and initialization
7206 // lists comprised of them.
7207 if (isa<ImplicitValueInitExpr>(FillerExpr))
7208 return false;
7209 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7210 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7211 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7212 return true;
7213 }
7214 return false;
7215 }
7216 return true;
7217}
7218
Richard Smithf3e9e432011-11-07 09:22:26 +00007219bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7220 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7221 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007222 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00007223
Richard Smithca2cfbf2011-12-22 01:07:19 +00007224 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7225 // an appropriately-typed string literal enclosed in braces.
Eli Friedman3bf72d72019-02-08 21:18:46 +00007226 if (E->isStringLiteralInit())
7227 return Visit(E->getInit(0));
Richard Smithca2cfbf2011-12-22 01:07:19 +00007228
Richard Smith253c2a32012-01-27 01:14:48 +00007229 bool Success = true;
7230
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007231 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7232 "zero-initialized array shouldn't have any initialized elts");
7233 APValue Filler;
7234 if (Result.isArray() && Result.hasArrayFiller())
7235 Filler = Result.getArrayFiller();
7236
Richard Smith9543c5e2013-04-22 14:44:29 +00007237 unsigned NumEltsToInit = E->getNumInits();
7238 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00007239 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00007240
7241 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007242 // array element.
7243 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00007244 NumEltsToInit = NumElts;
7245
Nicola Zaghen3538b392018-05-15 13:30:56 +00007246 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7247 << NumEltsToInit << ".\n");
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00007248
Richard Smith9543c5e2013-04-22 14:44:29 +00007249 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007250
7251 // If the array was previously zero-initialized, preserve the
7252 // zero-initialized values.
7253 if (!Filler.isUninit()) {
7254 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7255 Result.getArrayInitializedElt(I) = Filler;
7256 if (Result.hasArrayFiller())
7257 Result.getArrayFiller() = Filler;
7258 }
7259
Richard Smithd62306a2011-11-10 06:34:14 +00007260 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00007261 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00007262 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7263 const Expr *Init =
7264 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00007265 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00007266 Info, Subobject, Init) ||
7267 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00007268 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00007269 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00007270 return false;
7271 Success = false;
7272 }
Richard Smithd62306a2011-11-10 06:34:14 +00007273 }
Richard Smithf3e9e432011-11-07 09:22:26 +00007274
Richard Smith9543c5e2013-04-22 14:44:29 +00007275 if (!Result.hasArrayFiller())
7276 return Success;
7277
7278 // If we get here, we have a trivial filler, which we can just evaluate
7279 // once and splat over the rest of the array elements.
7280 assert(FillerExpr && "no array filler for incomplete init list");
7281 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7282 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00007283}
7284
Richard Smith410306b2016-12-12 02:53:20 +00007285bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7286 if (E->getCommonExpr() &&
7287 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7288 Info, E->getCommonExpr()->getSourceExpr()))
7289 return false;
7290
7291 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7292
7293 uint64_t Elements = CAT->getSize().getZExtValue();
7294 Result = APValue(APValue::UninitArray(), Elements, Elements);
7295
7296 LValue Subobject = This;
7297 Subobject.addArray(Info, E, CAT);
7298
7299 bool Success = true;
7300 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7301 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7302 Info, Subobject, E->getSubExpr()) ||
7303 !HandleLValueArrayAdjustment(Info, E, Subobject,
7304 CAT->getElementType(), 1)) {
7305 if (!Info.noteFailure())
7306 return false;
7307 Success = false;
7308 }
7309 }
7310
7311 return Success;
7312}
7313
Richard Smith027bf112011-11-17 22:56:20 +00007314bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00007315 return VisitCXXConstructExpr(E, This, &Result, E->getType());
7316}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007317
Richard Smith9543c5e2013-04-22 14:44:29 +00007318bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7319 const LValue &Subobject,
7320 APValue *Value,
7321 QualType Type) {
7322 bool HadZeroInit = !Value->isUninit();
7323
7324 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7325 unsigned N = CAT->getSize().getZExtValue();
7326
7327 // Preserve the array filler if we had prior zero-initialization.
7328 APValue Filler =
7329 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7330 : APValue();
7331
7332 *Value = APValue(APValue::UninitArray(), N, N);
7333
7334 if (HadZeroInit)
7335 for (unsigned I = 0; I != N; ++I)
7336 Value->getArrayInitializedElt(I) = Filler;
7337
7338 // Initialize the elements.
7339 LValue ArrayElt = Subobject;
7340 ArrayElt.addArray(Info, E, CAT);
7341 for (unsigned I = 0; I != N; ++I)
7342 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7343 CAT->getElementType()) ||
7344 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7345 CAT->getElementType(), 1))
7346 return false;
7347
7348 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007349 }
Richard Smith027bf112011-11-17 22:56:20 +00007350
Richard Smith9543c5e2013-04-22 14:44:29 +00007351 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00007352 return Error(E);
7353
Richard Smithb8348f52016-05-12 22:16:28 +00007354 return RecordExprEvaluator(Info, Subobject, *Value)
7355 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00007356}
7357
Richard Smithf3e9e432011-11-07 09:22:26 +00007358//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007359// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007360//
7361// As a GNU extension, we support casting pointers to sufficiently-wide integer
7362// types and back in constant folding. Integer values are thus represented
7363// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00007364//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007365
7366namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007367class IntExprEvaluator
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007368 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00007369 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007370public:
Richard Smith2e312c82012-03-03 22:46:17 +00007371 IntExprEvaluator(EvalInfo &info, APValue &result)
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007372 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007373
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007374 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007375 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007376 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007377 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007378 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007379 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007380 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007381 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007382 return true;
7383 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007384 bool Success(const llvm::APSInt &SI, const Expr *E) {
7385 return Success(SI, E, Result);
7386 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007387
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007388 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007389 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007390 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007391 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007392 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007393 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007394 Result.getInt().setIsUnsigned(
7395 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007396 return true;
7397 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007398 bool Success(const llvm::APInt &I, const Expr *E) {
7399 return Success(I, E, Result);
7400 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007401
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007402 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00007403 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007404 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007405 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007406 return true;
7407 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007408 bool Success(uint64_t Value, const Expr *E) {
7409 return Success(Value, E, Result);
7410 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007411
Ken Dyckdbc01912011-03-11 02:13:43 +00007412 bool Success(CharUnits Size, const Expr *E) {
7413 return Success(Size.getQuantity(), E);
7414 }
7415
Richard Smith2e312c82012-03-03 22:46:17 +00007416 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007417 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007418 Result = V;
7419 return true;
7420 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007421 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007422 }
Mike Stump11289f42009-09-09 15:08:12 +00007423
Richard Smithfddd3842011-12-30 21:15:51 +00007424 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007425
Peter Collingbournee9200682011-05-13 03:29:01 +00007426 //===--------------------------------------------------------------------===//
7427 // Visitor Methods
7428 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007429
Fangrui Song407659a2018-11-30 23:41:18 +00007430 bool VisitConstantExpr(const ConstantExpr *E);
7431
Chris Lattner7174bf32008-07-12 00:38:25 +00007432 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007433 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007434 }
7435 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007436 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007437 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007438
7439 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7440 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007441 if (CheckReferencedDecl(E, E->getDecl()))
7442 return true;
7443
7444 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007445 }
7446 bool VisitMemberExpr(const MemberExpr *E) {
7447 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007448 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007449 return true;
7450 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007451
7452 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007453 }
7454
Peter Collingbournee9200682011-05-13 03:29:01 +00007455 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007456 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007457 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007458 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007459 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007460
Peter Collingbournee9200682011-05-13 03:29:01 +00007461 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007462 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007463
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007464 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007465 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007466 }
Mike Stump11289f42009-09-09 15:08:12 +00007467
Ted Kremeneke65b0862012-03-06 20:05:56 +00007468 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7469 return Success(E->getValue(), E);
7470 }
Richard Smith410306b2016-12-12 02:53:20 +00007471
7472 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7473 if (Info.ArrayInitIndex == uint64_t(-1)) {
7474 // We were asked to evaluate this subexpression independent of the
7475 // enclosing ArrayInitLoopExpr. We can't do that.
7476 Info.FFDiag(E);
7477 return false;
7478 }
7479 return Success(Info.ArrayInitIndex, E);
7480 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007481
Richard Smith4ce706a2011-10-11 21:43:33 +00007482 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007483 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007484 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007485 }
7486
Douglas Gregor29c42f22012-02-24 07:38:34 +00007487 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7488 return Success(E->getValue(), E);
7489 }
7490
John Wiegley6242b6a2011-04-28 00:16:57 +00007491 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7492 return Success(E->getValue(), E);
7493 }
7494
John Wiegleyf9f65842011-04-25 06:54:41 +00007495 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7496 return Success(E->getValue(), E);
7497 }
7498
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007499 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007500 bool VisitUnaryImag(const UnaryOperator *E);
7501
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007502 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007503 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007504
Eli Friedman4e7a2412009-02-27 04:45:43 +00007505 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007506};
Leonard Chandb01c3a2018-06-20 17:19:40 +00007507
7508class FixedPointExprEvaluator
7509 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
7510 APValue &Result;
7511
7512 public:
7513 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
7514 : ExprEvaluatorBaseTy(info), Result(result) {}
7515
Leonard Chandb01c3a2018-06-20 17:19:40 +00007516 bool Success(const llvm::APInt &I, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00007517 return Success(
7518 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00007519 }
7520
Leonard Chandb01c3a2018-06-20 17:19:40 +00007521 bool Success(uint64_t Value, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00007522 return Success(
7523 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00007524 }
7525
7526 bool Success(const APValue &V, const Expr *E) {
Leonard Chand3f3e162019-01-18 21:04:25 +00007527 return Success(V.getFixedPoint(), E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00007528 }
7529
Leonard Chand3f3e162019-01-18 21:04:25 +00007530 bool Success(const APFixedPoint &V, const Expr *E) {
7531 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7532 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7533 "Invalid evaluation result.");
7534 Result = APValue(V);
7535 return true;
7536 }
Leonard Chandb01c3a2018-06-20 17:19:40 +00007537
7538 //===--------------------------------------------------------------------===//
7539 // Visitor Methods
7540 //===--------------------------------------------------------------------===//
7541
7542 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
7543 return Success(E->getValue(), E);
7544 }
7545
Leonard Chand3f3e162019-01-18 21:04:25 +00007546 bool VisitCastExpr(const CastExpr *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00007547 bool VisitUnaryOperator(const UnaryOperator *E);
Leonard Chand3f3e162019-01-18 21:04:25 +00007548 bool VisitBinaryOperator(const BinaryOperator *E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00007549};
Chris Lattner05706e882008-07-11 18:11:29 +00007550} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007551
Richard Smith11562c52011-10-28 17:51:58 +00007552/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7553/// produce either the integer value or a pointer.
7554///
7555/// GCC has a heinous extension which folds casts between pointer types and
7556/// pointer-sized integral types. We support this by allowing the evaluation of
7557/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7558/// Some simple arithmetic on such values is supported (they are treated much
7559/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007560static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007561 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007562 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007563 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007564}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007565
Richard Smithf57d8cb2011-12-09 22:58:01 +00007566static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007567 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007568 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007569 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007570 if (!Val.isInt()) {
7571 // FIXME: It would be better to produce the diagnostic for casting
7572 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007573 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007574 return false;
7575 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007576 Result = Val.getInt();
7577 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007578}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007579
Leonard Chand3f3e162019-01-18 21:04:25 +00007580static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
7581 EvalInfo &Info) {
7582 if (E->getType()->isFixedPointType()) {
7583 APValue Val;
7584 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
7585 return false;
7586 if (!Val.isFixedPoint())
7587 return false;
7588
7589 Result = Val.getFixedPoint();
7590 return true;
7591 }
7592 return false;
7593}
7594
7595static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
7596 EvalInfo &Info) {
7597 if (E->getType()->isIntegerType()) {
7598 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
7599 APSInt Val;
7600 if (!EvaluateInteger(E, Val, Info))
7601 return false;
7602 Result = APFixedPoint(Val, FXSema);
7603 return true;
7604 } else if (E->getType()->isFixedPointType()) {
7605 return EvaluateFixedPoint(E, Result, Info);
7606 }
7607 return false;
7608}
7609
Richard Smithf57d8cb2011-12-09 22:58:01 +00007610/// Check whether the given declaration can be directly converted to an integral
7611/// rvalue. If not, no diagnostic is produced; there are other things we can
7612/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007613bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007614 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007615 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007616 // Check for signedness/width mismatches between E type and ECD value.
7617 bool SameSign = (ECD->getInitVal().isSigned()
7618 == E->getType()->isSignedIntegerOrEnumerationType());
7619 bool SameWidth = (ECD->getInitVal().getBitWidth()
7620 == Info.Ctx.getIntWidth(E->getType()));
7621 if (SameSign && SameWidth)
7622 return Success(ECD->getInitVal(), E);
7623 else {
7624 // Get rid of mismatch (otherwise Success assertions will fail)
7625 // by computing a new value matching the type of E.
7626 llvm::APSInt Val = ECD->getInitVal();
7627 if (!SameSign)
7628 Val.setIsSigned(!ECD->getInitVal().isSigned());
7629 if (!SameWidth)
7630 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7631 return Success(Val, E);
7632 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007633 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007634 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007635}
7636
Richard Smith08b682b2018-05-23 21:18:00 +00007637/// Values returned by __builtin_classify_type, chosen to match the values
7638/// produced by GCC's builtin.
7639enum class GCCTypeClass {
7640 None = -1,
7641 Void = 0,
7642 Integer = 1,
7643 // GCC reserves 2 for character types, but instead classifies them as
7644 // integers.
7645 Enum = 3,
7646 Bool = 4,
7647 Pointer = 5,
7648 // GCC reserves 6 for references, but appears to never use it (because
7649 // expressions never have reference type, presumably).
7650 PointerToDataMember = 7,
7651 RealFloat = 8,
7652 Complex = 9,
7653 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7654 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7655 // GCC claims to reserve 11 for pointers to member functions, but *actually*
7656 // uses 12 for that purpose, same as for a class or struct. Maybe it
7657 // internally implements a pointer to member as a struct? Who knows.
7658 PointerToMemberFunction = 12, // Not a bug, see above.
7659 ClassOrStruct = 12,
7660 Union = 13,
7661 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7662 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7663 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7664 // literals.
7665};
7666
Chris Lattner86ee2862008-10-06 06:40:35 +00007667/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7668/// as GCC.
Richard Smith08b682b2018-05-23 21:18:00 +00007669static GCCTypeClass
7670EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7671 assert(!T->isDependentType() && "unexpected dependent type");
Mike Stump11289f42009-09-09 15:08:12 +00007672
Richard Smith08b682b2018-05-23 21:18:00 +00007673 QualType CanTy = T.getCanonicalType();
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007674 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7675
7676 switch (CanTy->getTypeClass()) {
7677#define TYPE(ID, BASE)
7678#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7679#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7680#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7681#include "clang/AST/TypeNodes.def"
Richard Smith08b682b2018-05-23 21:18:00 +00007682 case Type::Auto:
7683 case Type::DeducedTemplateSpecialization:
7684 llvm_unreachable("unexpected non-canonical or dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007685
7686 case Type::Builtin:
7687 switch (BT->getKind()) {
7688#define BUILTIN_TYPE(ID, SINGLETON_ID)
Richard Smith08b682b2018-05-23 21:18:00 +00007689#define SIGNED_TYPE(ID, SINGLETON_ID) \
7690 case BuiltinType::ID: return GCCTypeClass::Integer;
7691#define FLOATING_TYPE(ID, SINGLETON_ID) \
7692 case BuiltinType::ID: return GCCTypeClass::RealFloat;
7693#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7694 case BuiltinType::ID: break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007695#include "clang/AST/BuiltinTypes.def"
7696 case BuiltinType::Void:
Richard Smith08b682b2018-05-23 21:18:00 +00007697 return GCCTypeClass::Void;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007698
7699 case BuiltinType::Bool:
Richard Smith08b682b2018-05-23 21:18:00 +00007700 return GCCTypeClass::Bool;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007701
Richard Smith08b682b2018-05-23 21:18:00 +00007702 case BuiltinType::Char_U:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007703 case BuiltinType::UChar:
Richard Smith08b682b2018-05-23 21:18:00 +00007704 case BuiltinType::WChar_U:
7705 case BuiltinType::Char8:
7706 case BuiltinType::Char16:
7707 case BuiltinType::Char32:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007708 case BuiltinType::UShort:
7709 case BuiltinType::UInt:
7710 case BuiltinType::ULong:
7711 case BuiltinType::ULongLong:
7712 case BuiltinType::UInt128:
Richard Smith08b682b2018-05-23 21:18:00 +00007713 return GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007714
Leonard Chanf921d852018-06-04 16:07:52 +00007715 case BuiltinType::UShortAccum:
7716 case BuiltinType::UAccum:
7717 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00007718 case BuiltinType::UShortFract:
7719 case BuiltinType::UFract:
7720 case BuiltinType::ULongFract:
7721 case BuiltinType::SatUShortAccum:
7722 case BuiltinType::SatUAccum:
7723 case BuiltinType::SatULongAccum:
7724 case BuiltinType::SatUShortFract:
7725 case BuiltinType::SatUFract:
7726 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00007727 return GCCTypeClass::None;
7728
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007729 case BuiltinType::NullPtr:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007730
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007731 case BuiltinType::ObjCId:
7732 case BuiltinType::ObjCClass:
7733 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007734#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7735 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007736#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00007737#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7738 case BuiltinType::Id:
7739#include "clang/Basic/OpenCLExtensionTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007740 case BuiltinType::OCLSampler:
7741 case BuiltinType::OCLEvent:
7742 case BuiltinType::OCLClkEvent:
7743 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007744 case BuiltinType::OCLReserveID:
Richard Smith08b682b2018-05-23 21:18:00 +00007745 return GCCTypeClass::None;
7746
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007747 case BuiltinType::Dependent:
Richard Smith08b682b2018-05-23 21:18:00 +00007748 llvm_unreachable("unexpected dependent type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007749 };
Richard Smith08b682b2018-05-23 21:18:00 +00007750 llvm_unreachable("unexpected placeholder type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007751
7752 case Type::Enum:
Richard Smith08b682b2018-05-23 21:18:00 +00007753 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007754
7755 case Type::Pointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007756 case Type::ConstantArray:
7757 case Type::VariableArray:
7758 case Type::IncompleteArray:
Richard Smith08b682b2018-05-23 21:18:00 +00007759 case Type::FunctionNoProto:
7760 case Type::FunctionProto:
7761 return GCCTypeClass::Pointer;
7762
7763 case Type::MemberPointer:
7764 return CanTy->isMemberDataPointerType()
7765 ? GCCTypeClass::PointerToDataMember
7766 : GCCTypeClass::PointerToMemberFunction;
7767
7768 case Type::Complex:
7769 return GCCTypeClass::Complex;
7770
7771 case Type::Record:
7772 return CanTy->isUnionType() ? GCCTypeClass::Union
7773 : GCCTypeClass::ClassOrStruct;
7774
7775 case Type::Atomic:
7776 // GCC classifies _Atomic T the same as T.
7777 return EvaluateBuiltinClassifyType(
7778 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007779
7780 case Type::BlockPointer:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007781 case Type::Vector:
7782 case Type::ExtVector:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007783 case Type::ObjCObject:
7784 case Type::ObjCInterface:
7785 case Type::ObjCObjectPointer:
7786 case Type::Pipe:
Richard Smith08b682b2018-05-23 21:18:00 +00007787 // GCC classifies vectors as None. We follow its lead and classify all
7788 // other types that don't fit into the regular classification the same way.
7789 return GCCTypeClass::None;
7790
7791 case Type::LValueReference:
7792 case Type::RValueReference:
7793 llvm_unreachable("invalid type for expression");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007794 }
7795
Richard Smith08b682b2018-05-23 21:18:00 +00007796 llvm_unreachable("unexpected type class");
7797}
7798
7799/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7800/// as GCC.
7801static GCCTypeClass
7802EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7803 // If no argument was supplied, default to None. This isn't
7804 // ideal, however it is what gcc does.
7805 if (E->getNumArgs() == 0)
7806 return GCCTypeClass::None;
7807
7808 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7809 // being an ICE, but still folds it to a constant using the type of the first
7810 // argument.
7811 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
Chris Lattner86ee2862008-10-06 06:40:35 +00007812}
7813
Richard Smith5fab0c92011-12-28 19:48:30 +00007814/// EvaluateBuiltinConstantPForLValue - Determine the result of
Richard Smith31cfb312019-04-27 02:58:17 +00007815/// __builtin_constant_p when applied to the given pointer.
Richard Smith5fab0c92011-12-28 19:48:30 +00007816///
Richard Smith31cfb312019-04-27 02:58:17 +00007817/// A pointer is only "constant" if it is null (or a pointer cast to integer)
7818/// or it points to the first character of a string literal.
7819static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
7820 APValue::LValueBase Base = LV.getLValueBase();
7821 if (Base.isNull()) {
7822 // A null base is acceptable.
7823 return true;
7824 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
7825 if (!isa<StringLiteral>(E))
7826 return false;
7827 return LV.getLValueOffset().isZero();
7828 } else {
7829 // Any other base is not constant enough for GCC.
7830 return false;
7831 }
Richard Smith5fab0c92011-12-28 19:48:30 +00007832}
7833
7834/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7835/// GCC as we can manage.
Richard Smith31cfb312019-04-27 02:58:17 +00007836static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
Richard Smith37be3362019-05-04 04:00:45 +00007837 // This evaluation is not permitted to have side-effects, so evaluate it in
7838 // a speculative evaluation context.
7839 SpeculativeEvaluationRAII SpeculativeEval(Info);
7840
Richard Smith31cfb312019-04-27 02:58:17 +00007841 // Constant-folding is always enabled for the operand of __builtin_constant_p
7842 // (even when the enclosing evaluation context otherwise requires a strict
7843 // language-specific constant expression).
7844 FoldConstant Fold(Info, true);
7845
Richard Smith5fab0c92011-12-28 19:48:30 +00007846 QualType ArgType = Arg->getType();
7847
7848 // __builtin_constant_p always has one operand. The rules which gcc follows
7849 // are not precisely documented, but are as follows:
7850 //
7851 // - If the operand is of integral, floating, complex or enumeration type,
7852 // and can be folded to a known value of that type, it returns 1.
Richard Smith31cfb312019-04-27 02:58:17 +00007853 // - If the operand can be folded to a pointer to the first character
7854 // of a string literal (or such a pointer cast to an integral type)
7855 // or to a null pointer or an integer cast to a pointer, it returns 1.
Richard Smith5fab0c92011-12-28 19:48:30 +00007856 //
7857 // Otherwise, it returns 0.
7858 //
7859 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
Richard Smith31cfb312019-04-27 02:58:17 +00007860 // its support for this did not work prior to GCC 9 and is not yet well
7861 // understood.
7862 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
7863 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
7864 ArgType->isNullPtrType()) {
7865 APValue V;
7866 if (!::EvaluateAsRValue(Info, Arg, V)) {
7867 Fold.keepDiagnostics();
Richard Smith5fab0c92011-12-28 19:48:30 +00007868 return false;
Richard Smith31cfb312019-04-27 02:58:17 +00007869 }
Richard Smith5fab0c92011-12-28 19:48:30 +00007870
Richard Smith31cfb312019-04-27 02:58:17 +00007871 // For a pointer (possibly cast to integer), there are special rules.
Richard Smith0c6124b2015-12-03 01:36:22 +00007872 if (V.getKind() == APValue::LValue)
7873 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith31cfb312019-04-27 02:58:17 +00007874
7875 // Otherwise, any constant value is good enough.
7876 return V.getKind() != APValue::Uninitialized;
Richard Smith5fab0c92011-12-28 19:48:30 +00007877 }
7878
7879 // Anything else isn't considered to be sufficiently constant.
7880 return false;
7881}
7882
John McCall95007602010-05-10 23:27:23 +00007883/// Retrieves the "underlying object type" of the given expression,
7884/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007885static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007886 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7887 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007888 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007889 } else if (const Expr *E = B.get<const Expr*>()) {
7890 if (isa<CompoundLiteralExpr>(E))
7891 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007892 }
7893
7894 return QualType();
7895}
7896
George Burgess IV3a03fab2015-09-04 21:28:13 +00007897/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007898/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007899/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007900/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7901///
7902/// Always returns an RValue with a pointer representation.
7903static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7904 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7905
7906 auto *NoParens = E->IgnoreParens();
7907 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007908 if (Cast == nullptr)
7909 return NoParens;
7910
7911 // We only conservatively allow a few kinds of casts, because this code is
7912 // inherently a simple solution that seeks to support the common case.
7913 auto CastKind = Cast->getCastKind();
7914 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7915 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007916 return NoParens;
7917
7918 auto *SubExpr = Cast->getSubExpr();
7919 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7920 return NoParens;
7921 return ignorePointerCastsAndParens(SubExpr);
7922}
7923
George Burgess IVa51c4072015-10-16 01:49:01 +00007924/// Checks to see if the given LValue's Designator is at the end of the LValue's
7925/// record layout. e.g.
7926/// struct { struct { int a, b; } fst, snd; } obj;
7927/// obj.fst // no
7928/// obj.snd // yes
7929/// obj.fst.a // no
7930/// obj.fst.b // no
7931/// obj.snd.a // no
7932/// obj.snd.b // yes
7933///
7934/// Please note: this function is specialized for how __builtin_object_size
7935/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007936///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007937/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7938/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007939static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7940 assert(!LVal.Designator.Invalid);
7941
George Burgess IV4168d752016-06-27 19:40:41 +00007942 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7943 const RecordDecl *Parent = FD->getParent();
7944 Invalid = Parent->isInvalidDecl();
7945 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007946 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007947 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007948 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7949 };
7950
7951 auto &Base = LVal.getLValueBase();
7952 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7953 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007954 bool Invalid;
7955 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7956 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007957 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007958 for (auto *FD : IFD->chain()) {
7959 bool Invalid;
7960 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7961 return Invalid;
7962 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007963 }
7964 }
7965
George Burgess IVe3763372016-12-22 02:50:20 +00007966 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007967 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007968 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007969 // If we don't know the array bound, conservatively assume we're looking at
7970 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007971 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007972 if (BaseType->isIncompleteArrayType())
7973 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7974 else
7975 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007976 }
7977
7978 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7979 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007980 if (BaseType->isArrayType()) {
7981 // Because __builtin_object_size treats arrays as objects, we can ignore
7982 // the index iff this is the last array in the Designator.
7983 if (I + 1 == E)
7984 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007985 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7986 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007987 if (Index + 1 != CAT->getSize())
7988 return false;
7989 BaseType = CAT->getElementType();
7990 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007991 const auto *CT = BaseType->castAs<ComplexType>();
7992 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007993 if (Index != 1)
7994 return false;
7995 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007996 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007997 bool Invalid;
7998 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7999 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00008000 BaseType = FD->getType();
8001 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00008002 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00008003 return false;
8004 }
8005 }
8006 return true;
8007}
8008
George Burgess IVe3763372016-12-22 02:50:20 +00008009/// Tests to see if the LValue has a user-specified designator (that isn't
8010/// necessarily valid). Note that this always returns 'true' if the LValue has
8011/// an unsized array as its first designator entry, because there's currently no
8012/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00008013static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00008014 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00008015 return false;
8016
George Burgess IVe3763372016-12-22 02:50:20 +00008017 if (!LVal.Designator.Entries.empty())
8018 return LVal.Designator.isMostDerivedAnUnsizedArray();
8019
George Burgess IVa51c4072015-10-16 01:49:01 +00008020 if (!LVal.InvalidBase)
8021 return true;
8022
George Burgess IVe3763372016-12-22 02:50:20 +00008023 // If `E` is a MemberExpr, then the first part of the designator is hiding in
8024 // the LValueBase.
8025 const auto *E = LVal.Base.dyn_cast<const Expr *>();
8026 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00008027}
8028
George Burgess IVe3763372016-12-22 02:50:20 +00008029/// Attempts to detect a user writing into a piece of memory that's impossible
8030/// to figure out the size of by just using types.
8031static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
8032 const SubobjectDesignator &Designator = LVal.Designator;
8033 // Notes:
8034 // - Users can only write off of the end when we have an invalid base. Invalid
8035 // bases imply we don't know where the memory came from.
8036 // - We used to be a bit more aggressive here; we'd only be conservative if
8037 // the array at the end was flexible, or if it had 0 or 1 elements. This
8038 // broke some common standard library extensions (PR30346), but was
8039 // otherwise seemingly fine. It may be useful to reintroduce this behavior
8040 // with some sort of whitelist. OTOH, it seems that GCC is always
8041 // conservative with the last element in structs (if it's an array), so our
8042 // current behavior is more compatible than a whitelisting approach would
8043 // be.
8044 return LVal.InvalidBase &&
8045 Designator.Entries.size() == Designator.MostDerivedPathLength &&
8046 Designator.MostDerivedIsArrayElement &&
8047 isDesignatorAtObjectEnd(Ctx, LVal);
8048}
8049
8050/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
8051/// Fails if the conversion would cause loss of precision.
8052static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
8053 CharUnits &Result) {
8054 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
8055 if (Int.ugt(CharUnitsMax))
8056 return false;
8057 Result = CharUnits::fromQuantity(Int.getZExtValue());
8058 return true;
8059}
8060
8061/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
8062/// determine how many bytes exist from the beginning of the object to either
8063/// the end of the current subobject, or the end of the object itself, depending
8064/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00008065///
George Burgess IVe3763372016-12-22 02:50:20 +00008066/// If this returns false, the value of Result is undefined.
8067static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
8068 unsigned Type, const LValue &LVal,
8069 CharUnits &EndOffset) {
8070 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008071
George Burgess IV7fb7e362017-01-03 23:35:19 +00008072 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
8073 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
8074 return false;
8075 return HandleSizeof(Info, ExprLoc, Ty, Result);
8076 };
8077
George Burgess IVe3763372016-12-22 02:50:20 +00008078 // We want to evaluate the size of the entire object. This is a valid fallback
8079 // for when Type=1 and the designator is invalid, because we're asked for an
8080 // upper-bound.
8081 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
8082 // Type=3 wants a lower bound, so we can't fall back to this.
8083 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00008084 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00008085
8086 llvm::APInt APEndOffset;
8087 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8088 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8089 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8090
8091 if (LVal.InvalidBase)
8092 return false;
8093
8094 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00008095 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00008096 }
8097
George Burgess IVe3763372016-12-22 02:50:20 +00008098 // We want to evaluate the size of a subobject.
8099 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008100
8101 // The following is a moderately common idiom in C:
8102 //
8103 // struct Foo { int a; char c[1]; };
8104 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8105 // strcpy(&F->c[0], Bar);
8106 //
George Burgess IVe3763372016-12-22 02:50:20 +00008107 // In order to not break too much legacy code, we need to support it.
8108 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8109 // If we can resolve this to an alloc_size call, we can hand that back,
8110 // because we know for certain how many bytes there are to write to.
8111 llvm::APInt APEndOffset;
8112 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8113 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8114 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8115
8116 // If we cannot determine the size of the initial allocation, then we can't
8117 // given an accurate upper-bound. However, we are still able to give
8118 // conservative lower-bounds for Type=3.
8119 if (Type == 1)
8120 return false;
8121 }
8122
8123 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00008124 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008125 return false;
8126
George Burgess IVe3763372016-12-22 02:50:20 +00008127 // According to the GCC documentation, we want the size of the subobject
8128 // denoted by the pointer. But that's not quite right -- what we actually
8129 // want is the size of the immediately-enclosing array, if there is one.
8130 int64_t ElemsRemaining;
8131 if (Designator.MostDerivedIsArrayElement &&
8132 Designator.Entries.size() == Designator.MostDerivedPathLength) {
8133 uint64_t ArraySize = Designator.getMostDerivedArraySize();
8134 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
8135 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8136 } else {
8137 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8138 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008139
George Burgess IVe3763372016-12-22 02:50:20 +00008140 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8141 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00008142}
8143
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008144/// Tries to evaluate the __builtin_object_size for @p E. If successful,
George Burgess IVe3763372016-12-22 02:50:20 +00008145/// returns true and stores the result in @p Size.
8146///
8147/// If @p WasError is non-null, this will report whether the failure to evaluate
8148/// is to be treated as an Error in IntExprEvaluator.
8149static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8150 EvalInfo &Info, uint64_t &Size) {
8151 // Determine the denoted object.
8152 LValue LVal;
8153 {
8154 // The operand of __builtin_object_size is never evaluated for side-effects.
8155 // If there are any, but we can determine the pointed-to object anyway, then
8156 // ignore the side-effects.
8157 SpeculativeEvaluationRAII SpeculativeEval(Info);
James Y Knight892b09b2018-10-10 02:53:43 +00008158 IgnoreSideEffectsRAII Fold(Info);
George Burgess IVe3763372016-12-22 02:50:20 +00008159
8160 if (E->isGLValue()) {
8161 // It's possible for us to be given GLValues if we're called via
8162 // Expr::tryEvaluateObjectSize.
8163 APValue RVal;
8164 if (!EvaluateAsRValue(Info, E, RVal))
8165 return false;
8166 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00008167 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8168 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00008169 return false;
8170 }
8171
8172 // If we point to before the start of the object, there are no accessible
8173 // bytes.
8174 if (LVal.getLValueOffset().isNegative()) {
8175 Size = 0;
8176 return true;
8177 }
8178
8179 CharUnits EndOffset;
8180 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8181 return false;
8182
8183 // If we've fallen outside of the end offset, just pretend there's nothing to
8184 // write to/read from.
8185 if (EndOffset <= LVal.getLValueOffset())
8186 Size = 0;
8187 else
8188 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8189 return true;
John McCall95007602010-05-10 23:27:23 +00008190}
8191
Fangrui Song407659a2018-11-30 23:41:18 +00008192bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
8193 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
8194 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
8195}
8196
Peter Collingbournee9200682011-05-13 03:29:01 +00008197bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00008198 if (unsigned BuiltinOp = E->getBuiltinCallee())
8199 return VisitBuiltinCallExpr(E, BuiltinOp);
8200
8201 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8202}
8203
8204bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8205 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00008206 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008207 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00008208 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00008209
Erik Pilkington9c3b5882019-01-30 20:34:53 +00008210 case Builtin::BI__builtin_dynamic_object_size:
Mike Stump722cedf2009-10-26 18:35:08 +00008211 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00008212 // The type was checked when we built the expression.
8213 unsigned Type =
8214 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8215 assert(Type <= 3 && "unexpected type");
8216
George Burgess IVe3763372016-12-22 02:50:20 +00008217 uint64_t Size;
8218 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8219 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00008220
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008221 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00008222 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00008223
Richard Smith01ade172012-05-23 04:13:20 +00008224 // Expression had no side effects, but we couldn't statically determine the
8225 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008226 switch (Info.EvalMode) {
8227 case EvalInfo::EM_ConstantExpression:
8228 case EvalInfo::EM_PotentialConstantExpression:
8229 case EvalInfo::EM_ConstantFold:
8230 case EvalInfo::EM_EvaluateForOverflow:
8231 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008232 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008233 return Error(E);
8234 case EvalInfo::EM_ConstantExpressionUnevaluated:
8235 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00008236 // Reduce it to a constant now.
8237 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008238 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00008239
8240 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00008241 }
8242
Tim Northover314fbfa2018-11-02 13:14:11 +00008243 case Builtin::BI__builtin_os_log_format_buffer_size: {
8244 analyze_os_log::OSLogBufferLayout Layout;
8245 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
8246 return Success(Layout.size().getQuantity(), E);
8247 }
8248
Benjamin Kramera801f4a2012-10-06 14:42:22 +00008249 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00008250 case Builtin::BI__builtin_bswap32:
8251 case Builtin::BI__builtin_bswap64: {
8252 APSInt Val;
8253 if (!EvaluateInteger(E->getArg(0), Val, Info))
8254 return false;
8255
8256 return Success(Val.byteSwap(), E);
8257 }
8258
Richard Smith8889a3d2013-06-13 06:26:32 +00008259 case Builtin::BI__builtin_classify_type:
Richard Smith08b682b2018-05-23 21:18:00 +00008260 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00008261
Craig Topperf95a6d92018-08-08 22:31:12 +00008262 case Builtin::BI__builtin_clrsb:
8263 case Builtin::BI__builtin_clrsbl:
8264 case Builtin::BI__builtin_clrsbll: {
8265 APSInt Val;
8266 if (!EvaluateInteger(E->getArg(0), Val, Info))
8267 return false;
8268
8269 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8270 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008271
Richard Smith80b3c8e2013-06-13 05:04:16 +00008272 case Builtin::BI__builtin_clz:
8273 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008274 case Builtin::BI__builtin_clzll:
8275 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008276 APSInt Val;
8277 if (!EvaluateInteger(E->getArg(0), Val, Info))
8278 return false;
8279 if (!Val)
8280 return Error(E);
8281
8282 return Success(Val.countLeadingZeros(), E);
8283 }
8284
Fangrui Song407659a2018-11-30 23:41:18 +00008285 case Builtin::BI__builtin_constant_p: {
Richard Smith31cfb312019-04-27 02:58:17 +00008286 const Expr *Arg = E->getArg(0);
David Blaikie639b3d12019-05-03 18:11:31 +00008287 if (EvaluateBuiltinConstantP(Info, Arg))
Fangrui Song407659a2018-11-30 23:41:18 +00008288 return Success(true, E);
David Blaikie639b3d12019-05-03 18:11:31 +00008289 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
Richard Smithf7d30482019-05-02 23:21:28 +00008290 // Outside a constant context, eagerly evaluate to false in the presence
8291 // of side-effects in order to avoid -Wunsequenced false-positives in
8292 // a branch on __builtin_constant_p(expr).
Richard Smith31cfb312019-04-27 02:58:17 +00008293 return Success(false, E);
Fangrui Song407659a2018-11-30 23:41:18 +00008294 }
David Blaikie639b3d12019-05-03 18:11:31 +00008295 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8296 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00008297 }
Richard Smith8889a3d2013-06-13 06:26:32 +00008298
Eric Fiselieradd16a82019-04-24 02:23:30 +00008299 case Builtin::BI__builtin_is_constant_evaluated:
8300 return Success(Info.InConstantContext, E);
8301
Richard Smith80b3c8e2013-06-13 05:04:16 +00008302 case Builtin::BI__builtin_ctz:
8303 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00008304 case Builtin::BI__builtin_ctzll:
8305 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00008306 APSInt Val;
8307 if (!EvaluateInteger(E->getArg(0), Val, Info))
8308 return false;
8309 if (!Val)
8310 return Error(E);
8311
8312 return Success(Val.countTrailingZeros(), E);
8313 }
8314
Richard Smith8889a3d2013-06-13 06:26:32 +00008315 case Builtin::BI__builtin_eh_return_data_regno: {
8316 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8317 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8318 return Success(Operand, E);
8319 }
8320
8321 case Builtin::BI__builtin_expect:
8322 return Visit(E->getArg(0));
8323
8324 case Builtin::BI__builtin_ffs:
8325 case Builtin::BI__builtin_ffsl:
8326 case Builtin::BI__builtin_ffsll: {
8327 APSInt Val;
8328 if (!EvaluateInteger(E->getArg(0), Val, Info))
8329 return false;
8330
8331 unsigned N = Val.countTrailingZeros();
8332 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8333 }
8334
8335 case Builtin::BI__builtin_fpclassify: {
8336 APFloat Val(0.0);
8337 if (!EvaluateFloat(E->getArg(5), Val, Info))
8338 return false;
8339 unsigned Arg;
8340 switch (Val.getCategory()) {
8341 case APFloat::fcNaN: Arg = 0; break;
8342 case APFloat::fcInfinity: Arg = 1; break;
8343 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8344 case APFloat::fcZero: Arg = 4; break;
8345 }
8346 return Visit(E->getArg(Arg));
8347 }
8348
8349 case Builtin::BI__builtin_isinf_sign: {
8350 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00008351 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00008352 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8353 }
8354
Richard Smithea3019d2013-10-15 19:07:14 +00008355 case Builtin::BI__builtin_isinf: {
8356 APFloat Val(0.0);
8357 return EvaluateFloat(E->getArg(0), Val, Info) &&
8358 Success(Val.isInfinity() ? 1 : 0, E);
8359 }
8360
8361 case Builtin::BI__builtin_isfinite: {
8362 APFloat Val(0.0);
8363 return EvaluateFloat(E->getArg(0), Val, Info) &&
8364 Success(Val.isFinite() ? 1 : 0, E);
8365 }
8366
8367 case Builtin::BI__builtin_isnan: {
8368 APFloat Val(0.0);
8369 return EvaluateFloat(E->getArg(0), Val, Info) &&
8370 Success(Val.isNaN() ? 1 : 0, E);
8371 }
8372
8373 case Builtin::BI__builtin_isnormal: {
8374 APFloat Val(0.0);
8375 return EvaluateFloat(E->getArg(0), Val, Info) &&
8376 Success(Val.isNormal() ? 1 : 0, E);
8377 }
8378
Richard Smith8889a3d2013-06-13 06:26:32 +00008379 case Builtin::BI__builtin_parity:
8380 case Builtin::BI__builtin_parityl:
8381 case Builtin::BI__builtin_parityll: {
8382 APSInt Val;
8383 if (!EvaluateInteger(E->getArg(0), Val, Info))
8384 return false;
8385
8386 return Success(Val.countPopulation() % 2, E);
8387 }
8388
Richard Smith80b3c8e2013-06-13 05:04:16 +00008389 case Builtin::BI__builtin_popcount:
8390 case Builtin::BI__builtin_popcountl:
8391 case Builtin::BI__builtin_popcountll: {
8392 APSInt Val;
8393 if (!EvaluateInteger(E->getArg(0), Val, Info))
8394 return false;
8395
8396 return Success(Val.countPopulation(), E);
8397 }
8398
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008399 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00008400 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00008401 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008402 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008403 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00008404 << /*isConstexpr*/0 << /*isConstructor*/0
8405 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00008406 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00008407 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008408 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00008409 case Builtin::BI__builtin_strlen:
8410 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00008411 // As an extension, we support __builtin_strlen() as a constant expression,
8412 // and support folding strlen() to a constant.
8413 LValue String;
8414 if (!EvaluatePointer(E->getArg(0), String, Info))
8415 return false;
8416
Richard Smith8110c9d2016-11-29 19:45:17 +00008417 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8418
Richard Smithe6c19f22013-11-15 02:10:04 +00008419 // Fast path: if it's a string literal, search the string value.
8420 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8421 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008422 // The string literal may have embedded null characters. Find the first
8423 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00008424 StringRef Str = S->getBytes();
8425 int64_t Off = String.Offset.getQuantity();
8426 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008427 S->getCharByteWidth() == 1 &&
8428 // FIXME: Add fast-path for wchar_t too.
8429 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00008430 Str = Str.substr(Off);
8431
8432 StringRef::size_type Pos = Str.find(0);
8433 if (Pos != StringRef::npos)
8434 Str = Str.substr(0, Pos);
8435
8436 return Success(Str.size(), E);
8437 }
8438
8439 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00008440 }
Richard Smithe6c19f22013-11-15 02:10:04 +00008441
8442 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00008443 for (uint64_t Strlen = 0; /**/; ++Strlen) {
8444 APValue Char;
8445 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8446 !Char.isInt())
8447 return false;
8448 if (!Char.getInt())
8449 return Success(Strlen, E);
8450 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8451 return false;
8452 }
8453 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008454
Richard Smithe151bab2016-11-11 23:43:35 +00008455 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008456 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008457 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008458 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008459 case Builtin::BImemcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00008460 case Builtin::BIbcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008461 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008462 // A call to strlen is not a constant expression.
8463 if (Info.getLangOpts().CPlusPlus11)
8464 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8465 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00008466 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00008467 else
8468 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008469 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00008470 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008471 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008472 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008473 case Builtin::BI__builtin_wcsncmp:
8474 case Builtin::BI__builtin_memcmp:
Clement Courbet8c3343d2019-02-14 12:00:34 +00008475 case Builtin::BI__builtin_bcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008476 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00008477 LValue String1, String2;
8478 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8479 !EvaluatePointer(E->getArg(1), String2, Info))
8480 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00008481
Richard Smithe151bab2016-11-11 23:43:35 +00008482 uint64_t MaxLength = uint64_t(-1);
8483 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008484 BuiltinOp != Builtin::BIwcscmp &&
8485 BuiltinOp != Builtin::BI__builtin_strcmp &&
8486 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00008487 APSInt N;
8488 if (!EvaluateInteger(E->getArg(2), N, Info))
8489 return false;
8490 MaxLength = N.getExtValue();
8491 }
Hubert Tong147b7432018-12-12 16:53:43 +00008492
8493 // Empty substrings compare equal by definition.
8494 if (MaxLength == 0u)
8495 return Success(0, E);
8496
8497 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8498 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8499 String1.Designator.Invalid || String2.Designator.Invalid)
8500 return false;
8501
8502 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
8503 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
8504
8505 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
Clement Courbet8c3343d2019-02-14 12:00:34 +00008506 BuiltinOp == Builtin::BIbcmp ||
8507 BuiltinOp == Builtin::BI__builtin_memcmp ||
8508 BuiltinOp == Builtin::BI__builtin_bcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00008509
8510 assert(IsRawByte ||
8511 (Info.Ctx.hasSameUnqualifiedType(
8512 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
8513 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
8514
8515 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
8516 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
8517 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
8518 Char1.isInt() && Char2.isInt();
8519 };
8520 const auto &AdvanceElems = [&] {
8521 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
8522 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
8523 };
8524
8525 if (IsRawByte) {
8526 uint64_t BytesRemaining = MaxLength;
8527 // Pointers to const void may point to objects of incomplete type.
8528 if (CharTy1->isIncompleteType()) {
8529 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
8530 return false;
8531 }
8532 if (CharTy2->isIncompleteType()) {
8533 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
8534 return false;
8535 }
8536 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
8537 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
8538 // Give up on comparing between elements with disparate widths.
8539 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
8540 return false;
8541 uint64_t BytesPerElement = CharTy1Size.getQuantity();
8542 assert(BytesRemaining && "BytesRemaining should not be zero: the "
8543 "following loop considers at least one element");
8544 while (true) {
8545 APValue Char1, Char2;
8546 if (!ReadCurElems(Char1, Char2))
8547 return false;
8548 // We have compatible in-memory widths, but a possible type and
8549 // (for `bool`) internal representation mismatch.
8550 // Assuming two's complement representation, including 0 for `false` and
8551 // 1 for `true`, we can check an appropriate number of elements for
8552 // equality even if they are not byte-sized.
8553 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
8554 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
8555 if (Char1InMem.ne(Char2InMem)) {
8556 // If the elements are byte-sized, then we can produce a three-way
8557 // comparison result in a straightforward manner.
8558 if (BytesPerElement == 1u) {
8559 // memcmp always compares unsigned chars.
8560 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
8561 }
8562 // The result is byte-order sensitive, and we have multibyte elements.
8563 // FIXME: We can compare the remaining bytes in the correct order.
8564 return false;
8565 }
8566 if (!AdvanceElems())
8567 return false;
8568 if (BytesRemaining <= BytesPerElement)
8569 break;
8570 BytesRemaining -= BytesPerElement;
8571 }
8572 // Enough elements are equal to account for the memcmp limit.
8573 return Success(0, E);
8574 }
8575
Clement Courbet8c3343d2019-02-14 12:00:34 +00008576 bool StopAtNull =
8577 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
8578 BuiltinOp != Builtin::BIwmemcmp &&
8579 BuiltinOp != Builtin::BI__builtin_memcmp &&
8580 BuiltinOp != Builtin::BI__builtin_bcmp &&
8581 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00008582 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8583 BuiltinOp == Builtin::BIwcsncmp ||
8584 BuiltinOp == Builtin::BIwmemcmp ||
8585 BuiltinOp == Builtin::BI__builtin_wcscmp ||
8586 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8587 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Hubert Tong147b7432018-12-12 16:53:43 +00008588
Richard Smithe151bab2016-11-11 23:43:35 +00008589 for (; MaxLength; --MaxLength) {
8590 APValue Char1, Char2;
Hubert Tong147b7432018-12-12 16:53:43 +00008591 if (!ReadCurElems(Char1, Char2))
Richard Smithe151bab2016-11-11 23:43:35 +00008592 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00008593 if (Char1.getInt() != Char2.getInt()) {
8594 if (IsWide) // wmemcmp compares with wchar_t signedness.
8595 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8596 // memcmp always compares unsigned chars.
8597 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8598 }
Richard Smithe151bab2016-11-11 23:43:35 +00008599 if (StopAtNull && !Char1.getInt())
8600 return Success(0, E);
8601 assert(!(StopAtNull && !Char2.getInt()));
Hubert Tong147b7432018-12-12 16:53:43 +00008602 if (!AdvanceElems())
Richard Smithe151bab2016-11-11 23:43:35 +00008603 return false;
8604 }
8605 // We hit the strncmp / memcmp limit.
8606 return Success(0, E);
8607 }
8608
Richard Smith01ba47d2012-04-13 00:45:38 +00008609 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00008610 case Builtin::BI__atomic_is_lock_free:
8611 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00008612 APSInt SizeVal;
8613 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8614 return false;
8615
8616 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8617 // of two less than the maximum inline atomic width, we know it is
8618 // lock-free. If the size isn't a power of two, or greater than the
8619 // maximum alignment where we promote atomics, we know it is not lock-free
8620 // (at least not in the sense of atomic_is_lock_free). Otherwise,
8621 // the answer can only be determined at runtime; for example, 16-byte
8622 // atomics have lock-free implementations on some, but not all,
8623 // x86-64 processors.
8624
8625 // Check power-of-two.
8626 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00008627 if (Size.isPowerOfTwo()) {
8628 // Check against inlining width.
8629 unsigned InlineWidthBits =
8630 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8631 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8632 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8633 Size == CharUnits::One() ||
8634 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8635 Expr::NPC_NeverValueDependent))
8636 // OK, we will inline appropriately-aligned operations of this size,
8637 // and _Atomic(T) is appropriately-aligned.
8638 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008639
Richard Smith01ba47d2012-04-13 00:45:38 +00008640 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8641 castAs<PointerType>()->getPointeeType();
8642 if (!PointeeType->isIncompleteType() &&
8643 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8644 // OK, we will inline operations on this object.
8645 return Success(1, E);
8646 }
8647 }
8648 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008649
Richard Smith01ba47d2012-04-13 00:45:38 +00008650 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8651 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008652 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008653 case Builtin::BIomp_is_initial_device:
8654 // We can decide statically which value the runtime would return if called.
8655 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Erich Keane00958272018-06-13 20:43:27 +00008656 case Builtin::BI__builtin_add_overflow:
8657 case Builtin::BI__builtin_sub_overflow:
8658 case Builtin::BI__builtin_mul_overflow:
8659 case Builtin::BI__builtin_sadd_overflow:
8660 case Builtin::BI__builtin_uadd_overflow:
8661 case Builtin::BI__builtin_uaddl_overflow:
8662 case Builtin::BI__builtin_uaddll_overflow:
8663 case Builtin::BI__builtin_usub_overflow:
8664 case Builtin::BI__builtin_usubl_overflow:
8665 case Builtin::BI__builtin_usubll_overflow:
8666 case Builtin::BI__builtin_umul_overflow:
8667 case Builtin::BI__builtin_umull_overflow:
8668 case Builtin::BI__builtin_umulll_overflow:
8669 case Builtin::BI__builtin_saddl_overflow:
8670 case Builtin::BI__builtin_saddll_overflow:
8671 case Builtin::BI__builtin_ssub_overflow:
8672 case Builtin::BI__builtin_ssubl_overflow:
8673 case Builtin::BI__builtin_ssubll_overflow:
8674 case Builtin::BI__builtin_smul_overflow:
8675 case Builtin::BI__builtin_smull_overflow:
8676 case Builtin::BI__builtin_smulll_overflow: {
8677 LValue ResultLValue;
8678 APSInt LHS, RHS;
8679
8680 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
8681 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
8682 !EvaluateInteger(E->getArg(1), RHS, Info) ||
8683 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
8684 return false;
8685
8686 APSInt Result;
8687 bool DidOverflow = false;
8688
8689 // If the types don't have to match, enlarge all 3 to the largest of them.
8690 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8691 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8692 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8693 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
8694 ResultType->isSignedIntegerOrEnumerationType();
8695 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
8696 ResultType->isSignedIntegerOrEnumerationType();
8697 uint64_t LHSSize = LHS.getBitWidth();
8698 uint64_t RHSSize = RHS.getBitWidth();
8699 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
8700 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
8701
8702 // Add an additional bit if the signedness isn't uniformly agreed to. We
8703 // could do this ONLY if there is a signed and an unsigned that both have
8704 // MaxBits, but the code to check that is pretty nasty. The issue will be
8705 // caught in the shrink-to-result later anyway.
8706 if (IsSigned && !AllSigned)
8707 ++MaxBits;
8708
8709 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
8710 !IsSigned);
8711 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
8712 !IsSigned);
8713 Result = APSInt(MaxBits, !IsSigned);
8714 }
8715
8716 // Find largest int.
8717 switch (BuiltinOp) {
8718 default:
8719 llvm_unreachable("Invalid value for BuiltinOp");
8720 case Builtin::BI__builtin_add_overflow:
8721 case Builtin::BI__builtin_sadd_overflow:
8722 case Builtin::BI__builtin_saddl_overflow:
8723 case Builtin::BI__builtin_saddll_overflow:
8724 case Builtin::BI__builtin_uadd_overflow:
8725 case Builtin::BI__builtin_uaddl_overflow:
8726 case Builtin::BI__builtin_uaddll_overflow:
8727 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
8728 : LHS.uadd_ov(RHS, DidOverflow);
8729 break;
8730 case Builtin::BI__builtin_sub_overflow:
8731 case Builtin::BI__builtin_ssub_overflow:
8732 case Builtin::BI__builtin_ssubl_overflow:
8733 case Builtin::BI__builtin_ssubll_overflow:
8734 case Builtin::BI__builtin_usub_overflow:
8735 case Builtin::BI__builtin_usubl_overflow:
8736 case Builtin::BI__builtin_usubll_overflow:
8737 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
8738 : LHS.usub_ov(RHS, DidOverflow);
8739 break;
8740 case Builtin::BI__builtin_mul_overflow:
8741 case Builtin::BI__builtin_smul_overflow:
8742 case Builtin::BI__builtin_smull_overflow:
8743 case Builtin::BI__builtin_smulll_overflow:
8744 case Builtin::BI__builtin_umul_overflow:
8745 case Builtin::BI__builtin_umull_overflow:
8746 case Builtin::BI__builtin_umulll_overflow:
8747 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
8748 : LHS.umul_ov(RHS, DidOverflow);
8749 break;
8750 }
8751
8752 // In the case where multiple sizes are allowed, truncate and see if
8753 // the values are the same.
8754 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8755 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8756 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8757 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
8758 // since it will give us the behavior of a TruncOrSelf in the case where
8759 // its parameter <= its size. We previously set Result to be at least the
8760 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
8761 // will work exactly like TruncOrSelf.
8762 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
8763 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
8764
8765 if (!APSInt::isSameValue(Temp, Result))
8766 DidOverflow = true;
8767 Result = Temp;
8768 }
8769
8770 APValue APV{Result};
Erich Keanecb549642018-07-05 15:52:58 +00008771 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
8772 return false;
Erich Keane00958272018-06-13 20:43:27 +00008773 return Success(DidOverflow, E);
8774 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008775 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008776}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008777
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008778/// Determine whether this is a pointer past the end of the complete
Richard Smithd20f1e62014-10-21 23:01:04 +00008779/// object referred to by the lvalue.
8780static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8781 const LValue &LV) {
8782 // A null pointer can be viewed as being "past the end" but we don't
8783 // choose to look at it that way here.
8784 if (!LV.getLValueBase())
8785 return false;
8786
8787 // If the designator is valid and refers to a subobject, we're not pointing
8788 // past the end.
8789 if (!LV.getLValueDesignator().Invalid &&
8790 !LV.getLValueDesignator().isOnePastTheEnd())
8791 return false;
8792
David Majnemerc378ca52015-08-29 08:32:55 +00008793 // A pointer to an incomplete type might be past-the-end if the type's size is
8794 // zero. We cannot tell because the type is incomplete.
8795 QualType Ty = getType(LV.getLValueBase());
8796 if (Ty->isIncompleteType())
8797 return true;
8798
Richard Smithd20f1e62014-10-21 23:01:04 +00008799 // We're a past-the-end pointer if we point to the byte after the object,
8800 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008801 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008802 return LV.getLValueOffset() == Size;
8803}
8804
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008805namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008806
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008807/// Data recursive integer evaluator of certain binary operators.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008808///
8809/// We use a data recursive algorithm for binary operators so that we are able
8810/// to handle extreme cases of chained binary operators without causing stack
8811/// overflow.
8812class DataRecursiveIntBinOpEvaluator {
8813 struct EvalResult {
8814 APValue Val;
8815 bool Failed;
8816
8817 EvalResult() : Failed(false) { }
8818
8819 void swap(EvalResult &RHS) {
8820 Val.swap(RHS.Val);
8821 Failed = RHS.Failed;
8822 RHS.Failed = false;
8823 }
8824 };
8825
8826 struct Job {
8827 const Expr *E;
8828 EvalResult LHSResult; // meaningful only for binary operator expression.
8829 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008830
David Blaikie73726062015-08-12 23:09:24 +00008831 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008832 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008833
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008834 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008835 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008836 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008837
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008838 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008839 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008840 };
8841
8842 SmallVector<Job, 16> Queue;
8843
8844 IntExprEvaluator &IntEval;
8845 EvalInfo &Info;
8846 APValue &FinalResult;
8847
8848public:
8849 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8850 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8851
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008852 /// True if \param E is a binary operator that we are going to handle
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008853 /// data recursively.
8854 /// We handle binary operators that are comma, logical, or that have operands
8855 /// with integral or enumeration type.
8856 static bool shouldEnqueue(const BinaryOperator *E) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00008857 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8858 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
Richard Smith3a09d8b2016-06-04 00:22:31 +00008859 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008860 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008861 }
8862
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008863 bool Traverse(const BinaryOperator *E) {
8864 enqueue(E);
8865 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008866 while (!Queue.empty())
8867 process(PrevResult);
8868
8869 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008870
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008871 FinalResult.swap(PrevResult.Val);
8872 return true;
8873 }
8874
8875private:
8876 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8877 return IntEval.Success(Value, E, Result);
8878 }
8879 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8880 return IntEval.Success(Value, E, Result);
8881 }
8882 bool Error(const Expr *E) {
8883 return IntEval.Error(E);
8884 }
8885 bool Error(const Expr *E, diag::kind D) {
8886 return IntEval.Error(E, D);
8887 }
8888
8889 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8890 return Info.CCEDiag(E, D);
8891 }
8892
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008893 // Returns true if visiting the RHS is necessary, false otherwise.
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008894 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008895 bool &SuppressRHSDiags);
8896
8897 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8898 const BinaryOperator *E, APValue &Result);
8899
8900 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8901 Result.Failed = !Evaluate(Result.Val, Info, E);
8902 if (Result.Failed)
8903 Result.Val = APValue();
8904 }
8905
Richard Trieuba4d0872012-03-21 23:30:30 +00008906 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008907
8908 void enqueue(const Expr *E) {
8909 E = E->IgnoreParens();
8910 Queue.resize(Queue.size()+1);
8911 Queue.back().E = E;
8912 Queue.back().Kind = Job::AnyExprKind;
8913 }
8914};
8915
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008916}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008917
8918bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008919 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008920 bool &SuppressRHSDiags) {
8921 if (E->getOpcode() == BO_Comma) {
8922 // Ignore LHS but note if we could not evaluate it.
8923 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008924 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008925 return true;
8926 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008927
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008928 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008929 bool LHSAsBool;
8930 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008931 // We were able to evaluate the LHS, see if we can get away with not
8932 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008933 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8934 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008935 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008936 }
8937 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008938 LHSResult.Failed = true;
8939
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008940 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008941 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008942 if (!Info.noteSideEffect())
8943 return false;
8944
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008945 // We can't evaluate the LHS; however, sometimes the result
8946 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8947 // Don't ignore RHS and suppress diagnostics from this arm.
8948 SuppressRHSDiags = true;
8949 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008950
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008951 return true;
8952 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008953
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008954 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8955 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008956
George Burgess IVa145e252016-05-25 22:38:36 +00008957 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008958 return false; // Ignore RHS;
8959
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008960 return true;
8961}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008962
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008963static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8964 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008965 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8966 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8967 // offsets.
8968 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8969 CharUnits &Offset = LVal.getLValueOffset();
8970 uint64_t Offset64 = Offset.getQuantity();
8971 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8972 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8973 : Offset64 + Index64);
8974}
8975
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008976bool DataRecursiveIntBinOpEvaluator::
8977 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8978 const BinaryOperator *E, APValue &Result) {
8979 if (E->getOpcode() == BO_Comma) {
8980 if (RHSResult.Failed)
8981 return false;
8982 Result = RHSResult.Val;
8983 return true;
8984 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008985
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008986 if (E->isLogicalOp()) {
8987 bool lhsResult, rhsResult;
8988 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8989 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Fangrui Song6907ce22018-07-30 19:24:48 +00008990
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008991 if (LHSIsOK) {
8992 if (RHSIsOK) {
8993 if (E->getOpcode() == BO_LOr)
8994 return Success(lhsResult || rhsResult, E, Result);
8995 else
8996 return Success(lhsResult && rhsResult, E, Result);
8997 }
8998 } else {
8999 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009000 // We can't evaluate the LHS; however, sometimes the result
9001 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
9002 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009003 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009004 }
9005 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009006
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00009007 return false;
9008 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009009
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009010 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
9011 E->getRHS()->getType()->isIntegralOrEnumerationType());
Fangrui Song6907ce22018-07-30 19:24:48 +00009012
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009013 if (LHSResult.Failed || RHSResult.Failed)
9014 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009015
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009016 const APValue &LHSVal = LHSResult.Val;
9017 const APValue &RHSVal = RHSResult.Val;
Fangrui Song6907ce22018-07-30 19:24:48 +00009018
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009019 // Handle cases like (unsigned long)&a + 4.
9020 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
9021 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00009022 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009023 return true;
9024 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009025
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009026 // Handle cases like 4 + (unsigned long)&a
9027 if (E->getOpcode() == BO_Add &&
9028 RHSVal.isLValue() && LHSVal.isInt()) {
9029 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00009030 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009031 return true;
9032 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009033
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009034 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
9035 // Handle (intptr_t)&&A - (intptr_t)&&B.
9036 if (!LHSVal.getLValueOffset().isZero() ||
9037 !RHSVal.getLValueOffset().isZero())
9038 return false;
9039 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
9040 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
9041 if (!LHSExpr || !RHSExpr)
9042 return false;
9043 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9044 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9045 if (!LHSAddrExpr || !RHSAddrExpr)
9046 return false;
9047 // Make sure both labels come from the same function.
9048 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9049 RHSAddrExpr->getLabel()->getDeclContext())
9050 return false;
9051 Result = APValue(LHSAddrExpr, RHSAddrExpr);
9052 return true;
9053 }
Richard Smith43e77732013-05-07 04:50:00 +00009054
9055 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009056 if (!LHSVal.isInt() || !RHSVal.isInt())
9057 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00009058
9059 // Set up the width and signedness manually, in case it can't be deduced
9060 // from the operation we're performing.
9061 // FIXME: Don't do this in the cases where we can deduce it.
9062 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
9063 E->getType()->isUnsignedIntegerOrEnumerationType());
9064 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
9065 RHSVal.getInt(), Value))
9066 return false;
9067 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009068}
9069
Richard Trieuba4d0872012-03-21 23:30:30 +00009070void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009071 Job &job = Queue.back();
Fangrui Song6907ce22018-07-30 19:24:48 +00009072
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009073 switch (job.Kind) {
9074 case Job::AnyExprKind: {
9075 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
9076 if (shouldEnqueue(Bop)) {
9077 job.Kind = Job::BinOpKind;
9078 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009079 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009080 }
9081 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009082
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009083 EvaluateExpr(job.E, Result);
9084 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009085 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009086 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009087
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009088 case Job::BinOpKind: {
9089 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009090 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009091 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009092 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009093 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009094 }
9095 if (SuppressRHSDiags)
9096 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00009097 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009098 job.Kind = Job::BinOpVisitedLHSKind;
9099 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00009100 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009101 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009102
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009103 case Job::BinOpVisitedLHSKind: {
9104 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9105 EvalResult RHS;
9106 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00009107 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009108 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00009109 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009110 }
9111 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009112
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009113 llvm_unreachable("Invalid Job::Kind!");
9114}
9115
George Burgess IV8c892b52016-05-25 22:31:54 +00009116namespace {
9117/// Used when we determine that we should fail, but can keep evaluating prior to
9118/// noting that we had a failure.
9119class DelayedNoteFailureRAII {
9120 EvalInfo &Info;
9121 bool NoteFailure;
9122
9123public:
9124 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
9125 : Info(Info), NoteFailure(NoteFailure) {}
9126 ~DelayedNoteFailureRAII() {
9127 if (NoteFailure) {
9128 bool ContinueAfterFailure = Info.noteFailure();
9129 (void)ContinueAfterFailure;
9130 assert(ContinueAfterFailure &&
9131 "Shouldn't have kept evaluating on failure.");
9132 }
9133 }
9134};
9135}
9136
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009137template <class SuccessCB, class AfterCB>
9138static bool
9139EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
9140 SuccessCB &&Success, AfterCB &&DoAfter) {
9141 assert(E->isComparisonOp() && "expected comparison operator");
9142 assert((E->getOpcode() == BO_Cmp ||
9143 E->getType()->isIntegralOrEnumerationType()) &&
9144 "unsupported binary expression evaluation");
9145 auto Error = [&](const Expr *E) {
9146 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9147 return false;
9148 };
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009149
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009150 using CCR = ComparisonCategoryResult;
9151 bool IsRelational = E->isRelationalOp();
9152 bool IsEquality = E->isEqualityOp();
9153 if (E->getOpcode() == BO_Cmp) {
9154 const ComparisonCategoryInfo &CmpInfo =
9155 Info.Ctx.CompCategories.getInfoForType(E->getType());
9156 IsRelational = CmpInfo.isOrdered();
9157 IsEquality = CmpInfo.isEquality();
9158 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00009159
Anders Carlssonacc79812008-11-16 07:17:21 +00009160 QualType LHSTy = E->getLHS()->getType();
9161 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009162
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009163 if (LHSTy->isIntegralOrEnumerationType() &&
9164 RHSTy->isIntegralOrEnumerationType()) {
9165 APSInt LHS, RHS;
9166 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
9167 if (!LHSOK && !Info.noteFailure())
9168 return false;
9169 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
9170 return false;
9171 if (LHS < RHS)
9172 return Success(CCR::Less, E);
9173 if (LHS > RHS)
9174 return Success(CCR::Greater, E);
9175 return Success(CCR::Equal, E);
9176 }
9177
Leonard Chance1d4f12019-02-21 20:50:09 +00009178 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
9179 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
9180 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
9181
9182 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
9183 if (!LHSOK && !Info.noteFailure())
9184 return false;
9185 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
9186 return false;
9187 if (LHSFX < RHSFX)
9188 return Success(CCR::Less, E);
9189 if (LHSFX > RHSFX)
9190 return Success(CCR::Greater, E);
9191 return Success(CCR::Equal, E);
9192 }
9193
Chandler Carruthb29a7432014-10-11 11:03:30 +00009194 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009195 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00009196 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00009197 if (E->isAssignmentOp()) {
9198 LValue LV;
9199 EvaluateLValue(E->getLHS(), LV, Info);
9200 LHSOK = false;
9201 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00009202 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
9203 if (LHSOK) {
9204 LHS.makeComplexFloat();
9205 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
9206 }
9207 } else {
9208 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
9209 }
George Burgess IVa145e252016-05-25 22:38:36 +00009210 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009211 return false;
9212
Chandler Carruthb29a7432014-10-11 11:03:30 +00009213 if (E->getRHS()->getType()->isRealFloatingType()) {
9214 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
9215 return false;
9216 RHS.makeComplexFloat();
9217 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
9218 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009219 return false;
9220
9221 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00009222 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009223 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00009224 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009225 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009226 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9227 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009228 } else {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009229 assert(IsEquality && "invalid complex comparison");
9230 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
9231 LHS.getComplexIntImag() == RHS.getComplexIntImag();
9232 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00009233 }
9234 }
Mike Stump11289f42009-09-09 15:08:12 +00009235
Anders Carlssonacc79812008-11-16 07:17:21 +00009236 if (LHSTy->isRealFloatingType() &&
9237 RHSTy->isRealFloatingType()) {
9238 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00009239
Richard Smith253c2a32012-01-27 01:14:48 +00009240 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009241 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00009242 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009243
Richard Smith253c2a32012-01-27 01:14:48 +00009244 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00009245 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009246
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009247 assert(E->isComparisonOp() && "Invalid binary operator!");
9248 auto GetCmpRes = [&]() {
9249 switch (LHS.compare(RHS)) {
9250 case APFloat::cmpEqual:
9251 return CCR::Equal;
9252 case APFloat::cmpLessThan:
9253 return CCR::Less;
9254 case APFloat::cmpGreaterThan:
9255 return CCR::Greater;
9256 case APFloat::cmpUnordered:
9257 return CCR::Unordered;
9258 }
Simon Pilgrim3366dcf2018-05-08 09:40:32 +00009259 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009260 };
9261 return Success(GetCmpRes(), E);
Anders Carlssonacc79812008-11-16 07:17:21 +00009262 }
Mike Stump11289f42009-09-09 15:08:12 +00009263
Eli Friedmana38da572009-04-28 19:17:36 +00009264 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009265 LValue LHSValue, RHSValue;
Richard Smith253c2a32012-01-27 01:14:48 +00009266
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009267 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9268 if (!LHSOK && !Info.noteFailure())
9269 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009270
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009271 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9272 return false;
Eli Friedman64004332009-03-23 04:38:34 +00009273
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009274 // Reject differing bases from the normal codepath; we special-case
9275 // comparisons to null.
9276 if (!HasSameBase(LHSValue, RHSValue)) {
9277 // Inequalities and subtractions between unrelated pointers have
9278 // unspecified or undefined behavior.
9279 if (!IsEquality)
9280 return Error(E);
9281 // A constant address may compare equal to the address of a symbol.
9282 // The one exception is that address of an object cannot compare equal
9283 // to a null pointer constant.
9284 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9285 (!RHSValue.Base && !RHSValue.Offset.isZero()))
9286 return Error(E);
9287 // It's implementation-defined whether distinct literals will have
9288 // distinct addresses. In clang, the result of such a comparison is
9289 // unspecified, so it is not a constant expression. However, we do know
9290 // that the address of a literal will be non-null.
9291 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9292 LHSValue.Base && RHSValue.Base)
9293 return Error(E);
9294 // We can't tell whether weak symbols will end up pointing to the same
9295 // object.
9296 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9297 return Error(E);
9298 // We can't compare the address of the start of one object with the
9299 // past-the-end address of another object, per C++ DR1652.
9300 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9301 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9302 (RHSValue.Base && RHSValue.Offset.isZero() &&
9303 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9304 return Error(E);
9305 // We can't tell whether an object is at the same address as another
9306 // zero sized object.
9307 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9308 (LHSValue.Base && isZeroSized(RHSValue)))
9309 return Error(E);
9310 return Success(CCR::Nonequal, E);
9311 }
Eli Friedman64004332009-03-23 04:38:34 +00009312
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009313 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9314 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith1b470412012-02-01 08:10:20 +00009315
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009316 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9317 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
Richard Smith84f6dcf2012-02-02 01:16:57 +00009318
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009319 // C++11 [expr.rel]p3:
9320 // Pointers to void (after pointer conversions) can be compared, with a
9321 // result defined as follows: If both pointers represent the same
9322 // address or are both the null pointer value, the result is true if the
9323 // operator is <= or >= and false otherwise; otherwise the result is
9324 // unspecified.
9325 // We interpret this as applying to pointers to *cv* void.
9326 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9327 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
Richard Smith84f6dcf2012-02-02 01:16:57 +00009328
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009329 // C++11 [expr.rel]p2:
9330 // - If two pointers point to non-static data members of the same object,
9331 // or to subobjects or array elements fo such members, recursively, the
9332 // pointer to the later declared member compares greater provided the
9333 // two members have the same access control and provided their class is
9334 // not a union.
9335 // [...]
9336 // - Otherwise pointer comparisons are unspecified.
9337 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9338 bool WasArrayIndex;
9339 unsigned Mismatch = FindDesignatorMismatch(
9340 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9341 // At the point where the designators diverge, the comparison has a
9342 // specified value if:
9343 // - we are comparing array indices
9344 // - we are comparing fields of a union, or fields with the same access
9345 // Otherwise, the result is unspecified and thus the comparison is not a
9346 // constant expression.
9347 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9348 Mismatch < RHSDesignator.Entries.size()) {
9349 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9350 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9351 if (!LF && !RF)
9352 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9353 else if (!LF)
9354 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009355 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9356 << RF->getParent() << RF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009357 else if (!RF)
9358 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009359 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9360 << LF->getParent() << LF;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009361 else if (!LF->getParent()->isUnion() &&
9362 LF->getAccess() != RF->getAccess())
9363 Info.CCEDiag(E,
9364 diag::note_constexpr_pointer_comparison_differing_access)
Richard Smith84f6dcf2012-02-02 01:16:57 +00009365 << LF << LF->getAccess() << RF << RF->getAccess()
9366 << LF->getParent();
Eli Friedmana38da572009-04-28 19:17:36 +00009367 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009368 }
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009369
9370 // The comparison here must be unsigned, and performed with the same
9371 // width as the pointer.
9372 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9373 uint64_t CompareLHS = LHSOffset.getQuantity();
9374 uint64_t CompareRHS = RHSOffset.getQuantity();
9375 assert(PtrSize <= 64 && "Unexpected pointer width");
9376 uint64_t Mask = ~0ULL >> (64 - PtrSize);
9377 CompareLHS &= Mask;
9378 CompareRHS &= Mask;
9379
9380 // If there is a base and this is a relational operator, we can only
9381 // compare pointers within the object in question; otherwise, the result
9382 // depends on where the object is located in memory.
9383 if (!LHSValue.Base.isNull() && IsRelational) {
9384 QualType BaseTy = getType(LHSValue.Base);
9385 if (BaseTy->isIncompleteType())
9386 return Error(E);
9387 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9388 uint64_t OffsetLimit = Size.getQuantity();
9389 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9390 return Error(E);
9391 }
9392
9393 if (CompareLHS < CompareRHS)
9394 return Success(CCR::Less, E);
9395 if (CompareLHS > CompareRHS)
9396 return Success(CCR::Greater, E);
9397 return Success(CCR::Equal, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00009398 }
Richard Smith7bb00672012-02-01 01:42:44 +00009399
9400 if (LHSTy->isMemberPointerType()) {
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009401 assert(IsEquality && "unexpected member pointer operation");
Richard Smith7bb00672012-02-01 01:42:44 +00009402 assert(RHSTy->isMemberPointerType() && "invalid comparison");
9403
9404 MemberPtr LHSValue, RHSValue;
9405
9406 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009407 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00009408 return false;
9409
9410 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9411 return false;
9412
9413 // C++11 [expr.eq]p2:
9414 // If both operands are null, they compare equal. Otherwise if only one is
9415 // null, they compare unequal.
9416 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9417 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009418 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009419 }
9420
9421 // Otherwise if either is a pointer to a virtual member function, the
9422 // result is unspecified.
9423 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9424 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009425 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009426 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9427 if (MD->isVirtual())
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009428 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
Richard Smith7bb00672012-02-01 01:42:44 +00009429
9430 // Otherwise they compare equal if and only if they would refer to the
9431 // same member of the same most derived object or the same subobject if
9432 // they were dereferenced with a hypothetical object of the associated
9433 // class type.
9434 bool Equal = LHSValue == RHSValue;
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009435 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
Richard Smith7bb00672012-02-01 01:42:44 +00009436 }
9437
Richard Smithab44d9b2012-02-14 22:35:28 +00009438 if (LHSTy->isNullPtrType()) {
9439 assert(E->isComparisonOp() && "unexpected nullptr operation");
9440 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9441 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9442 // are compared, the result is true of the operator is <=, >= or ==, and
9443 // false otherwise.
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009444 return Success(CCR::Equal, E);
Richard Smithab44d9b2012-02-14 22:35:28 +00009445 }
9446
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009447 return DoAfter();
9448}
9449
9450bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
9451 if (!CheckLiteralType(Info, E))
9452 return false;
9453
9454 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9455 const BinaryOperator *E) {
9456 // Evaluation succeeded. Lookup the information for the comparison category
9457 // type and fetch the VarDecl for the result.
9458 const ComparisonCategoryInfo &CmpInfo =
9459 Info.Ctx.CompCategories.getInfoForType(E->getType());
9460 const VarDecl *VD =
9461 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
9462 // Check and evaluate the result as a constant expression.
9463 LValue LV;
9464 LV.set(VD);
9465 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9466 return false;
9467 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9468 };
9469 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9470 return ExprEvaluatorBaseTy::VisitBinCmp(E);
9471 });
9472}
9473
9474bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9475 // We don't call noteFailure immediately because the assignment happens after
9476 // we evaluate LHS and RHS.
9477 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
9478 return Error(E);
9479
9480 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
9481 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
9482 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
9483
9484 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
9485 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009486 "DataRecursiveIntBinOpEvaluator should have handled integral types");
Eric Fiselier0683c0e2018-05-07 21:07:10 +00009487
9488 if (E->isComparisonOp()) {
9489 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
9490 // comparisons and then translating the result.
9491 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9492 const BinaryOperator *E) {
9493 using CCR = ComparisonCategoryResult;
9494 bool IsEqual = ResKind == CCR::Equal,
9495 IsLess = ResKind == CCR::Less,
9496 IsGreater = ResKind == CCR::Greater;
9497 auto Op = E->getOpcode();
9498 switch (Op) {
9499 default:
9500 llvm_unreachable("unsupported binary operator");
9501 case BO_EQ:
9502 case BO_NE:
9503 return Success(IsEqual == (Op == BO_EQ), E);
9504 case BO_LT: return Success(IsLess, E);
9505 case BO_GT: return Success(IsGreater, E);
9506 case BO_LE: return Success(IsEqual || IsLess, E);
9507 case BO_GE: return Success(IsEqual || IsGreater, E);
9508 }
9509 };
9510 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9511 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9512 });
9513 }
9514
9515 QualType LHSTy = E->getLHS()->getType();
9516 QualType RHSTy = E->getRHS()->getType();
9517
9518 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
9519 E->getOpcode() == BO_Sub) {
9520 LValue LHSValue, RHSValue;
9521
9522 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9523 if (!LHSOK && !Info.noteFailure())
9524 return false;
9525
9526 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9527 return false;
9528
9529 // Reject differing bases from the normal codepath; we special-case
9530 // comparisons to null.
9531 if (!HasSameBase(LHSValue, RHSValue)) {
9532 // Handle &&A - &&B.
9533 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
9534 return Error(E);
9535 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
9536 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
9537 if (!LHSExpr || !RHSExpr)
9538 return Error(E);
9539 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9540 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9541 if (!LHSAddrExpr || !RHSAddrExpr)
9542 return Error(E);
9543 // Make sure both labels come from the same function.
9544 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9545 RHSAddrExpr->getLabel()->getDeclContext())
9546 return Error(E);
9547 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
9548 }
9549 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9550 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9551
9552 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9553 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9554
9555 // C++11 [expr.add]p6:
9556 // Unless both pointers point to elements of the same array object, or
9557 // one past the last element of the array object, the behavior is
9558 // undefined.
9559 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
9560 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
9561 RHSDesignator))
9562 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
9563
9564 QualType Type = E->getLHS()->getType();
9565 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
9566
9567 CharUnits ElementSize;
9568 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
9569 return false;
9570
9571 // As an extension, a type may have zero size (empty struct or union in
9572 // C, array of zero length). Pointer subtraction in such cases has
9573 // undefined behavior, so is not constant.
9574 if (ElementSize.isZero()) {
9575 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
9576 << ElementType;
9577 return false;
9578 }
9579
9580 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
9581 // and produce incorrect results when it overflows. Such behavior
9582 // appears to be non-conforming, but is common, so perhaps we should
9583 // assume the standard intended for such cases to be undefined behavior
9584 // and check for them.
9585
9586 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
9587 // overflow in the final conversion to ptrdiff_t.
9588 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
9589 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
9590 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
9591 false);
9592 APSInt TrueResult = (LHS - RHS) / ElemSize;
9593 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
9594
9595 if (Result.extend(65) != TrueResult &&
9596 !HandleOverflow(Info, E, TrueResult, E->getType()))
9597 return false;
9598 return Success(Result, E);
9599 }
9600
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00009601 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00009602}
9603
Peter Collingbournee190dee2011-03-11 19:24:49 +00009604/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
9605/// a result as the expression's type.
9606bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
9607 const UnaryExprOrTypeTraitExpr *E) {
9608 switch(E->getKind()) {
Richard Smith6822bd72018-10-26 19:26:45 +00009609 case UETT_PreferredAlignOf:
Peter Collingbournee190dee2011-03-11 19:24:49 +00009610 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00009611 if (E->isArgumentType())
Richard Smith6822bd72018-10-26 19:26:45 +00009612 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
9613 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009614 else
Richard Smith6822bd72018-10-26 19:26:45 +00009615 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
9616 E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00009617 }
Eli Friedman64004332009-03-23 04:38:34 +00009618
Peter Collingbournee190dee2011-03-11 19:24:49 +00009619 case UETT_VecStep: {
9620 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00009621
Peter Collingbournee190dee2011-03-11 19:24:49 +00009622 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00009623 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00009624
Peter Collingbournee190dee2011-03-11 19:24:49 +00009625 // The vec_step built-in functions that take a 3-component
9626 // vector return 4. (OpenCL 1.1 spec 6.11.12)
9627 if (n == 3)
9628 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00009629
Peter Collingbournee190dee2011-03-11 19:24:49 +00009630 return Success(n, E);
9631 } else
9632 return Success(1, E);
9633 }
9634
9635 case UETT_SizeOf: {
9636 QualType SrcTy = E->getTypeOfArgument();
9637 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9638 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00009639 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9640 SrcTy = Ref->getPointeeType();
9641
Richard Smithd62306a2011-11-10 06:34:14 +00009642 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00009643 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00009644 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00009645 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009646 }
Alexey Bataev00396512015-07-02 03:40:19 +00009647 case UETT_OpenMPRequiredSimdAlign:
9648 assert(E->isArgumentType());
9649 return Success(
9650 Info.Ctx.toCharUnitsFromBits(
9651 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9652 .getQuantity(),
9653 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00009654 }
9655
9656 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00009657}
9658
Peter Collingbournee9200682011-05-13 03:29:01 +00009659bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00009660 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00009661 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00009662 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009663 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00009664 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00009665 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00009666 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00009667 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00009668 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00009669 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00009670 APSInt IdxResult;
9671 if (!EvaluateInteger(Idx, IdxResult, Info))
9672 return false;
9673 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9674 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009675 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009676 CurrentType = AT->getElementType();
9677 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9678 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00009679 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00009680 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009681
James Y Knight7281c352015-12-29 22:31:18 +00009682 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00009683 FieldDecl *MemberDecl = ON.getField();
9684 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009685 if (!RT)
9686 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009687 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009688 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00009689 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00009690 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00009691 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00009692 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00009693 CurrentType = MemberDecl->getType().getNonReferenceType();
9694 break;
9695 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009696
James Y Knight7281c352015-12-29 22:31:18 +00009697 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00009698 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00009699
James Y Knight7281c352015-12-29 22:31:18 +00009700 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00009701 CXXBaseSpecifier *BaseSpec = ON.getBase();
9702 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00009703 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009704
9705 // Find the layout of the class whose base we are looking into.
9706 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00009707 if (!RT)
9708 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00009709 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00009710 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00009711 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9712
9713 // Find the base class itself.
9714 CurrentType = BaseSpec->getType();
9715 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9716 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009717 return Error(OOE);
Fangrui Song6907ce22018-07-30 19:24:48 +00009718
Douglas Gregord1702062010-04-29 00:18:15 +00009719 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00009720 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00009721 break;
9722 }
Douglas Gregor882211c2010-04-28 22:16:22 +00009723 }
9724 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009725 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009726}
9727
Chris Lattnere13042c2008-07-11 19:10:17 +00009728bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009729 switch (E->getOpcode()) {
9730 default:
9731 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9732 // See C99 6.6p3.
9733 return Error(E);
9734 case UO_Extension:
9735 // FIXME: Should extension allow i-c-e extension expressions in its scope?
9736 // If so, we could clear the diagnostic ID.
9737 return Visit(E->getSubExpr());
9738 case UO_Plus:
9739 // The result is just the value.
9740 return Visit(E->getSubExpr());
9741 case UO_Minus: {
9742 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00009743 return false;
9744 if (!Result.isInt()) return Error(E);
9745 const APSInt &Value = Result.getInt();
9746 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9747 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9748 E->getType()))
9749 return false;
Richard Smithfe800032012-01-31 04:08:20 +00009750 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009751 }
9752 case UO_Not: {
9753 if (!Visit(E->getSubExpr()))
9754 return false;
9755 if (!Result.isInt()) return Error(E);
9756 return Success(~Result.getInt(), E);
9757 }
9758 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00009759 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00009760 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00009761 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009762 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00009763 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009764 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009765}
Mike Stump11289f42009-09-09 15:08:12 +00009766
Chris Lattner477c4be2008-07-12 01:15:53 +00009767/// HandleCast - This is used to evaluate implicit or explicit casts where the
9768/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00009769bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9770 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009771 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00009772 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009773
Eli Friedmanc757de22011-03-25 00:43:55 +00009774 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00009775 case CK_BaseToDerived:
9776 case CK_DerivedToBase:
9777 case CK_UncheckedDerivedToBase:
9778 case CK_Dynamic:
9779 case CK_ToUnion:
9780 case CK_ArrayToPointerDecay:
9781 case CK_FunctionToPointerDecay:
9782 case CK_NullToPointer:
9783 case CK_NullToMemberPointer:
9784 case CK_BaseToDerivedMemberPointer:
9785 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00009786 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00009787 case CK_ConstructorConversion:
9788 case CK_IntegralToPointer:
9789 case CK_ToVoid:
9790 case CK_VectorSplat:
9791 case CK_IntegralToFloating:
9792 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009793 case CK_CPointerToObjCPointerCast:
9794 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009795 case CK_AnyPointerToBlockPointerCast:
9796 case CK_ObjCObjectLValueCast:
9797 case CK_FloatingRealToComplex:
9798 case CK_FloatingComplexToReal:
9799 case CK_FloatingComplexCast:
9800 case CK_FloatingComplexToIntegralComplex:
9801 case CK_IntegralRealToComplex:
9802 case CK_IntegralComplexCast:
9803 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00009804 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +00009805 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +00009806 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009807 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009808 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00009809 case CK_FixedPointCast:
Leonard Chan8f7caae2019-03-06 00:28:43 +00009810 case CK_IntegralToFixedPoint:
Eli Friedmanc757de22011-03-25 00:43:55 +00009811 llvm_unreachable("invalid cast kind for integral value");
9812
Eli Friedman9faf2f92011-03-25 19:07:11 +00009813 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009814 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009815 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00009816 case CK_ARCProduceObject:
9817 case CK_ARCConsumeObject:
9818 case CK_ARCReclaimReturnedObject:
9819 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009820 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009821 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009822
Richard Smith4ef685b2012-01-17 21:17:26 +00009823 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00009824 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009825 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009826 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009827 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009828
9829 case CK_MemberPointerToBoolean:
9830 case CK_PointerToBoolean:
9831 case CK_IntegralToBoolean:
9832 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009833 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009834 case CK_FloatingComplexToBoolean:
9835 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009836 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009837 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009838 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009839 uint64_t IntResult = BoolResult;
9840 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9841 IntResult = (uint64_t)-1;
9842 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009843 }
9844
Leonard Chan8f7caae2019-03-06 00:28:43 +00009845 case CK_FixedPointToIntegral: {
9846 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
9847 if (!EvaluateFixedPoint(SubExpr, Src, Info))
9848 return false;
9849 bool Overflowed;
9850 llvm::APSInt Result = Src.convertToInt(
9851 Info.Ctx.getIntWidth(DestType),
9852 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
9853 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
9854 return false;
9855 return Success(Result, E);
9856 }
9857
Leonard Chanb4ba4672018-10-23 17:55:35 +00009858 case CK_FixedPointToBoolean: {
9859 // Unsigned padding does not affect this.
9860 APValue Val;
9861 if (!Evaluate(Val, Info, SubExpr))
9862 return false;
Leonard Chand3f3e162019-01-18 21:04:25 +00009863 return Success(Val.getFixedPoint().getBoolValue(), E);
Leonard Chanb4ba4672018-10-23 17:55:35 +00009864 }
9865
Eli Friedmanc757de22011-03-25 00:43:55 +00009866 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009867 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009868 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009869
Eli Friedman742421e2009-02-20 01:15:07 +00009870 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009871 // Allow casts of address-of-label differences if they are no-ops
9872 // or narrowing. (The narrowing case isn't actually guaranteed to
9873 // be constant-evaluatable except in some narrow cases which are hard
9874 // to detect here. We let it through on the assumption the user knows
9875 // what they are doing.)
9876 if (Result.isAddrLabelDiff())
9877 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009878 // Only allow casts of lvalues if they are lossless.
9879 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9880 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009881
Richard Smith911e1422012-01-30 22:27:01 +00009882 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9883 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009884 }
Mike Stump11289f42009-09-09 15:08:12 +00009885
Eli Friedmanc757de22011-03-25 00:43:55 +00009886 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009887 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9888
John McCall45d55e42010-05-07 21:00:08 +00009889 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009890 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009891 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009892
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009893 if (LV.getLValueBase()) {
9894 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009895 // FIXME: Allow a larger integer size than the pointer size, and allow
9896 // narrowing back down to pointer width in subsequent integral casts.
9897 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009898 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009899 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009900
Richard Smithcf74da72011-11-16 07:18:12 +00009901 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009902 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009903 return true;
9904 }
9905
Hans Wennborgdd1ea8a2019-03-06 10:26:19 +00009906 APSInt AsInt;
9907 APValue V;
9908 LV.moveInto(V);
9909 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
9910 llvm_unreachable("Can't cast this!");
Yaxun Liu402804b2016-12-15 08:09:08 +00009911
Richard Smith911e1422012-01-30 22:27:01 +00009912 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009913 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009914
Eli Friedmanc757de22011-03-25 00:43:55 +00009915 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009916 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009917 if (!EvaluateComplex(SubExpr, C, Info))
9918 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009919 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009920 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009921
Eli Friedmanc757de22011-03-25 00:43:55 +00009922 case CK_FloatingToIntegral: {
9923 APFloat F(0.0);
9924 if (!EvaluateFloat(SubExpr, F, Info))
9925 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009926
Richard Smith357362d2011-12-13 06:39:58 +00009927 APSInt Value;
9928 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9929 return false;
9930 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009931 }
9932 }
Mike Stump11289f42009-09-09 15:08:12 +00009933
Eli Friedmanc757de22011-03-25 00:43:55 +00009934 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009935}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009936
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009937bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9938 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009939 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009940 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9941 return false;
9942 if (!LV.isComplexInt())
9943 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009944 return Success(LV.getComplexIntReal(), E);
9945 }
9946
9947 return Visit(E->getSubExpr());
9948}
9949
Eli Friedman4e7a2412009-02-27 04:45:43 +00009950bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009951 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009952 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009953 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9954 return false;
9955 if (!LV.isComplexInt())
9956 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009957 return Success(LV.getComplexIntImag(), E);
9958 }
9959
Richard Smith4a678122011-10-24 18:44:57 +00009960 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009961 return Success(0, E);
9962}
9963
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009964bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9965 return Success(E->getPackLength(), E);
9966}
9967
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009968bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9969 return Success(E->getValue(), E);
9970}
9971
Leonard Chandb01c3a2018-06-20 17:19:40 +00009972bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9973 switch (E->getOpcode()) {
9974 default:
9975 // Invalid unary operators
9976 return Error(E);
9977 case UO_Plus:
9978 // The result is just the value.
9979 return Visit(E->getSubExpr());
9980 case UO_Minus: {
9981 if (!Visit(E->getSubExpr())) return false;
Leonard Chand3f3e162019-01-18 21:04:25 +00009982 if (!Result.isFixedPoint())
9983 return Error(E);
9984 bool Overflowed;
9985 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
9986 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
9987 return false;
9988 return Success(Negated, E);
Leonard Chandb01c3a2018-06-20 17:19:40 +00009989 }
9990 case UO_LNot: {
9991 bool bres;
9992 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9993 return false;
9994 return Success(!bres, E);
9995 }
9996 }
9997}
9998
Leonard Chand3f3e162019-01-18 21:04:25 +00009999bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
10000 const Expr *SubExpr = E->getSubExpr();
10001 QualType DestType = E->getType();
10002 assert(DestType->isFixedPointType() &&
10003 "Expected destination type to be a fixed point type");
10004 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
10005
10006 switch (E->getCastKind()) {
10007 case CK_FixedPointCast: {
10008 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
10009 if (!EvaluateFixedPoint(SubExpr, Src, Info))
10010 return false;
10011 bool Overflowed;
10012 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
10013 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
10014 return false;
10015 return Success(Result, E);
10016 }
Leonard Chan8f7caae2019-03-06 00:28:43 +000010017 case CK_IntegralToFixedPoint: {
10018 APSInt Src;
10019 if (!EvaluateInteger(SubExpr, Src, Info))
10020 return false;
10021
10022 bool Overflowed;
10023 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
10024 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
10025
10026 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
10027 return false;
10028
10029 return Success(IntResult, E);
10030 }
Leonard Chand3f3e162019-01-18 21:04:25 +000010031 case CK_NoOp:
10032 case CK_LValueToRValue:
10033 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10034 default:
10035 return Error(E);
10036 }
10037}
10038
10039bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10040 const Expr *LHS = E->getLHS();
10041 const Expr *RHS = E->getRHS();
10042 FixedPointSemantics ResultFXSema =
10043 Info.Ctx.getFixedPointSemantics(E->getType());
10044
10045 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
10046 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
10047 return false;
10048 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
10049 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
10050 return false;
10051
10052 switch (E->getOpcode()) {
10053 case BO_Add: {
10054 bool AddOverflow, ConversionOverflow;
10055 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
10056 .convert(ResultFXSema, &ConversionOverflow);
10057 if ((AddOverflow || ConversionOverflow) &&
10058 !HandleOverflow(Info, E, Result, E->getType()))
10059 return false;
10060 return Success(Result, E);
10061 }
10062 default:
10063 return false;
10064 }
10065 llvm_unreachable("Should've exited before this");
10066}
10067
Chris Lattner05706e882008-07-11 18:11:29 +000010068//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +000010069// Float Evaluation
10070//===----------------------------------------------------------------------===//
10071
10072namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000010073class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010074 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +000010075 APFloat &Result;
10076public:
10077 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +000010078 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +000010079
Richard Smith2e312c82012-03-03 22:46:17 +000010080 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010081 Result = V.getFloat();
10082 return true;
10083 }
Eli Friedman24c01542008-08-22 00:06:13 +000010084
Richard Smithfddd3842011-12-30 21:15:51 +000010085 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +000010086 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
10087 return true;
10088 }
10089
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010090 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +000010091
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010092 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +000010093 bool VisitBinaryOperator(const BinaryOperator *E);
10094 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000010095 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +000010096
John McCallb1fb0d32010-05-07 22:08:54 +000010097 bool VisitUnaryReal(const UnaryOperator *E);
10098 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +000010099
Richard Smithfddd3842011-12-30 21:15:51 +000010100 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +000010101};
10102} // end anonymous namespace
10103
10104static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000010105 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010106 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +000010107}
10108
Jay Foad39c79802011-01-12 09:06:06 +000010109static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +000010110 QualType ResultTy,
10111 const Expr *Arg,
10112 bool SNaN,
10113 llvm::APFloat &Result) {
10114 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
10115 if (!S) return false;
10116
10117 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
10118
10119 llvm::APInt fill;
10120
10121 // Treat empty strings as if they were zero.
10122 if (S->getString().empty())
10123 fill = llvm::APInt(32, 0);
10124 else if (S->getString().getAsInteger(0, fill))
10125 return false;
10126
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +000010127 if (Context.getTargetInfo().isNan2008()) {
10128 if (SNaN)
10129 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10130 else
10131 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10132 } else {
10133 // Prior to IEEE 754-2008, architectures were allowed to choose whether
10134 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
10135 // a different encoding to what became a standard in 2008, and for pre-
10136 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
10137 // sNaN. This is now known as "legacy NaN" encoding.
10138 if (SNaN)
10139 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
10140 else
10141 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
10142 }
10143
John McCall16291492010-02-28 13:00:19 +000010144 return true;
10145}
10146
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010147bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +000010148 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010149 default:
10150 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10151
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010152 case Builtin::BI__builtin_huge_val:
10153 case Builtin::BI__builtin_huge_valf:
10154 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010155 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010156 case Builtin::BI__builtin_inf:
10157 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010158 case Builtin::BI__builtin_infl:
10159 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010160 const llvm::fltSemantics &Sem =
10161 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +000010162 Result = llvm::APFloat::getInf(Sem);
10163 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +000010164 }
Mike Stump11289f42009-09-09 15:08:12 +000010165
John McCall16291492010-02-28 13:00:19 +000010166 case Builtin::BI__builtin_nans:
10167 case Builtin::BI__builtin_nansf:
10168 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010169 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010170 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10171 true, Result))
10172 return Error(E);
10173 return true;
John McCall16291492010-02-28 13:00:19 +000010174
Chris Lattner0b7282e2008-10-06 06:31:58 +000010175 case Builtin::BI__builtin_nan:
10176 case Builtin::BI__builtin_nanf:
10177 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010178 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +000010179 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +000010180 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +000010181 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10182 false, Result))
10183 return Error(E);
10184 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010185
10186 case Builtin::BI__builtin_fabs:
10187 case Builtin::BI__builtin_fabsf:
10188 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010189 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010190 if (!EvaluateFloat(E->getArg(0), Result, Info))
10191 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010192
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010193 if (Result.isNegative())
10194 Result.changeSign();
10195 return true;
10196
Richard Smith8889a3d2013-06-13 06:26:32 +000010197 // FIXME: Builtin::BI__builtin_powi
10198 // FIXME: Builtin::BI__builtin_powif
10199 // FIXME: Builtin::BI__builtin_powil
10200
Mike Stump11289f42009-09-09 15:08:12 +000010201 case Builtin::BI__builtin_copysign:
10202 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +000010203 case Builtin::BI__builtin_copysignl:
10204 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010205 APFloat RHS(0.);
10206 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
10207 !EvaluateFloat(E->getArg(1), RHS, Info))
10208 return false;
10209 Result.copySign(RHS);
10210 return true;
10211 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010212 }
10213}
10214
John McCallb1fb0d32010-05-07 22:08:54 +000010215bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000010216 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10217 ComplexValue CV;
10218 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10219 return false;
10220 Result = CV.FloatReal;
10221 return true;
10222 }
10223
10224 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +000010225}
10226
10227bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +000010228 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10229 ComplexValue CV;
10230 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10231 return false;
10232 Result = CV.FloatImag;
10233 return true;
10234 }
10235
Richard Smith4a678122011-10-24 18:44:57 +000010236 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +000010237 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
10238 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +000010239 return true;
10240}
10241
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010242bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010243 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010244 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000010245 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +000010246 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +000010247 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +000010248 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
10249 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010250 Result.changeSign();
10251 return true;
10252 }
10253}
Chris Lattner4deaa4e2008-10-06 05:28:25 +000010254
Eli Friedman24c01542008-08-22 00:06:13 +000010255bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000010256 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10257 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +000010258
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +000010259 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +000010260 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +000010261 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +000010262 return false;
Richard Smith861b5b52013-05-07 23:34:45 +000010263 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
10264 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +000010265}
10266
10267bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
10268 Result = E->getValue();
10269 return true;
10270}
10271
Peter Collingbournee9200682011-05-13 03:29:01 +000010272bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
10273 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +000010274
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010275 switch (E->getCastKind()) {
10276 default:
Richard Smith11562c52011-10-28 17:51:58 +000010277 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010278
10279 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010280 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +000010281 return EvaluateInteger(SubExpr, IntResult, Info) &&
10282 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
10283 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000010284 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010285
10286 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +000010287 if (!Visit(SubExpr))
10288 return false;
Richard Smith357362d2011-12-13 06:39:58 +000010289 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
10290 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +000010291 }
John McCalld7646252010-11-14 08:17:51 +000010292
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010293 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +000010294 ComplexValue V;
10295 if (!EvaluateComplex(SubExpr, V, Info))
10296 return false;
10297 Result = V.getComplexFloatReal();
10298 return true;
10299 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +000010300 }
Eli Friedman9a156e52008-11-12 09:44:48 +000010301}
10302
Eli Friedman24c01542008-08-22 00:06:13 +000010303//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010304// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +000010305//===----------------------------------------------------------------------===//
10306
10307namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +000010308class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010309 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +000010310 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +000010311
Anders Carlsson537969c2008-11-16 20:27:53 +000010312public:
John McCall93d91dc2010-05-07 17:22:02 +000010313 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +000010314 : ExprEvaluatorBaseTy(info), Result(Result) {}
10315
Richard Smith2e312c82012-03-03 22:46:17 +000010316 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +000010317 Result.setFrom(V);
10318 return true;
10319 }
Mike Stump11289f42009-09-09 15:08:12 +000010320
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010321 bool ZeroInitialization(const Expr *E);
10322
Anders Carlsson537969c2008-11-16 20:27:53 +000010323 //===--------------------------------------------------------------------===//
10324 // Visitor Methods
10325 //===--------------------------------------------------------------------===//
10326
Peter Collingbournee9200682011-05-13 03:29:01 +000010327 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +000010328 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +000010329 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010330 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010331 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010332};
10333} // end anonymous namespace
10334
John McCall93d91dc2010-05-07 17:22:02 +000010335static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
10336 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +000010337 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +000010338 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +000010339}
10340
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010341bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +000010342 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010343 if (ElemTy->isRealFloatingType()) {
10344 Result.makeComplexFloat();
10345 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10346 Result.FloatReal = Zero;
10347 Result.FloatImag = Zero;
10348 } else {
10349 Result.makeComplexInt();
10350 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10351 Result.IntReal = Zero;
10352 Result.IntImag = Zero;
10353 }
10354 return true;
10355}
10356
Peter Collingbournee9200682011-05-13 03:29:01 +000010357bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10358 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010359
10360 if (SubExpr->getType()->isRealFloatingType()) {
10361 Result.makeComplexFloat();
10362 APFloat &Imag = Result.FloatImag;
10363 if (!EvaluateFloat(SubExpr, Imag, Info))
10364 return false;
10365
10366 Result.FloatReal = APFloat(Imag.getSemantics());
10367 return true;
10368 } else {
10369 assert(SubExpr->getType()->isIntegerType() &&
10370 "Unexpected imaginary literal.");
10371
10372 Result.makeComplexInt();
10373 APSInt &Imag = Result.IntImag;
10374 if (!EvaluateInteger(SubExpr, Imag, Info))
10375 return false;
10376
10377 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10378 return true;
10379 }
10380}
10381
Peter Collingbournee9200682011-05-13 03:29:01 +000010382bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010383
John McCallfcef3cf2010-12-14 17:51:41 +000010384 switch (E->getCastKind()) {
10385 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010386 case CK_BaseToDerived:
10387 case CK_DerivedToBase:
10388 case CK_UncheckedDerivedToBase:
10389 case CK_Dynamic:
10390 case CK_ToUnion:
10391 case CK_ArrayToPointerDecay:
10392 case CK_FunctionToPointerDecay:
10393 case CK_NullToPointer:
10394 case CK_NullToMemberPointer:
10395 case CK_BaseToDerivedMemberPointer:
10396 case CK_DerivedToBaseMemberPointer:
10397 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +000010398 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +000010399 case CK_ConstructorConversion:
10400 case CK_IntegralToPointer:
10401 case CK_PointerToIntegral:
10402 case CK_PointerToBoolean:
10403 case CK_ToVoid:
10404 case CK_VectorSplat:
10405 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +000010406 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +000010407 case CK_IntegralToBoolean:
10408 case CK_IntegralToFloating:
10409 case CK_FloatingToIntegral:
10410 case CK_FloatingToBoolean:
10411 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +000010412 case CK_CPointerToObjCPointerCast:
10413 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010414 case CK_AnyPointerToBlockPointerCast:
10415 case CK_ObjCObjectLValueCast:
10416 case CK_FloatingComplexToReal:
10417 case CK_FloatingComplexToBoolean:
10418 case CK_IntegralComplexToReal:
10419 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +000010420 case CK_ARCProduceObject:
10421 case CK_ARCConsumeObject:
10422 case CK_ARCReclaimReturnedObject:
10423 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +000010424 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +000010425 case CK_BuiltinFnToFnPtr:
Andrew Savonichevb555b762018-10-23 15:19:20 +000010426 case CK_ZeroToOCLOpaqueType:
Richard Smitha23ab512013-05-23 00:30:41 +000010427 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +000010428 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +000010429 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +000010430 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +000010431 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +000010432 case CK_FixedPointToIntegral:
10433 case CK_IntegralToFixedPoint:
John McCallfcef3cf2010-12-14 17:51:41 +000010434 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +000010435
John McCallfcef3cf2010-12-14 17:51:41 +000010436 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010437 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +000010438 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +000010439 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010440
10441 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +000010442 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +000010443 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010444 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +000010445
10446 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010447 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +000010448 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010449 return false;
10450
John McCallfcef3cf2010-12-14 17:51:41 +000010451 Result.makeComplexFloat();
10452 Result.FloatImag = APFloat(Real.getSemantics());
10453 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010454 }
10455
John McCallfcef3cf2010-12-14 17:51:41 +000010456 case CK_FloatingComplexCast: {
10457 if (!Visit(E->getSubExpr()))
10458 return false;
10459
10460 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10461 QualType From
10462 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10463
Richard Smith357362d2011-12-13 06:39:58 +000010464 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
10465 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010466 }
10467
10468 case CK_FloatingComplexToIntegralComplex: {
10469 if (!Visit(E->getSubExpr()))
10470 return false;
10471
10472 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10473 QualType From
10474 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10475 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +000010476 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
10477 To, Result.IntReal) &&
10478 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
10479 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010480 }
10481
10482 case CK_IntegralRealToComplex: {
10483 APSInt &Real = Result.IntReal;
10484 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
10485 return false;
10486
10487 Result.makeComplexInt();
10488 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
10489 return true;
10490 }
10491
10492 case CK_IntegralComplexCast: {
10493 if (!Visit(E->getSubExpr()))
10494 return false;
10495
10496 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10497 QualType From
10498 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10499
Richard Smith911e1422012-01-30 22:27:01 +000010500 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
10501 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010502 return true;
10503 }
10504
10505 case CK_IntegralComplexToFloatingComplex: {
10506 if (!Visit(E->getSubExpr()))
10507 return false;
10508
Ted Kremenek28831752012-08-23 20:46:57 +000010509 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010510 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +000010511 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +000010512 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +000010513 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
10514 To, Result.FloatReal) &&
10515 HandleIntToFloatCast(Info, E, From, Result.IntImag,
10516 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +000010517 }
10518 }
10519
10520 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +000010521}
10522
John McCall93d91dc2010-05-07 17:22:02 +000010523bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +000010524 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +000010525 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10526
Chandler Carrutha216cad2014-10-11 00:57:18 +000010527 // Track whether the LHS or RHS is real at the type system level. When this is
10528 // the case we can simplify our evaluation strategy.
10529 bool LHSReal = false, RHSReal = false;
10530
10531 bool LHSOK;
10532 if (E->getLHS()->getType()->isRealFloatingType()) {
10533 LHSReal = true;
10534 APFloat &Real = Result.FloatReal;
10535 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
10536 if (LHSOK) {
10537 Result.makeComplexFloat();
10538 Result.FloatImag = APFloat(Real.getSemantics());
10539 }
10540 } else {
10541 LHSOK = Visit(E->getLHS());
10542 }
George Burgess IVa145e252016-05-25 22:38:36 +000010543 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +000010544 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010545
John McCall93d91dc2010-05-07 17:22:02 +000010546 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010547 if (E->getRHS()->getType()->isRealFloatingType()) {
10548 RHSReal = true;
10549 APFloat &Real = RHS.FloatReal;
10550 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
10551 return false;
10552 RHS.makeComplexFloat();
10553 RHS.FloatImag = APFloat(Real.getSemantics());
10554 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +000010555 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010556
Chandler Carrutha216cad2014-10-11 00:57:18 +000010557 assert(!(LHSReal && RHSReal) &&
10558 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010559 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010560 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +000010561 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010562 if (Result.isComplexFloat()) {
10563 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
10564 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010565 if (LHSReal)
10566 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10567 else if (!RHSReal)
10568 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
10569 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010570 } else {
10571 Result.getComplexIntReal() += RHS.getComplexIntReal();
10572 Result.getComplexIntImag() += RHS.getComplexIntImag();
10573 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010574 break;
John McCalle3027922010-08-25 11:45:40 +000010575 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010576 if (Result.isComplexFloat()) {
10577 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
10578 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010579 if (LHSReal) {
10580 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10581 Result.getComplexFloatImag().changeSign();
10582 } else if (!RHSReal) {
10583 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
10584 APFloat::rmNearestTiesToEven);
10585 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000010586 } else {
10587 Result.getComplexIntReal() -= RHS.getComplexIntReal();
10588 Result.getComplexIntImag() -= RHS.getComplexIntImag();
10589 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010590 break;
John McCalle3027922010-08-25 11:45:40 +000010591 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010592 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010593 // This is an implementation of complex multiplication according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000010594 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010595 // following naming scheme:
10596 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +000010597 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010598 APFloat &A = LHS.getComplexFloatReal();
10599 APFloat &B = LHS.getComplexFloatImag();
10600 APFloat &C = RHS.getComplexFloatReal();
10601 APFloat &D = RHS.getComplexFloatImag();
10602 APFloat &ResR = Result.getComplexFloatReal();
10603 APFloat &ResI = Result.getComplexFloatImag();
10604 if (LHSReal) {
10605 assert(!RHSReal && "Cannot have two real operands for a complex op!");
10606 ResR = A * C;
10607 ResI = A * D;
10608 } else if (RHSReal) {
10609 ResR = C * A;
10610 ResI = C * B;
10611 } else {
10612 // In the fully general case, we need to handle NaNs and infinities
10613 // robustly.
10614 APFloat AC = A * C;
10615 APFloat BD = B * D;
10616 APFloat AD = A * D;
10617 APFloat BC = B * C;
10618 ResR = AC - BD;
10619 ResI = AD + BC;
10620 if (ResR.isNaN() && ResI.isNaN()) {
10621 bool Recalc = false;
10622 if (A.isInfinity() || B.isInfinity()) {
10623 A = APFloat::copySign(
10624 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10625 B = APFloat::copySign(
10626 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10627 if (C.isNaN())
10628 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10629 if (D.isNaN())
10630 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10631 Recalc = true;
10632 }
10633 if (C.isInfinity() || D.isInfinity()) {
10634 C = APFloat::copySign(
10635 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10636 D = APFloat::copySign(
10637 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10638 if (A.isNaN())
10639 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10640 if (B.isNaN())
10641 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10642 Recalc = true;
10643 }
10644 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
10645 AD.isInfinity() || BC.isInfinity())) {
10646 if (A.isNaN())
10647 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10648 if (B.isNaN())
10649 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10650 if (C.isNaN())
10651 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10652 if (D.isNaN())
10653 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10654 Recalc = true;
10655 }
10656 if (Recalc) {
10657 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
10658 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
10659 }
10660 }
10661 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010662 } else {
John McCall93d91dc2010-05-07 17:22:02 +000010663 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +000010664 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010665 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
10666 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +000010667 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +000010668 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
10669 LHS.getComplexIntImag() * RHS.getComplexIntReal());
10670 }
10671 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010672 case BO_Div:
10673 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +000010674 // This is an implementation of complex division according to the
Raphael Isemannb23ccec2018-12-10 12:37:46 +000010675 // constraints laid out in C11 Annex G. The implementation uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +000010676 // following naming scheme:
10677 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010678 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +000010679 APFloat &A = LHS.getComplexFloatReal();
10680 APFloat &B = LHS.getComplexFloatImag();
10681 APFloat &C = RHS.getComplexFloatReal();
10682 APFloat &D = RHS.getComplexFloatImag();
10683 APFloat &ResR = Result.getComplexFloatReal();
10684 APFloat &ResI = Result.getComplexFloatImag();
10685 if (RHSReal) {
10686 ResR = A / C;
10687 ResI = B / C;
10688 } else {
10689 if (LHSReal) {
10690 // No real optimizations we can do here, stub out with zero.
10691 B = APFloat::getZero(A.getSemantics());
10692 }
10693 int DenomLogB = 0;
10694 APFloat MaxCD = maxnum(abs(C), abs(D));
10695 if (MaxCD.isFinite()) {
10696 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +000010697 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
10698 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010699 }
10700 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +000010701 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
10702 APFloat::rmNearestTiesToEven);
10703 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
10704 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +000010705 if (ResR.isNaN() && ResI.isNaN()) {
10706 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
10707 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
10708 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
10709 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
10710 D.isFinite()) {
10711 A = APFloat::copySign(
10712 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10713 B = APFloat::copySign(
10714 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10715 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
10716 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
10717 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
10718 C = APFloat::copySign(
10719 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10720 D = APFloat::copySign(
10721 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10722 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
10723 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
10724 }
10725 }
10726 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010727 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +000010728 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
10729 return Error(E, diag::note_expr_divide_by_zero);
10730
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010731 ComplexValue LHS = Result;
10732 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
10733 RHS.getComplexIntImag() * RHS.getComplexIntImag();
10734 Result.getComplexIntReal() =
10735 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10736 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10737 Result.getComplexIntImag() =
10738 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10739 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10740 }
10741 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010742 }
10743
John McCall93d91dc2010-05-07 17:22:02 +000010744 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +000010745}
10746
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010747bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10748 // Get the operand value into 'Result'.
10749 if (!Visit(E->getSubExpr()))
10750 return false;
10751
10752 switch (E->getOpcode()) {
10753 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +000010754 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +000010755 case UO_Extension:
10756 return true;
10757 case UO_Plus:
10758 // The result is always just the subexpr.
10759 return true;
10760 case UO_Minus:
10761 if (Result.isComplexFloat()) {
10762 Result.getComplexFloatReal().changeSign();
10763 Result.getComplexFloatImag().changeSign();
10764 }
10765 else {
10766 Result.getComplexIntReal() = -Result.getComplexIntReal();
10767 Result.getComplexIntImag() = -Result.getComplexIntImag();
10768 }
10769 return true;
10770 case UO_Not:
10771 if (Result.isComplexFloat())
10772 Result.getComplexFloatImag().changeSign();
10773 else
10774 Result.getComplexIntImag() = -Result.getComplexIntImag();
10775 return true;
10776 }
10777}
10778
Eli Friedmanc4b251d2012-01-10 04:58:17 +000010779bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10780 if (E->getNumInits() == 2) {
10781 if (E->getType()->isComplexType()) {
10782 Result.makeComplexFloat();
10783 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10784 return false;
10785 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10786 return false;
10787 } else {
10788 Result.makeComplexInt();
10789 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10790 return false;
10791 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10792 return false;
10793 }
10794 return true;
10795 }
10796 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10797}
10798
Anders Carlsson537969c2008-11-16 20:27:53 +000010799//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +000010800// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10801// implicit conversion.
10802//===----------------------------------------------------------------------===//
10803
10804namespace {
10805class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +000010806 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010807 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +000010808 APValue &Result;
10809public:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010810 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10811 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +000010812
10813 bool Success(const APValue &V, const Expr *E) {
10814 Result = V;
10815 return true;
10816 }
10817
10818 bool ZeroInitialization(const Expr *E) {
10819 ImplicitValueInitExpr VIE(
10820 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010821 // For atomic-qualified class (and array) types in C++, initialize the
10822 // _Atomic-wrapped subobject directly, in-place.
10823 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10824 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +000010825 }
10826
10827 bool VisitCastExpr(const CastExpr *E) {
10828 switch (E->getCastKind()) {
10829 default:
10830 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10831 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +000010832 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10833 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +000010834 }
10835 }
10836};
10837} // end anonymous namespace
10838
Richard Smith64cb9ca2017-02-22 22:09:50 +000010839static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10840 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +000010841 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +000010842 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000010843}
10844
10845//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000010846// Void expression evaluation, primarily for a cast to void on the LHS of a
10847// comma operator
10848//===----------------------------------------------------------------------===//
10849
10850namespace {
10851class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010852 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000010853public:
10854 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10855
Richard Smith2e312c82012-03-03 22:46:17 +000010856 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000010857
Richard Smith7cd577b2017-08-17 19:35:50 +000010858 bool ZeroInitialization(const Expr *E) { return true; }
10859
Richard Smith42d3af92011-12-07 00:43:50 +000010860 bool VisitCastExpr(const CastExpr *E) {
10861 switch (E->getCastKind()) {
10862 default:
10863 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10864 case CK_ToVoid:
10865 VisitIgnoredValue(E->getSubExpr());
10866 return true;
10867 }
10868 }
Hal Finkela8443c32014-07-17 14:49:58 +000010869
10870 bool VisitCallExpr(const CallExpr *E) {
10871 switch (E->getBuiltinCallee()) {
10872 default:
10873 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10874 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000010875 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000010876 // The argument is not evaluated!
10877 return true;
10878 }
10879 }
Richard Smith42d3af92011-12-07 00:43:50 +000010880};
10881} // end anonymous namespace
10882
10883static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10884 assert(E->isRValue() && E->getType()->isVoidType());
10885 return VoidExprEvaluator(Info).Visit(E);
10886}
10887
10888//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000010889// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000010890//===----------------------------------------------------------------------===//
10891
Richard Smith2e312c82012-03-03 22:46:17 +000010892static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000010893 // In C, function designators are not lvalues, but we evaluate them as if they
10894 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000010895 QualType T = E->getType();
10896 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000010897 LValue LV;
10898 if (!EvaluateLValue(E, LV, Info))
10899 return false;
10900 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010901 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010902 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000010903 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010904 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010905 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010906 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010907 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000010908 LValue LV;
10909 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010910 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010911 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010912 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000010913 llvm::APFloat F(0.0);
10914 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010915 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000010916 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000010917 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000010918 ComplexValue C;
10919 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010920 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010921 C.moveInto(Result);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010922 } else if (T->isFixedPointType()) {
10923 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010924 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000010925 MemberPtr P;
10926 if (!EvaluateMemberPointer(E, P, Info))
10927 return false;
10928 P.moveInto(Result);
10929 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000010930 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010931 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010932 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010933 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000010934 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010935 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010936 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010937 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010938 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010939 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000010940 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010941 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010942 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010943 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010944 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000010945 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000010946 if (!EvaluateVoid(E, Info))
10947 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010948 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010949 QualType Unqual = T.getAtomicUnqualifiedType();
10950 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10951 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010952 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010953 if (!EvaluateAtomic(E, &LV, Value, Info))
10954 return false;
10955 } else {
10956 if (!EvaluateAtomic(E, nullptr, Result, Info))
10957 return false;
10958 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010959 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010960 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010961 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010962 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010963 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010964 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010965 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010966
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010967 return true;
10968}
10969
Richard Smithb228a862012-02-15 02:18:13 +000010970/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10971/// cases, the in-place evaluation is essential, since later initializers for
10972/// an object can indirectly refer to subobjects which were initialized earlier.
10973static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010974 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010975 assert(!E->isValueDependent());
10976
Richard Smith7525ff62013-05-09 07:14:00 +000010977 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010978 return false;
10979
10980 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010981 // Evaluate arrays and record types in-place, so that later initializers can
10982 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010983 QualType T = E->getType();
10984 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010985 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010986 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010987 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010988 else if (T->isAtomicType()) {
10989 QualType Unqual = T.getAtomicUnqualifiedType();
10990 if (Unqual->isArrayType() || Unqual->isRecordType())
10991 return EvaluateAtomic(E, &This, Result, Info);
10992 }
Richard Smithed5165f2011-11-04 05:33:44 +000010993 }
10994
10995 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010996 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010997}
10998
Richard Smithf57d8cb2011-12-09 22:58:01 +000010999/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
11000/// lvalue-to-rvalue cast if it is an lvalue.
11001static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000011002 if (E->getType().isNull())
11003 return false;
11004
Nick Lewyckyc190f962017-05-02 01:06:16 +000011005 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000011006 return false;
11007
Richard Smith2e312c82012-03-03 22:46:17 +000011008 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011009 return false;
11010
11011 if (E->isGLValue()) {
11012 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000011013 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000011014 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000011015 return false;
11016 }
11017
Richard Smith2e312c82012-03-03 22:46:17 +000011018 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000011019 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011020}
Richard Smith11562c52011-10-28 17:51:58 +000011021
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011022static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000011023 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011024 // Fast-path evaluations of integer literals, since we sometimes see files
11025 // containing vast quantities of these.
11026 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
11027 Result.Val = APValue(APSInt(L->getValue(),
11028 L->getType()->isUnsignedIntegerType()));
11029 IsConst = true;
11030 return true;
11031 }
James Dennett0492ef02014-03-14 17:44:10 +000011032
11033 // This case should be rare, but we need to check it before we check on
11034 // the type below.
11035 if (Exp->getType().isNull()) {
11036 IsConst = false;
11037 return true;
11038 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011039
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011040 // FIXME: Evaluating values of large array and record types can cause
11041 // performance problems. Only do so in C++11 for now.
11042 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
11043 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000011044 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011045 IsConst = false;
11046 return true;
11047 }
11048 return false;
11049}
11050
Fangrui Song407659a2018-11-30 23:41:18 +000011051static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
11052 Expr::SideEffectsKind SEK) {
11053 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
11054 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
11055}
11056
11057static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
11058 const ASTContext &Ctx, EvalInfo &Info) {
11059 bool IsConst;
11060 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
11061 return IsConst;
11062
11063 return EvaluateAsRValue(Info, E, Result.Val);
11064}
11065
11066static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
11067 const ASTContext &Ctx,
11068 Expr::SideEffectsKind AllowSideEffects,
11069 EvalInfo &Info) {
11070 if (!E->getType()->isIntegralOrEnumerationType())
11071 return false;
11072
11073 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
11074 !ExprResult.Val.isInt() ||
11075 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11076 return false;
11077
11078 return true;
11079}
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011080
Leonard Chand3f3e162019-01-18 21:04:25 +000011081static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
11082 const ASTContext &Ctx,
11083 Expr::SideEffectsKind AllowSideEffects,
11084 EvalInfo &Info) {
11085 if (!E->getType()->isFixedPointType())
11086 return false;
11087
11088 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
11089 return false;
11090
11091 if (!ExprResult.Val.isFixedPoint() ||
11092 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
11093 return false;
11094
11095 return true;
11096}
11097
Richard Smith7b553f12011-10-29 00:50:52 +000011098/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000011099/// any crazy technique (that has nothing to do with language standards) that
11100/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000011101/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
11102/// will be applied to the result.
Fangrui Song407659a2018-11-30 23:41:18 +000011103bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
11104 bool InConstantContext) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000011105 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Fangrui Song407659a2018-11-30 23:41:18 +000011106 Info.InConstantContext = InConstantContext;
11107 return ::EvaluateAsRValue(this, Result, Ctx, Info);
John McCallc07a0c72011-02-17 10:25:35 +000011108}
11109
Jay Foad39c79802011-01-12 09:06:06 +000011110bool Expr::EvaluateAsBooleanCondition(bool &Result,
11111 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000011112 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000011113 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000011114 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000011115}
11116
Fangrui Song407659a2018-11-30 23:41:18 +000011117bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
Richard Smith5fab0c92011-12-28 19:48:30 +000011118 SideEffectsKind AllowSideEffects) const {
Fangrui Song407659a2018-11-30 23:41:18 +000011119 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11120 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
Richard Smithcaf33902011-10-10 18:28:20 +000011121}
11122
Leonard Chand3f3e162019-01-18 21:04:25 +000011123bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
11124 SideEffectsKind AllowSideEffects) const {
11125 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
11126 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
11127}
11128
Richard Trieube234c32016-04-21 21:04:55 +000011129bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
11130 SideEffectsKind AllowSideEffects) const {
11131 if (!getType()->isRealFloatingType())
11132 return false;
11133
11134 EvalResult ExprResult;
11135 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
Richard Smith3f1d6de2018-05-21 20:36:58 +000011136 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Trieube234c32016-04-21 21:04:55 +000011137 return false;
11138
11139 Result = ExprResult.Val.getFloat();
11140 return true;
11141}
11142
Jay Foad39c79802011-01-12 09:06:06 +000011143bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000011144 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000011145
John McCall45d55e42010-05-07 21:00:08 +000011146 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000011147 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
11148 !CheckLValueConstantExpression(Info, getExprLoc(),
Reid Kleckner1a840d22018-05-10 18:57:35 +000011149 Ctx.getLValueReferenceType(getType()), LV,
11150 Expr::EvaluateForCodeGen))
Richard Smithb228a862012-02-15 02:18:13 +000011151 return false;
11152
Richard Smith2e312c82012-03-03 22:46:17 +000011153 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000011154 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000011155}
11156
Reid Kleckner1a840d22018-05-10 18:57:35 +000011157bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
11158 const ASTContext &Ctx) const {
11159 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
11160 EvalInfo Info(Ctx, Result, EM);
Eric Fiselier680e8652019-03-08 22:06:48 +000011161 Info.InConstantContext = true;
Eric Fiselieradd16a82019-04-24 02:23:30 +000011162
Reid Kleckner1a840d22018-05-10 18:57:35 +000011163 if (!::Evaluate(Result.Val, Info, this))
11164 return false;
11165
11166 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
11167 Usage);
11168}
11169
Richard Smithd0b4dd62011-12-19 06:19:21 +000011170bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
11171 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011172 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000011173 // FIXME: Evaluating initializers for large array and record types can cause
11174 // performance problems. Only do so in C++11 for now.
11175 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011176 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000011177 return false;
11178
Richard Smithd0b4dd62011-12-19 06:19:21 +000011179 Expr::EvalStatus EStatus;
11180 EStatus.Diag = &Notes;
11181
Richard Smith0c6124b2015-12-03 01:36:22 +000011182 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
11183 ? EvalInfo::EM_ConstantExpression
11184 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000011185 InitInfo.setEvaluatingDecl(VD, Value);
Fangrui Song407659a2018-11-30 23:41:18 +000011186 InitInfo.InConstantContext = true;
Richard Smithd0b4dd62011-12-19 06:19:21 +000011187
11188 LValue LVal;
11189 LVal.set(VD);
11190
Richard Smithfddd3842011-12-30 21:15:51 +000011191 // C++11 [basic.start.init]p2:
11192 // Variables with static storage duration or thread storage duration shall be
11193 // zero-initialized before any other initialization takes place.
11194 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011195 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000011196 !VD->getType()->isReferenceType()) {
11197 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000011198 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000011199 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000011200 return false;
11201 }
11202
Richard Smith7525ff62013-05-09 07:14:00 +000011203 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
11204 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000011205 EStatus.HasSideEffects)
11206 return false;
11207
11208 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
11209 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000011210}
11211
Richard Smith7b553f12011-10-29 00:50:52 +000011212/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
11213/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000011214bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000011215 EvalResult Result;
Fangrui Song407659a2018-11-30 23:41:18 +000011216 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
Richard Smith3f1d6de2018-05-21 20:36:58 +000011217 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000011218}
Anders Carlsson59689ed2008-11-22 21:04:56 +000011219
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000011220APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011221 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Fangrui Song407659a2018-11-30 23:41:18 +000011222 EvalResult EVResult;
11223 EVResult.Diag = Diag;
11224 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
11225 Info.InConstantContext = true;
11226
11227 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000011228 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000011229 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000011230 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000011231
Fangrui Song407659a2018-11-30 23:41:18 +000011232 return EVResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000011233}
John McCall864e3962010-05-07 05:32:02 +000011234
David Bolvansky3b6ae572018-10-18 20:49:06 +000011235APSInt Expr::EvaluateKnownConstIntCheckOverflow(
11236 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Fangrui Song407659a2018-11-30 23:41:18 +000011237 EvalResult EVResult;
11238 EVResult.Diag = Diag;
11239 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11240 Info.InConstantContext = true;
11241
11242 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
David Bolvansky3b6ae572018-10-18 20:49:06 +000011243 (void)Result;
11244 assert(Result && "Could not evaluate expression");
Fangrui Song407659a2018-11-30 23:41:18 +000011245 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
David Bolvansky3b6ae572018-10-18 20:49:06 +000011246
Fangrui Song407659a2018-11-30 23:41:18 +000011247 return EVResult.Val.getInt();
David Bolvansky3b6ae572018-10-18 20:49:06 +000011248}
11249
Richard Smithe9ff7702013-11-05 22:23:30 +000011250void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011251 bool IsConst;
Fangrui Song407659a2018-11-30 23:41:18 +000011252 EvalResult EVResult;
11253 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
11254 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11255 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011256 }
11257}
11258
Richard Smithe6c01442013-06-05 00:46:14 +000011259bool Expr::EvalResult::isGlobalLValue() const {
11260 assert(Val.isLValue());
11261 return IsGlobalLValue(Val.getLValueBase());
11262}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000011263
11264
John McCall864e3962010-05-07 05:32:02 +000011265/// isIntegerConstantExpr - this recursive routine will test if an expression is
11266/// an integer constant expression.
11267
11268/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
11269/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000011270
11271// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000011272// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
11273// and a (possibly null) SourceLocation indicating the location of the problem.
11274//
John McCall864e3962010-05-07 05:32:02 +000011275// Note that to reduce code duplication, this helper does no evaluation
11276// itself; the caller checks whether the expression is evaluatable, and
11277// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000011278// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000011279
Dan Gohman28ade552010-07-26 21:25:24 +000011280namespace {
11281
Richard Smith9e575da2012-12-28 13:25:52 +000011282enum ICEKind {
11283 /// This expression is an ICE.
11284 IK_ICE,
11285 /// This expression is not an ICE, but if it isn't evaluated, it's
11286 /// a legal subexpression for an ICE. This return value is used to handle
11287 /// the comma operator in C99 mode, and non-constant subexpressions.
11288 IK_ICEIfUnevaluated,
11289 /// This expression is not an ICE, and is not a legal subexpression for one.
11290 IK_NotICE
11291};
11292
John McCall864e3962010-05-07 05:32:02 +000011293struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000011294 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000011295 SourceLocation Loc;
11296
Richard Smith9e575da2012-12-28 13:25:52 +000011297 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000011298};
11299
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011300}
Dan Gohman28ade552010-07-26 21:25:24 +000011301
Richard Smith9e575da2012-12-28 13:25:52 +000011302static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
11303
11304static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000011305
Craig Toppera31a8822013-08-22 07:09:37 +000011306static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000011307 Expr::EvalResult EVResult;
Fangrui Song407659a2018-11-30 23:41:18 +000011308 Expr::EvalStatus Status;
11309 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11310
11311 Info.InConstantContext = true;
11312 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000011313 !EVResult.Val.isInt())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011314 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith9e575da2012-12-28 13:25:52 +000011315
John McCall864e3962010-05-07 05:32:02 +000011316 return NoDiag();
11317}
11318
Craig Toppera31a8822013-08-22 07:09:37 +000011319static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000011320 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000011321 if (!E->getType()->isIntegralOrEnumerationType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011322 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011323
11324 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000011325#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000011326#define STMT(Node, Base) case Expr::Node##Class:
11327#define EXPR(Node, Base)
11328#include "clang/AST/StmtNodes.inc"
11329 case Expr::PredefinedExprClass:
11330 case Expr::FloatingLiteralClass:
11331 case Expr::ImaginaryLiteralClass:
11332 case Expr::StringLiteralClass:
11333 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011334 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000011335 case Expr::MemberExprClass:
11336 case Expr::CompoundAssignOperatorClass:
11337 case Expr::CompoundLiteralExprClass:
11338 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000011339 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000011340 case Expr::ArrayInitLoopExprClass:
11341 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000011342 case Expr::NoInitExprClass:
11343 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000011344 case Expr::ImplicitValueInitExprClass:
11345 case Expr::ParenListExprClass:
11346 case Expr::VAArgExprClass:
11347 case Expr::AddrLabelExprClass:
11348 case Expr::StmtExprClass:
11349 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000011350 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000011351 case Expr::CXXDynamicCastExprClass:
11352 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000011353 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000011354 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000011355 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011356 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000011357 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011358 case Expr::CXXThisExprClass:
11359 case Expr::CXXThrowExprClass:
11360 case Expr::CXXNewExprClass:
11361 case Expr::CXXDeleteExprClass:
11362 case Expr::CXXPseudoDestructorExprClass:
11363 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000011364 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000011365 case Expr::DependentScopeDeclRefExprClass:
11366 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000011367 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000011368 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000011369 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000011370 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000011371 case Expr::CXXTemporaryObjectExprClass:
11372 case Expr::CXXUnresolvedConstructExprClass:
11373 case Expr::CXXDependentScopeMemberExprClass:
11374 case Expr::UnresolvedMemberExprClass:
11375 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000011376 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011377 case Expr::ObjCArrayLiteralClass:
11378 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011379 case Expr::ObjCEncodeExprClass:
11380 case Expr::ObjCMessageExprClass:
11381 case Expr::ObjCSelectorExprClass:
11382 case Expr::ObjCProtocolExprClass:
11383 case Expr::ObjCIvarRefExprClass:
11384 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011385 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000011386 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000011387 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000011388 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000011389 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000011390 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000011391 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000011392 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000011393 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000011394 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000011395 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000011396 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000011397 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000011398 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000011399 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000011400 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000011401 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000011402 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011403 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000011404 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000011405 case Expr::CoyieldExprClass:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011406 return ICEDiag(IK_NotICE, E->getBeginLoc());
Sebastian Redl12757ab2011-09-24 17:48:14 +000011407
Richard Smithf137f932014-01-25 20:50:08 +000011408 case Expr::InitListExprClass: {
11409 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
11410 // form "T x = { a };" is equivalent to "T x = a;".
11411 // Unless we're initializing a reference, T is a scalar as it is known to be
11412 // of integral or enumeration type.
11413 if (E->isRValue())
11414 if (cast<InitListExpr>(E)->getNumInits() == 1)
11415 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011416 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smithf137f932014-01-25 20:50:08 +000011417 }
11418
Douglas Gregor820ba7b2011-01-04 17:33:58 +000011419 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000011420 case Expr::GNUNullExprClass:
11421 // GCC considers the GNU __null value to be an integral constant expression.
11422 return NoDiag();
11423
John McCall7c454bb2011-07-15 05:09:51 +000011424 case Expr::SubstNonTypeTemplateParmExprClass:
11425 return
11426 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
11427
Bill Wendling7c44da22018-10-31 03:48:47 +000011428 case Expr::ConstantExprClass:
11429 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
11430
John McCall864e3962010-05-07 05:32:02 +000011431 case Expr::ParenExprClass:
11432 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000011433 case Expr::GenericSelectionExprClass:
11434 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011435 case Expr::IntegerLiteralClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +000011436 case Expr::FixedPointLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000011437 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000011438 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000011439 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000011440 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000011441 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000011442 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000011443 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000011444 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000011445 return NoDiag();
11446 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000011447 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000011448 // C99 6.6/3 allows function calls within unevaluated subexpressions of
11449 // constant expressions, but they can never be ICEs because an ICE cannot
11450 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000011451 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000011452 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000011453 return CheckEvalInICE(E, Ctx);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011454 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011455 }
Richard Smith6365c912012-02-24 22:12:32 +000011456 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011457 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
11458 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000011459 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011460 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000011461 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000011462 // Parameter variables are never constants. Without this check,
11463 // getAnyInitializer() can find a default argument, which leads
11464 // to chaos.
11465 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000011466 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011467
11468 // C++ 7.1.5.1p2
11469 // A variable of non-volatile const-qualified integral or enumeration
11470 // type initialized by an ICE can be used in ICEs.
11471 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000011472 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000011473 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000011474
Richard Smithd0b4dd62011-12-19 06:19:21 +000011475 const VarDecl *VD;
11476 // Look for a declaration of this variable that has an initializer, and
11477 // check whether it is an ICE.
11478 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
11479 return NoDiag();
11480 else
Richard Smith9e575da2012-12-28 13:25:52 +000011481 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000011482 }
11483 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011484 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith6365c912012-02-24 22:12:32 +000011485 }
John McCall864e3962010-05-07 05:32:02 +000011486 case Expr::UnaryOperatorClass: {
11487 const UnaryOperator *Exp = cast<UnaryOperator>(E);
11488 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011489 case UO_PostInc:
11490 case UO_PostDec:
11491 case UO_PreInc:
11492 case UO_PreDec:
11493 case UO_AddrOf:
11494 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000011495 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000011496 // C99 6.6/3 allows increment and decrement within unevaluated
11497 // subexpressions of constant expressions, but they can never be ICEs
11498 // because an ICE cannot contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011499 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCalle3027922010-08-25 11:45:40 +000011500 case UO_Extension:
11501 case UO_LNot:
11502 case UO_Plus:
11503 case UO_Minus:
11504 case UO_Not:
11505 case UO_Real:
11506 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000011507 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011508 }
Reid Klecknere540d972018-11-01 17:51:48 +000011509 llvm_unreachable("invalid unary operator class");
John McCall864e3962010-05-07 05:32:02 +000011510 }
11511 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000011512 // Note that per C99, offsetof must be an ICE. And AFAIK, using
11513 // EvaluateAsRValue matches the proposed gcc behavior for cases like
11514 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
11515 // compliance: we should warn earlier for offsetof expressions with
11516 // array subscripts that aren't ICEs, and if the array subscripts
11517 // are ICEs, the value of the offsetof must be an integer constant.
11518 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011519 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000011520 case Expr::UnaryExprOrTypeTraitExprClass: {
11521 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
11522 if ((Exp->getKind() == UETT_SizeOf) &&
11523 Exp->getTypeOfArgument()->isVariableArrayType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011524 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011525 return NoDiag();
11526 }
11527 case Expr::BinaryOperatorClass: {
11528 const BinaryOperator *Exp = cast<BinaryOperator>(E);
11529 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000011530 case BO_PtrMemD:
11531 case BO_PtrMemI:
11532 case BO_Assign:
11533 case BO_MulAssign:
11534 case BO_DivAssign:
11535 case BO_RemAssign:
11536 case BO_AddAssign:
11537 case BO_SubAssign:
11538 case BO_ShlAssign:
11539 case BO_ShrAssign:
11540 case BO_AndAssign:
11541 case BO_XorAssign:
11542 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +000011543 // C99 6.6/3 allows assignments within unevaluated subexpressions of
11544 // constant expressions, but they can never be ICEs because an ICE cannot
11545 // contain an lvalue operand.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011546 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011547
John McCalle3027922010-08-25 11:45:40 +000011548 case BO_Mul:
11549 case BO_Div:
11550 case BO_Rem:
11551 case BO_Add:
11552 case BO_Sub:
11553 case BO_Shl:
11554 case BO_Shr:
11555 case BO_LT:
11556 case BO_GT:
11557 case BO_LE:
11558 case BO_GE:
11559 case BO_EQ:
11560 case BO_NE:
11561 case BO_And:
11562 case BO_Xor:
11563 case BO_Or:
Eric Fiselier0683c0e2018-05-07 21:07:10 +000011564 case BO_Comma:
11565 case BO_Cmp: {
John McCall864e3962010-05-07 05:32:02 +000011566 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11567 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000011568 if (Exp->getOpcode() == BO_Div ||
11569 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000011570 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000011571 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000011572 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000011573 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011574 if (REval == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011575 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011576 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000011577 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000011578 if (LEval.isMinSignedValue())
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011579 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011580 }
11581 }
11582 }
John McCalle3027922010-08-25 11:45:40 +000011583 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011584 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000011585 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
11586 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000011587 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011588 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011589 } else {
11590 // In both C89 and C++, commas in ICEs are illegal.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011591 return ICEDiag(IK_NotICE, E->getBeginLoc());
John McCall864e3962010-05-07 05:32:02 +000011592 }
11593 }
Richard Smith9e575da2012-12-28 13:25:52 +000011594 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011595 }
John McCalle3027922010-08-25 11:45:40 +000011596 case BO_LAnd:
11597 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000011598 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11599 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011600 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000011601 // Rare case where the RHS has a comma "side-effect"; we need
11602 // to actually check the condition to see whether the side
11603 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000011604 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000011605 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000011606 return RHSResult;
11607 return NoDiag();
11608 }
11609
Richard Smith9e575da2012-12-28 13:25:52 +000011610 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000011611 }
11612 }
Reid Klecknere540d972018-11-01 17:51:48 +000011613 llvm_unreachable("invalid binary operator kind");
John McCall864e3962010-05-07 05:32:02 +000011614 }
11615 case Expr::ImplicitCastExprClass:
11616 case Expr::CStyleCastExprClass:
11617 case Expr::CXXFunctionalCastExprClass:
11618 case Expr::CXXStaticCastExprClass:
11619 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000011620 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000011621 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000011622 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000011623 if (isa<ExplicitCastExpr>(E)) {
11624 if (const FloatingLiteral *FL
11625 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
11626 unsigned DestWidth = Ctx.getIntWidth(E->getType());
11627 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
11628 APSInt IgnoredVal(DestWidth, !DestSigned);
11629 bool Ignored;
11630 // If the value does not fit in the destination type, the behavior is
11631 // undefined, so we are not required to treat it as a constant
11632 // expression.
11633 if (FL->getValue().convertToInteger(IgnoredVal,
11634 llvm::APFloat::rmTowardZero,
11635 &Ignored) & APFloat::opInvalidOp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011636 return ICEDiag(IK_NotICE, E->getBeginLoc());
Richard Smith0b973d02011-12-18 02:33:09 +000011637 return NoDiag();
11638 }
11639 }
Eli Friedman76d4e432011-09-29 21:49:34 +000011640 switch (cast<CastExpr>(E)->getCastKind()) {
11641 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000011642 case CK_AtomicToNonAtomic:
11643 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000011644 case CK_NoOp:
11645 case CK_IntegralToBoolean:
11646 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000011647 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000011648 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011649 return ICEDiag(IK_NotICE, E->getBeginLoc());
Eli Friedman76d4e432011-09-29 21:49:34 +000011650 }
John McCall864e3962010-05-07 05:32:02 +000011651 }
John McCallc07a0c72011-02-17 10:25:35 +000011652 case Expr::BinaryConditionalOperatorClass: {
11653 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
11654 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011655 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000011656 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011657 if (FalseResult.Kind == IK_NotICE) return FalseResult;
11658 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
11659 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000011660 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000011661 return FalseResult;
11662 }
John McCall864e3962010-05-07 05:32:02 +000011663 case Expr::ConditionalOperatorClass: {
11664 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
11665 // If the condition (ignoring parens) is a __builtin_constant_p call,
11666 // then only the true side is actually considered in an integer constant
11667 // expression, and it is fully evaluated. This is an important GNU
11668 // extension. See GCC PR38377 for discussion.
11669 if (const CallExpr *CallCE
11670 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000011671 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000011672 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000011673 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000011674 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011675 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011676
Richard Smithf57d8cb2011-12-09 22:58:01 +000011677 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
11678 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000011679
Richard Smith9e575da2012-12-28 13:25:52 +000011680 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011681 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011682 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000011683 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011684 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000011685 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000011686 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000011687 return NoDiag();
11688 // Rare case where the diagnostics depend on which side is evaluated
11689 // Note that if we get here, CondResult is 0, and at least one of
11690 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000011691 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000011692 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000011693 return TrueResult;
11694 }
11695 case Expr::CXXDefaultArgExprClass:
11696 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000011697 case Expr::CXXDefaultInitExprClass:
11698 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011699 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000011700 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000011701 }
11702 }
11703
David Blaikiee4d798f2012-01-20 21:50:17 +000011704 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000011705}
11706
Richard Smithf57d8cb2011-12-09 22:58:01 +000011707/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000011708static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011709 const Expr *E,
11710 llvm::APSInt *Value,
11711 SourceLocation *Loc) {
Erich Keane1ddd4bf2018-07-20 17:42:09 +000011712 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +000011713 if (Loc) *Loc = E->getExprLoc();
11714 return false;
11715 }
11716
Richard Smith66e05fe2012-01-18 05:21:49 +000011717 APValue Result;
11718 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000011719 return false;
11720
Richard Smith98710fc2014-11-13 23:03:19 +000011721 if (!Result.isInt()) {
11722 if (Loc) *Loc = E->getExprLoc();
11723 return false;
11724 }
11725
Richard Smith66e05fe2012-01-18 05:21:49 +000011726 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000011727 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000011728}
11729
Craig Toppera31a8822013-08-22 07:09:37 +000011730bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
11731 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011732 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000011733 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000011734
Richard Smith9e575da2012-12-28 13:25:52 +000011735 ICEDiag D = CheckICE(this, Ctx);
11736 if (D.Kind != IK_ICE) {
11737 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000011738 return false;
11739 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000011740 return true;
11741}
11742
Craig Toppera31a8822013-08-22 07:09:37 +000011743bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000011744 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011745 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000011746 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
11747
11748 if (!isIntegerConstantExpr(Ctx, Loc))
11749 return false;
Fangrui Song407659a2018-11-30 23:41:18 +000011750
Richard Smith5c40f092015-12-04 03:00:44 +000011751 // The only possible side-effects here are due to UB discovered in the
11752 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
11753 // required to treat the expression as an ICE, so we produce the folded
11754 // value.
Fangrui Song407659a2018-11-30 23:41:18 +000011755 EvalResult ExprResult;
11756 Expr::EvalStatus Status;
11757 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
11758 Info.InConstantContext = true;
11759
11760 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
John McCall864e3962010-05-07 05:32:02 +000011761 llvm_unreachable("ICE cannot be evaluated!");
Fangrui Song407659a2018-11-30 23:41:18 +000011762
11763 Value = ExprResult.Val.getInt();
John McCall864e3962010-05-07 05:32:02 +000011764 return true;
11765}
Richard Smith66e05fe2012-01-18 05:21:49 +000011766
Craig Toppera31a8822013-08-22 07:09:37 +000011767bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000011768 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000011769}
11770
Craig Toppera31a8822013-08-22 07:09:37 +000011771bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000011772 SourceLocation *Loc) const {
11773 // We support this checking in C++98 mode in order to diagnose compatibility
11774 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011775 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000011776
Richard Smith98a0a492012-02-14 21:38:30 +000011777 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000011778 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011779 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000011780 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000011781 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000011782
11783 APValue Scratch;
11784 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
11785
11786 if (!Diags.empty()) {
11787 IsConstExpr = false;
11788 if (Loc) *Loc = Diags[0].first;
11789 } else if (!IsConstExpr) {
11790 // FIXME: This shouldn't happen.
11791 if (Loc) *Loc = getExprLoc();
11792 }
11793
11794 return IsConstExpr;
11795}
Richard Smith253c2a32012-01-27 01:14:48 +000011796
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011797bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
11798 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000011799 ArrayRef<const Expr*> Args,
11800 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011801 Expr::EvalStatus Status;
11802 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000011803 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011804
George Burgess IV177399e2017-01-09 04:12:14 +000011805 LValue ThisVal;
11806 const LValue *ThisPtr = nullptr;
11807 if (This) {
11808#ifndef NDEBUG
11809 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11810 assert(MD && "Don't provide `this` for non-methods.");
11811 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11812#endif
11813 if (EvaluateObjectArgument(Info, This, ThisVal))
11814 ThisPtr = &ThisVal;
11815 if (Info.EvalStatus.HasSideEffects)
11816 return false;
11817 }
11818
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011819 ArgVector ArgValues(Args.size());
11820 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11821 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000011822 if ((*I)->isValueDependent() ||
11823 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011824 // If evaluation fails, throw away the argument entirely.
11825 ArgValues[I - Args.begin()] = APValue();
11826 if (Info.EvalStatus.HasSideEffects)
11827 return false;
11828 }
11829
11830 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000011831 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011832 ArgValues.data());
11833 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11834}
11835
Richard Smith253c2a32012-01-27 01:14:48 +000011836bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011837 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000011838 PartialDiagnosticAt> &Diags) {
11839 // FIXME: It would be useful to check constexpr function templates, but at the
11840 // moment the constant expression evaluator cannot cope with the non-rigorous
11841 // ASTs which we build for dependent expressions.
11842 if (FD->isDependentContext())
11843 return true;
11844
11845 Expr::EvalStatus Status;
11846 Status.Diag = &Diags;
11847
Richard Smith6d4c6582013-11-05 22:18:15 +000011848 EvalInfo Info(FD->getASTContext(), Status,
11849 EvalInfo::EM_PotentialConstantExpression);
Fangrui Song407659a2018-11-30 23:41:18 +000011850 Info.InConstantContext = true;
Richard Smith253c2a32012-01-27 01:14:48 +000011851
11852 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000011853 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000011854
Richard Smith7525ff62013-05-09 07:14:00 +000011855 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000011856 // is a temporary being used as the 'this' pointer.
11857 LValue This;
11858 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000011859 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000011860
Richard Smith253c2a32012-01-27 01:14:48 +000011861 ArrayRef<const Expr*> Args;
11862
Richard Smith2e312c82012-03-03 22:46:17 +000011863 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000011864 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11865 // Evaluate the call as a constant initializer, to allow the construction
11866 // of objects of non-literal types.
11867 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000011868 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11869 } else {
11870 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000011871 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000011872 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000011873 }
Richard Smith253c2a32012-01-27 01:14:48 +000011874
11875 return Diags.empty();
11876}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011877
11878bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11879 const FunctionDecl *FD,
11880 SmallVectorImpl<
11881 PartialDiagnosticAt> &Diags) {
11882 Expr::EvalStatus Status;
11883 Status.Diag = &Diags;
11884
11885 EvalInfo Info(FD->getASTContext(), Status,
11886 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
Eric Fiselier680e8652019-03-08 22:06:48 +000011887 Info.InConstantContext = true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011888
11889 // Fabricate a call stack frame to give the arguments a plausible cover story.
11890 ArrayRef<const Expr*> Args;
11891 ArgVector ArgValues(0);
11892 bool Success = EvaluateArgs(Args, ArgValues, Info);
11893 (void)Success;
11894 assert(Success &&
11895 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000011896 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011897
11898 APValue ResultScratch;
11899 Evaluate(ResultScratch, Info, E);
11900 return Diags.empty();
11901}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011902
11903bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11904 unsigned Type) const {
11905 if (!getType()->isPointerType())
11906 return false;
11907
11908 Expr::EvalStatus Status;
11909 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000011910 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011911}