blob: 84ac4daeef973ceb433dcb1153095ce952317e83 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith253c2a32012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Faisal Valia734ab92016-03-26 16:11:37 +000039#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000040#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000041#include "clang/AST/Expr.h"
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"
Anders Carlsson374b93d2008-07-08 05:49:43 +000046#include "clang/Basic/TargetInfo.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Ivan A. Kosarev01df5192018-02-14 13:10:35 +000051#define DEBUG_TYPE "exprconstant"
52
Anders Carlsson7a241ba2008-07-03 04:20:39 +000053using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000054using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000055using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000056
Richard Smithb228a862012-02-15 02:18:13 +000057static bool IsGlobalLValue(APValue::LValueBase B);
58
John McCall93d91dc2010-05-07 17:22:02 +000059namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000060 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000061 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000062 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000063
Richard Smithb228a862012-02-15 02:18:13 +000064 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000065 if (!B) return QualType();
Richard Smith69cf59e2018-03-09 02:00:01 +000066 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +000067 // FIXME: It's unclear where we're supposed to take the type from, and
Richard Smith69cf59e2018-03-09 02:00:01 +000068 // this actually matters for arrays of unknown bound. Eg:
Richard Smith6f4f0f12017-10-20 22:56:25 +000069 //
70 // extern int arr[]; void f() { extern int arr[3]; };
71 // constexpr int *p = &arr[1]; // valid?
Richard Smith69cf59e2018-03-09 02:00:01 +000072 //
73 // For now, we take the array bound from the most recent declaration.
74 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
75 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
76 QualType T = Redecl->getType();
77 if (!T->isIncompleteArrayType())
78 return T;
79 }
80 return D->getType();
81 }
Richard Smith84401042013-06-03 05:03:02 +000082
83 const Expr *Base = B.get<const Expr*>();
84
85 // For a materialized temporary, the type of the temporary we materialized
86 // may not be the type of the expression.
87 if (const MaterializeTemporaryExpr *MTE =
88 dyn_cast<MaterializeTemporaryExpr>(Base)) {
89 SmallVector<const Expr *, 2> CommaLHSs;
90 SmallVector<SubobjectAdjustment, 2> Adjustments;
91 const Expr *Temp = MTE->GetTemporaryExpr();
92 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
93 Adjustments);
94 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000095 // for it directly. Otherwise use the type after adjustment.
96 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000097 return Inner->getType();
98 }
99
100 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +0000101 }
102
Richard Smithd62306a2011-11-10 06:34:14 +0000103 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +0000105 static
Richard Smith84f6dcf2012-02-02 01:16:57 +0000106 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +0000107 APValue::BaseOrMemberType Value;
108 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return Value;
110 }
111
112 /// Get an LValue path entry, which is known to not be an array index, as a
113 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000114 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000115 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000116 }
117 /// Get an LValue path entry, which is known to not be an array index, as a
118 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000119 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000120 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000121 }
122 /// Determine whether this LValue path entry for a base class names a virtual
123 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000124 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000125 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000126 }
127
George Burgess IVe3763372016-12-22 02:50:20 +0000128 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
129 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
130 const FunctionDecl *Callee = CE->getDirectCallee();
131 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
132 }
133
134 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
135 /// This will look through a single cast.
136 ///
137 /// Returns null if we couldn't unwrap a function with alloc_size.
138 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
139 if (!E->getType()->isPointerType())
140 return nullptr;
141
142 E = E->IgnoreParens();
143 // If we're doing a variable assignment from e.g. malloc(N), there will
George Burgess IV47638762018-03-07 04:52:34 +0000144 // probably be a cast of some kind. In exotic cases, we might also see a
145 // top-level ExprWithCleanups. Ignore them either way.
146 if (const auto *EC = dyn_cast<ExprWithCleanups>(E))
147 E = EC->getSubExpr()->IgnoreParens();
148
George Burgess IVe3763372016-12-22 02:50:20 +0000149 if (const auto *Cast = dyn_cast<CastExpr>(E))
150 E = Cast->getSubExpr()->IgnoreParens();
151
152 if (const auto *CE = dyn_cast<CallExpr>(E))
153 return getAllocSizeAttr(CE) ? CE : nullptr;
154 return nullptr;
155 }
156
157 /// Determines whether or not the given Base contains a call to a function
158 /// with the alloc_size attribute.
159 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
160 const auto *E = Base.dyn_cast<const Expr *>();
161 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
162 }
163
Richard Smith6f4f0f12017-10-20 22:56:25 +0000164 /// The bound to claim that an array of unknown bound has.
165 /// The value in MostDerivedArraySize is undefined in this case. So, set it
166 /// to an arbitrary value that's likely to loudly break things if it's used.
167 static const uint64_t AssumedSizeForUnsizedArray =
168 std::numeric_limits<uint64_t>::max() / 2;
169
George Burgess IVe3763372016-12-22 02:50:20 +0000170 /// Determines if an LValue with the given LValueBase will have an unsized
171 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000172 /// Find the path length and type of the most-derived subobject in the given
173 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000174 static unsigned
175 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
176 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000177 uint64_t &ArraySize, QualType &Type, bool &IsArray,
178 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000179 // This only accepts LValueBases from APValues, and APValues don't support
180 // arrays that lack size info.
181 assert(!isBaseAnAllocSizeCall(Base) &&
182 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000183 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000184 Type = getType(Base);
185
Richard Smith80815602011-11-07 05:07:52 +0000186 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000187 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000188 const ArrayType *AT = Ctx.getAsArrayType(Type);
189 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000190 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000191 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000192
193 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
194 ArraySize = CAT->getSize().getZExtValue();
195 } else {
196 assert(I == 0 && "unexpected unsized array designator");
197 FirstEntryIsUnsizedArray = true;
198 ArraySize = AssumedSizeForUnsizedArray;
199 }
Richard Smith66c96992012-02-18 22:04:06 +0000200 } else if (Type->isAnyComplexType()) {
201 const ComplexType *CT = Type->castAs<ComplexType>();
202 Type = CT->getElementType();
203 ArraySize = 2;
204 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000205 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000206 } else if (const FieldDecl *FD = getAsField(Path[I])) {
207 Type = FD->getType();
208 ArraySize = 0;
209 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000210 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000211 } else {
Richard Smith80815602011-11-07 05:07:52 +0000212 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000213 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000214 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000215 }
Richard Smith80815602011-11-07 05:07:52 +0000216 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000218 }
219
Richard Smitha8105bc2012-01-06 16:39:00 +0000220 // The order of this enum is important for diagnostics.
221 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000222 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000223 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000224 };
225
Richard Smith96e0c102011-11-04 02:25:55 +0000226 /// A path from a glvalue to a subobject of that glvalue.
227 struct SubobjectDesignator {
228 /// True if the subobject was named in a manner not supported by C++11. Such
229 /// lvalues can still be folded, but they are not core constant expressions
230 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000231 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000232
Richard Smitha8105bc2012-01-06 16:39:00 +0000233 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000234 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000235
Daniel Jasperffdee092017-05-02 19:21:42 +0000236 /// Indicator of whether the first entry is an unsized array.
237 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000238
George Burgess IVa51c4072015-10-16 01:49:01 +0000239 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000240 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000241
Richard Smitha8105bc2012-01-06 16:39:00 +0000242 /// The length of the path to the most-derived object of which this is a
243 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000244 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000245
George Burgess IVa51c4072015-10-16 01:49:01 +0000246 /// The size of the array of which the most-derived object is an element.
247 /// This will always be 0 if the most-derived object is not an array
248 /// element. 0 is not an indicator of whether or not the most-derived object
249 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000250 ///
251 /// If the current array is an unsized array, the value of this is
252 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000253 uint64_t MostDerivedArraySize;
254
255 /// The type of the most derived object referred to by this address.
256 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000257
Richard Smith80815602011-11-07 05:07:52 +0000258 typedef APValue::LValuePathEntry PathEntry;
259
Richard Smith96e0c102011-11-04 02:25:55 +0000260 /// The entries on the path from the glvalue to the designated subobject.
261 SmallVector<PathEntry, 8> Entries;
262
Richard Smitha8105bc2012-01-06 16:39:00 +0000263 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000264
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000266 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000267 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000268 MostDerivedPathLength(0), MostDerivedArraySize(0),
269 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000270
271 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000272 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000273 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000274 MostDerivedPathLength(0), MostDerivedArraySize(0) {
275 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000276 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000277 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000278 ArrayRef<PathEntry> VEntries = V.getLValuePath();
279 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000280 if (V.getLValueBase()) {
281 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000282 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000283 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000284 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000285 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000286 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000287 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000288 }
Richard Smith80815602011-11-07 05:07:52 +0000289 }
290 }
291
Richard Smith96e0c102011-11-04 02:25:55 +0000292 void setInvalid() {
293 Invalid = true;
294 Entries.clear();
295 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000296
George Burgess IVe3763372016-12-22 02:50:20 +0000297 /// Determine whether the most derived subobject is an array without a
298 /// known bound.
299 bool isMostDerivedAnUnsizedArray() const {
300 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000301 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000302 }
303
304 /// Determine what the most derived array's size is. Results in an assertion
305 /// failure if the most derived array lacks a size.
306 uint64_t getMostDerivedArraySize() const {
307 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
308 return MostDerivedArraySize;
309 }
310
Richard Smitha8105bc2012-01-06 16:39:00 +0000311 /// Determine whether this is a one-past-the-end pointer.
312 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000313 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000314 if (IsOnePastTheEnd)
315 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000316 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000317 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
318 return true;
319 return false;
320 }
321
322 /// Check that this refers to a valid subobject.
323 bool isValidSubobject() const {
324 if (Invalid)
325 return false;
326 return !isOnePastTheEnd();
327 }
328 /// Check that this refers to a valid subobject, and if not, produce a
329 /// relevant diagnostic and set the designator as invalid.
330 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
331
332 /// Update this designator to refer to the first element within this array.
333 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000334 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000335 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000336 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000337
338 // This is a most-derived object.
339 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000340 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000341 MostDerivedArraySize = CAT->getSize().getZExtValue();
342 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000343 }
George Burgess IVe3763372016-12-22 02:50:20 +0000344 /// Update this designator to refer to the first element within the array of
345 /// elements of type T. This is an array of unknown size.
346 void addUnsizedArrayUnchecked(QualType ElemTy) {
347 PathEntry Entry;
348 Entry.ArrayIndex = 0;
349 Entries.push_back(Entry);
350
351 MostDerivedType = ElemTy;
352 MostDerivedIsArrayElement = true;
353 // The value in MostDerivedArraySize is undefined in this case. So, set it
354 // to an arbitrary value that's likely to loudly break things if it's
355 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000356 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000357 MostDerivedPathLength = Entries.size();
358 }
Richard Smith96e0c102011-11-04 02:25:55 +0000359 /// Update this designator to refer to the given base or member of this
360 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000361 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000362 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000363 APValue::BaseOrMemberType Value(D, Virtual);
364 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000365 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000366
367 // If this isn't a base class, it's a new most-derived object.
368 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
369 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000370 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000371 MostDerivedArraySize = 0;
372 MostDerivedPathLength = Entries.size();
373 }
Richard Smith96e0c102011-11-04 02:25:55 +0000374 }
Richard Smith66c96992012-02-18 22:04:06 +0000375 /// Update this designator to refer to the given complex component.
376 void addComplexUnchecked(QualType EltTy, bool Imag) {
377 PathEntry Entry;
378 Entry.ArrayIndex = Imag;
379 Entries.push_back(Entry);
380
381 // This is technically a most-derived object, though in practice this
382 // is unlikely to matter.
383 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000384 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000385 MostDerivedArraySize = 2;
386 MostDerivedPathLength = Entries.size();
387 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000388 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000389 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
390 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000391 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000392 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
393 if (Invalid || !N) return;
394 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
395 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000396 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000397 // Can't verify -- trust that the user is doing the right thing (or if
398 // not, trust that the caller will catch the bad behavior).
399 // FIXME: Should we reject if this overflows, at least?
400 Entries.back().ArrayIndex += TruncatedN;
401 return;
402 }
403
404 // [expr.add]p4: For the purposes of these operators, a pointer to a
405 // nonarray object behaves the same as a pointer to the first element of
406 // an array of length one with the type of the object as its element type.
407 bool IsArray = MostDerivedPathLength == Entries.size() &&
408 MostDerivedIsArrayElement;
409 uint64_t ArrayIndex =
410 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
411 uint64_t ArraySize =
412 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
413
414 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
415 // Calculate the actual index in a wide enough type, so we can include
416 // it in the note.
417 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
418 (llvm::APInt&)N += ArrayIndex;
419 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
420 diagnosePointerArithmetic(Info, E, N);
421 setInvalid();
422 return;
423 }
424
425 ArrayIndex += TruncatedN;
426 assert(ArrayIndex <= ArraySize &&
427 "bounds check succeeded for out-of-bounds index");
428
429 if (IsArray)
430 Entries.back().ArrayIndex = ArrayIndex;
431 else
432 IsOnePastTheEnd = (ArrayIndex != 0);
433 }
Richard Smith96e0c102011-11-04 02:25:55 +0000434 };
435
Richard Smith254a73d2011-10-28 22:34:42 +0000436 /// A stack frame in the constexpr call stack.
437 struct CallStackFrame {
438 EvalInfo &Info;
439
440 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000441 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000442
Richard Smithf6f003a2011-12-16 19:06:07 +0000443 /// Callee - The function which was called.
444 const FunctionDecl *Callee;
445
Richard Smithd62306a2011-11-10 06:34:14 +0000446 /// This - The binding for the this pointer in this call, if any.
447 const LValue *This;
448
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000449 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000450 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000451 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000452
Eli Friedman4830ec82012-06-25 21:21:08 +0000453 // Note that we intentionally use std::map here so that references to
454 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000455 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000456 typedef MapTy::const_iterator temp_iterator;
457 /// Temporaries - Temporary lvalues materialized within this stack frame.
458 MapTy Temporaries;
459
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000460 /// CallLoc - The location of the call expression for this call.
461 SourceLocation CallLoc;
462
463 /// Index - The call index of this call.
464 unsigned Index;
465
Faisal Vali051e3a22017-02-16 04:12:21 +0000466 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
467 // on the overall stack usage of deeply-recursing constexpr evaluataions.
468 // (We should cache this map rather than recomputing it repeatedly.)
469 // But let's try this and see how it goes; we can look into caching the map
470 // as a later change.
471
472 /// LambdaCaptureFields - Mapping from captured variables/this to
473 /// corresponding data members in the closure class.
474 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
475 FieldDecl *LambdaThisCaptureField;
476
Richard Smithf6f003a2011-12-16 19:06:07 +0000477 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
478 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000479 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000480 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000481
482 APValue *getTemporary(const void *Key) {
483 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000484 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000485 }
486 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000487 };
488
Richard Smith852c9db2013-04-20 22:23:05 +0000489 /// Temporarily override 'this'.
490 class ThisOverrideRAII {
491 public:
492 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
493 : Frame(Frame), OldThis(Frame.This) {
494 if (Enable)
495 Frame.This = NewThis;
496 }
497 ~ThisOverrideRAII() {
498 Frame.This = OldThis;
499 }
500 private:
501 CallStackFrame &Frame;
502 const LValue *OldThis;
503 };
504
Richard Smith92b1ce02011-12-12 09:28:41 +0000505 /// A partial diagnostic which we might know in advance that we are not going
506 /// to emit.
507 class OptionalDiagnostic {
508 PartialDiagnostic *Diag;
509
510 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000511 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
512 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000513
514 template<typename T>
515 OptionalDiagnostic &operator<<(const T &v) {
516 if (Diag)
517 *Diag << v;
518 return *this;
519 }
Richard Smithfe800032012-01-31 04:08:20 +0000520
521 OptionalDiagnostic &operator<<(const APSInt &I) {
522 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000523 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000524 I.toString(Buffer);
525 *Diag << StringRef(Buffer.data(), Buffer.size());
526 }
527 return *this;
528 }
529
530 OptionalDiagnostic &operator<<(const APFloat &F) {
531 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000532 // FIXME: Force the precision of the source value down so we don't
533 // print digits which are usually useless (we don't really care here if
534 // we truncate a digit by accident in edge cases). Ideally,
Daniel Jasperffdee092017-05-02 19:21:42 +0000535 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000536 // representation which rounds to the correct value, but it's a bit
537 // tricky to implement.
538 unsigned precision =
539 llvm::APFloat::semanticsPrecision(F.getSemantics());
540 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000541 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000542 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000543 *Diag << StringRef(Buffer.data(), Buffer.size());
544 }
545 return *this;
546 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000547 };
548
Richard Smith08d6a2c2013-07-24 07:11:57 +0000549 /// A cleanup, and a flag indicating whether it is lifetime-extended.
550 class Cleanup {
551 llvm::PointerIntPair<APValue*, 1, bool> Value;
552
553 public:
554 Cleanup(APValue *Val, bool IsLifetimeExtended)
555 : Value(Val, IsLifetimeExtended) {}
556
557 bool isLifetimeExtended() const { return Value.getInt(); }
558 void endLifetime() {
559 *Value.getPointer() = APValue();
560 }
561 };
562
Richard Smithb228a862012-02-15 02:18:13 +0000563 /// EvalInfo - This is a private struct used by the evaluator to capture
564 /// information about a subexpression as it is folded. It retains information
565 /// about the AST context, but also maintains information about the folded
566 /// expression.
567 ///
568 /// If an expression could be evaluated, it is still possible it is not a C
569 /// "integer constant expression" or constant expression. If not, this struct
570 /// captures information about how and why not.
571 ///
572 /// One bit of information passed *into* the request for constant folding
573 /// indicates whether the subexpression is "evaluated" or not according to C
574 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
575 /// evaluate the expression regardless of what the RHS is, but C only allows
576 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000577 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000578 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000579
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000580 /// EvalStatus - Contains information about the evaluation.
581 Expr::EvalStatus &EvalStatus;
582
583 /// CurrentCall - The top of the constexpr call stack.
584 CallStackFrame *CurrentCall;
585
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000586 /// CallStackDepth - The number of calls in the call stack right now.
587 unsigned CallStackDepth;
588
Richard Smithb228a862012-02-15 02:18:13 +0000589 /// NextCallIndex - The next call index to assign.
590 unsigned NextCallIndex;
591
Richard Smitha3d3bd22013-05-08 02:12:03 +0000592 /// StepsLeft - The remaining number of evaluation steps we're permitted
593 /// to perform. This is essentially a limit for the number of statements
594 /// we will evaluate.
595 unsigned StepsLeft;
596
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000597 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000598 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000599 CallStackFrame BottomFrame;
600
Richard Smith08d6a2c2013-07-24 07:11:57 +0000601 /// A stack of values whose lifetimes end at the end of some surrounding
602 /// evaluation frame.
603 llvm::SmallVector<Cleanup, 16> CleanupStack;
604
Richard Smithd62306a2011-11-10 06:34:14 +0000605 /// EvaluatingDecl - This is the declaration whose initializer is being
606 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000607 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000608
609 /// EvaluatingDeclValue - This is the value being constructed for the
610 /// declaration whose initializer is being evaluated, if any.
611 APValue *EvaluatingDeclValue;
612
Erik Pilkington42925492017-10-04 00:18:55 +0000613 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
614 /// the call index that that lvalue was allocated in.
615 typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject;
616
617 /// EvaluatingConstructors - Set of objects that are currently being
618 /// constructed.
619 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
620
621 struct EvaluatingConstructorRAII {
622 EvalInfo &EI;
623 EvaluatingObject Object;
624 bool DidInsert;
625 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
626 : EI(EI), Object(Object) {
627 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
628 }
629 ~EvaluatingConstructorRAII() {
630 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
631 }
632 };
633
634 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) {
635 return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex));
636 }
637
Richard Smith410306b2016-12-12 02:53:20 +0000638 /// The current array initialization index, if we're performing array
639 /// initialization.
640 uint64_t ArrayInitIndex = -1;
641
Richard Smith357362d2011-12-13 06:39:58 +0000642 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
643 /// notes attached to it will also be stored, otherwise they will not be.
644 bool HasActiveDiagnostic;
645
Richard Smith0c6124b2015-12-03 01:36:22 +0000646 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
647 /// fold (not just why it's not strictly a constant expression)?
648 bool HasFoldFailureDiagnostic;
649
George Burgess IV8c892b52016-05-25 22:31:54 +0000650 /// \brief Whether or not we're currently speculatively evaluating.
651 bool IsSpeculativelyEvaluating;
652
Richard Smith6d4c6582013-11-05 22:18:15 +0000653 enum EvaluationMode {
654 /// Evaluate as a constant expression. Stop if we find that the expression
655 /// is not a constant expression.
656 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000657
Richard Smith6d4c6582013-11-05 22:18:15 +0000658 /// Evaluate as a potential constant expression. Keep going if we hit a
659 /// construct that we can't evaluate yet (because we don't yet know the
660 /// value of something) but stop if we hit something that could never be
661 /// a constant expression.
662 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000663
Richard Smith6d4c6582013-11-05 22:18:15 +0000664 /// Fold the expression to a constant. Stop if we hit a side-effect that
665 /// we can't model.
666 EM_ConstantFold,
667
668 /// Evaluate the expression looking for integer overflow and similar
669 /// issues. Don't worry about side-effects, and try to visit all
670 /// subexpressions.
671 EM_EvaluateForOverflow,
672
673 /// Evaluate in any way we know how. Don't worry about side-effects that
674 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000675 EM_IgnoreSideEffects,
676
677 /// Evaluate as a constant expression. Stop if we find that the expression
678 /// is not a constant expression. Some expressions can be retried in the
679 /// optimizer if we don't constant fold them here, but in an unevaluated
680 /// context we try to fold them immediately since the optimizer never
681 /// gets a chance to look at it.
682 EM_ConstantExpressionUnevaluated,
683
684 /// Evaluate as a potential constant expression. Keep going if we hit a
685 /// construct that we can't evaluate yet (because we don't yet know the
686 /// value of something) but stop if we hit something that could never be
687 /// a constant expression. Some expressions can be retried in the
688 /// optimizer if we don't constant fold them here, but in an unevaluated
689 /// context we try to fold them immediately since the optimizer never
690 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000691 EM_PotentialConstantExpressionUnevaluated,
692
George Burgess IVf9013bf2017-02-10 22:52:29 +0000693 /// Evaluate as a constant expression. In certain scenarios, if:
694 /// - we find a MemberExpr with a base that can't be evaluated, or
695 /// - we find a variable initialized with a call to a function that has
696 /// the alloc_size attribute on it
697 /// then we may consider evaluation to have succeeded.
698 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000699 /// In either case, the LValue returned shall have an invalid base; in the
700 /// former, the base will be the invalid MemberExpr, in the latter, the
701 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
702 /// said CallExpr.
703 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000704 } EvalMode;
705
706 /// Are we checking whether the expression is a potential constant
707 /// expression?
708 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000709 return EvalMode == EM_PotentialConstantExpression ||
710 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000711 }
712
713 /// Are we checking an expression for overflow?
714 // FIXME: We should check for any kind of undefined or suspicious behavior
715 // in such constructs, not just overflow.
716 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
717
718 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000719 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000720 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000721 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000722 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
723 EvaluatingDecl((const ValueDecl *)nullptr),
724 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000725 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
726 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000727
Richard Smith7525ff62013-05-09 07:14:00 +0000728 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
729 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000730 EvaluatingDeclValue = &Value;
Erik Pilkington42925492017-10-04 00:18:55 +0000731 EvaluatingConstructors.insert({Base, 0});
Richard Smithd62306a2011-11-10 06:34:14 +0000732 }
733
David Blaikiebbafb8a2012-03-11 07:00:24 +0000734 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000735
Richard Smith357362d2011-12-13 06:39:58 +0000736 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000737 // Don't perform any constexpr calls (other than the call we're checking)
738 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000739 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000740 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000741 if (NextCallIndex == 0) {
742 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000743 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000744 return false;
745 }
Richard Smith357362d2011-12-13 06:39:58 +0000746 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
747 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000748 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000749 << getLangOpts().ConstexprCallDepth;
750 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000751 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000752
Richard Smithb228a862012-02-15 02:18:13 +0000753 CallStackFrame *getCallFrame(unsigned CallIndex) {
754 assert(CallIndex && "no call index in getCallFrame");
755 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
756 // be null in this loop.
757 CallStackFrame *Frame = CurrentCall;
758 while (Frame->Index > CallIndex)
759 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000760 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000761 }
762
Richard Smitha3d3bd22013-05-08 02:12:03 +0000763 bool nextStep(const Stmt *S) {
764 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000765 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000766 return false;
767 }
768 --StepsLeft;
769 return true;
770 }
771
Richard Smith357362d2011-12-13 06:39:58 +0000772 private:
773 /// Add a diagnostic to the diagnostics list.
774 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
775 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
776 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
777 return EvalStatus.Diag->back().second;
778 }
779
Richard Smithf6f003a2011-12-16 19:06:07 +0000780 /// Add notes containing a call stack to the current point of evaluation.
781 void addCallStack(unsigned Limit);
782
Faisal Valie690b7a2016-07-02 22:34:24 +0000783 private:
784 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
785 unsigned ExtraNotes, bool IsCCEDiag) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000786
Richard Smith92b1ce02011-12-12 09:28:41 +0000787 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000788 // If we have a prior diagnostic, it will be noting that the expression
789 // isn't a constant expression. This diagnostic is more important,
790 // unless we require this evaluation to produce a constant expression.
791 //
792 // FIXME: We might want to show both diagnostics to the user in
793 // EM_ConstantFold mode.
794 if (!EvalStatus.Diag->empty()) {
795 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000796 case EM_ConstantFold:
797 case EM_IgnoreSideEffects:
798 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000799 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000800 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000801 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000802 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000803 case EM_ConstantExpression:
804 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000805 case EM_ConstantExpressionUnevaluated:
806 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000807 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000808 HasActiveDiagnostic = false;
809 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000810 }
811 }
812
Richard Smithf6f003a2011-12-16 19:06:07 +0000813 unsigned CallStackNotes = CallStackDepth - 1;
814 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
815 if (Limit)
816 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000817 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000818 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000819
Richard Smith357362d2011-12-13 06:39:58 +0000820 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000821 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000822 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000823 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
824 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000825 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000826 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000827 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000828 }
Richard Smith357362d2011-12-13 06:39:58 +0000829 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000830 return OptionalDiagnostic();
831 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000832 public:
833 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
834 OptionalDiagnostic
835 FFDiag(SourceLocation Loc,
836 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
837 unsigned ExtraNotes = 0) {
838 return Diag(Loc, DiagId, ExtraNotes, false);
839 }
Daniel Jasperffdee092017-05-02 19:21:42 +0000840
Faisal Valie690b7a2016-07-02 22:34:24 +0000841 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000842 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000843 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000844 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000845 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000846 HasActiveDiagnostic = false;
847 return OptionalDiagnostic();
848 }
849
Richard Smith92b1ce02011-12-12 09:28:41 +0000850 /// Diagnose that the evaluation does not produce a C++11 core constant
851 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000852 ///
853 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
854 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000855 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000856 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000857 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000858 // Don't override a previous diagnostic. Don't bother collecting
859 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000860 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000861 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000862 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000863 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000864 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000865 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000866 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
867 = diag::note_invalid_subexpr_in_const_expr,
868 unsigned ExtraNotes = 0) {
869 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
870 }
Richard Smith357362d2011-12-13 06:39:58 +0000871 /// Add a note to a prior diagnostic.
872 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
873 if (!HasActiveDiagnostic)
874 return OptionalDiagnostic();
875 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000876 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000877
878 /// Add a stack of notes to a prior diagnostic.
879 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
880 if (HasActiveDiagnostic) {
881 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
882 Diags.begin(), Diags.end());
883 }
884 }
Richard Smith253c2a32012-01-27 01:14:48 +0000885
Richard Smith6d4c6582013-11-05 22:18:15 +0000886 /// Should we continue evaluation after encountering a side-effect that we
887 /// couldn't model?
888 bool keepEvaluatingAfterSideEffect() {
889 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000890 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000891 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000892 case EM_EvaluateForOverflow:
893 case EM_IgnoreSideEffects:
894 return true;
895
Richard Smith6d4c6582013-11-05 22:18:15 +0000896 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000897 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000898 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000899 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000900 return false;
901 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000902 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000903 }
904
905 /// Note that we have had a side-effect, and determine whether we should
906 /// keep evaluating.
907 bool noteSideEffect() {
908 EvalStatus.HasSideEffects = true;
909 return keepEvaluatingAfterSideEffect();
910 }
911
Richard Smithce8eca52015-12-08 03:21:47 +0000912 /// Should we continue evaluation after encountering undefined behavior?
913 bool keepEvaluatingAfterUndefinedBehavior() {
914 switch (EvalMode) {
915 case EM_EvaluateForOverflow:
916 case EM_IgnoreSideEffects:
917 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000918 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000919 return true;
920
921 case EM_PotentialConstantExpression:
922 case EM_PotentialConstantExpressionUnevaluated:
923 case EM_ConstantExpression:
924 case EM_ConstantExpressionUnevaluated:
925 return false;
926 }
927 llvm_unreachable("Missed EvalMode case");
928 }
929
930 /// Note that we hit something that was technically undefined behavior, but
931 /// that we can evaluate past it (such as signed overflow or floating-point
932 /// division by zero.)
933 bool noteUndefinedBehavior() {
934 EvalStatus.HasUndefinedBehavior = true;
935 return keepEvaluatingAfterUndefinedBehavior();
936 }
937
Richard Smith253c2a32012-01-27 01:14:48 +0000938 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000939 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000940 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000941 if (!StepsLeft)
942 return false;
943
944 switch (EvalMode) {
945 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000946 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000947 case EM_EvaluateForOverflow:
948 return true;
949
950 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000951 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000952 case EM_ConstantFold:
953 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000954 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000955 return false;
956 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000957 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000958 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000959
George Burgess IV8c892b52016-05-25 22:31:54 +0000960 /// Notes that we failed to evaluate an expression that other expressions
961 /// directly depend on, and determine if we should keep evaluating. This
962 /// should only be called if we actually intend to keep evaluating.
963 ///
964 /// Call noteSideEffect() instead if we may be able to ignore the value that
965 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
966 ///
967 /// (Foo(), 1) // use noteSideEffect
968 /// (Foo() || true) // use noteSideEffect
969 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000970 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000971 // Failure when evaluating some expression often means there is some
972 // subexpression whose evaluation was skipped. Therefore, (because we
973 // don't track whether we skipped an expression when unwinding after an
974 // evaluation failure) every evaluation failure that bubbles up from a
975 // subexpression implies that a side-effect has potentially happened. We
976 // skip setting the HasSideEffects flag to true until we decide to
977 // continue evaluating after that point, which happens here.
978 bool KeepGoing = keepEvaluatingAfterFailure();
979 EvalStatus.HasSideEffects |= KeepGoing;
980 return KeepGoing;
981 }
982
Richard Smith410306b2016-12-12 02:53:20 +0000983 class ArrayInitLoopIndex {
984 EvalInfo &Info;
985 uint64_t OuterIndex;
986
987 public:
988 ArrayInitLoopIndex(EvalInfo &Info)
989 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
990 Info.ArrayInitIndex = 0;
991 }
992 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
993
994 operator uint64_t&() { return Info.ArrayInitIndex; }
995 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000996 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000997
998 /// Object used to treat all foldable expressions as constant expressions.
999 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001000 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001001 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001002 bool HadNoPriorDiags;
1003 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001004
Richard Smith6d4c6582013-11-05 22:18:15 +00001005 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1006 : Info(Info),
1007 Enabled(Enabled),
1008 HadNoPriorDiags(Info.EvalStatus.Diag &&
1009 Info.EvalStatus.Diag->empty() &&
1010 !Info.EvalStatus.HasSideEffects),
1011 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001012 if (Enabled &&
1013 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1014 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001015 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001016 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001017 void keepDiagnostics() { Enabled = false; }
1018 ~FoldConstant() {
1019 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001020 !Info.EvalStatus.HasSideEffects)
1021 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001022 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001023 }
1024 };
Richard Smith17100ba2012-02-16 02:46:34 +00001025
George Burgess IV3a03fab2015-09-04 21:28:13 +00001026 /// RAII object used to treat the current evaluation as the correct pointer
1027 /// offset fold for the current EvalMode
1028 struct FoldOffsetRAII {
1029 EvalInfo &Info;
1030 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +00001031 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001032 : Info(Info), OldMode(Info.EvalMode) {
1033 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +00001034 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001035 }
1036
1037 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1038 };
1039
George Burgess IV8c892b52016-05-25 22:31:54 +00001040 /// RAII object used to optionally suppress diagnostics and side-effects from
1041 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001042 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001043 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001044 Expr::EvalStatus OldStatus;
1045 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001046
George Burgess IV8c892b52016-05-25 22:31:54 +00001047 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001048 Info = Other.Info;
1049 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001050 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001051 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001052 }
1053
1054 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001055 if (!Info)
1056 return;
1057
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001058 Info->EvalStatus = OldStatus;
1059 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001060 }
1061
Richard Smith17100ba2012-02-16 02:46:34 +00001062 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001063 SpeculativeEvaluationRAII() = default;
1064
1065 SpeculativeEvaluationRAII(
1066 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001067 : Info(&Info), OldStatus(Info.EvalStatus),
1068 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001069 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001070 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001071 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001072
1073 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1074 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1075 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001076 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001077
1078 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1079 maybeRestoreState();
1080 moveFromAndCancel(std::move(Other));
1081 return *this;
1082 }
1083
1084 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001085 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001086
1087 /// RAII object wrapping a full-expression or block scope, and handling
1088 /// the ending of the lifetime of temporaries created within it.
1089 template<bool IsFullExpression>
1090 class ScopeRAII {
1091 EvalInfo &Info;
1092 unsigned OldStackSize;
1093 public:
1094 ScopeRAII(EvalInfo &Info)
1095 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1096 ~ScopeRAII() {
1097 // Body moved to a static method to encourage the compiler to inline away
1098 // instances of this class.
1099 cleanup(Info, OldStackSize);
1100 }
1101 private:
1102 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1103 unsigned NewEnd = OldStackSize;
1104 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1105 I != N; ++I) {
1106 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1107 // Full-expression cleanup of a lifetime-extended temporary: nothing
1108 // to do, just move this cleanup to the right place in the stack.
1109 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1110 ++NewEnd;
1111 } else {
1112 // End the lifetime of the object.
1113 Info.CleanupStack[I].endLifetime();
1114 }
1115 }
1116 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1117 Info.CleanupStack.end());
1118 }
1119 };
1120 typedef ScopeRAII<false> BlockScopeRAII;
1121 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001122}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001123
Richard Smitha8105bc2012-01-06 16:39:00 +00001124bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1125 CheckSubobjectKind CSK) {
1126 if (Invalid)
1127 return false;
1128 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001129 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001130 << CSK;
1131 setInvalid();
1132 return false;
1133 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001134 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1135 // must actually be at least one array element; even a VLA cannot have a
1136 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001137 return true;
1138}
1139
Richard Smith6f4f0f12017-10-20 22:56:25 +00001140void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1141 const Expr *E) {
1142 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1143 // Do not set the designator as invalid: we can represent this situation,
1144 // and correct handling of __builtin_object_size requires us to do so.
1145}
1146
Richard Smitha8105bc2012-01-06 16:39:00 +00001147void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001148 const Expr *E,
1149 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001150 // If we're complaining, we must be able to statically determine the size of
1151 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001152 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001153 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001154 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001155 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001156 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001157 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001158 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001159 setInvalid();
1160}
1161
Richard Smithf6f003a2011-12-16 19:06:07 +00001162CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1163 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001164 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001165 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1166 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001167 Info.CurrentCall = this;
1168 ++Info.CallStackDepth;
1169}
1170
1171CallStackFrame::~CallStackFrame() {
1172 assert(Info.CurrentCall == this && "calls retired out of order");
1173 --Info.CallStackDepth;
1174 Info.CurrentCall = Caller;
1175}
1176
Richard Smith08d6a2c2013-07-24 07:11:57 +00001177APValue &CallStackFrame::createTemporary(const void *Key,
1178 bool IsLifetimeExtended) {
1179 APValue &Result = Temporaries[Key];
1180 assert(Result.isUninit() && "temporary created multiple times");
1181 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1182 return Result;
1183}
1184
Richard Smith84401042013-06-03 05:03:02 +00001185static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001186
1187void EvalInfo::addCallStack(unsigned Limit) {
1188 // Determine which calls to skip, if any.
1189 unsigned ActiveCalls = CallStackDepth - 1;
1190 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1191 if (Limit && Limit < ActiveCalls) {
1192 SkipStart = Limit / 2 + Limit % 2;
1193 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001194 }
1195
Richard Smithf6f003a2011-12-16 19:06:07 +00001196 // Walk the call stack and add the diagnostics.
1197 unsigned CallIdx = 0;
1198 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1199 Frame = Frame->Caller, ++CallIdx) {
1200 // Skip this call?
1201 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1202 if (CallIdx == SkipStart) {
1203 // Note that we're skipping calls.
1204 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1205 << unsigned(ActiveCalls - Limit);
1206 }
1207 continue;
1208 }
1209
Richard Smith5179eb72016-06-28 19:03:57 +00001210 // Use a different note for an inheriting constructor, because from the
1211 // user's perspective it's not really a function at all.
1212 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1213 if (CD->isInheritingConstructor()) {
1214 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1215 << CD->getParent();
1216 continue;
1217 }
1218 }
1219
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001220 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001221 llvm::raw_svector_ostream Out(Buffer);
1222 describeCall(Frame, Out);
1223 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1224 }
1225}
1226
1227namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001228 struct ComplexValue {
1229 private:
1230 bool IsInt;
1231
1232 public:
1233 APSInt IntReal, IntImag;
1234 APFloat FloatReal, FloatImag;
1235
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001236 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001237
1238 void makeComplexFloat() { IsInt = false; }
1239 bool isComplexFloat() const { return !IsInt; }
1240 APFloat &getComplexFloatReal() { return FloatReal; }
1241 APFloat &getComplexFloatImag() { return FloatImag; }
1242
1243 void makeComplexInt() { IsInt = true; }
1244 bool isComplexInt() const { return IsInt; }
1245 APSInt &getComplexIntReal() { return IntReal; }
1246 APSInt &getComplexIntImag() { return IntImag; }
1247
Richard Smith2e312c82012-03-03 22:46:17 +00001248 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001249 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001250 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001251 else
Richard Smith2e312c82012-03-03 22:46:17 +00001252 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001253 }
Richard Smith2e312c82012-03-03 22:46:17 +00001254 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001255 assert(v.isComplexFloat() || v.isComplexInt());
1256 if (v.isComplexFloat()) {
1257 makeComplexFloat();
1258 FloatReal = v.getComplexFloatReal();
1259 FloatImag = v.getComplexFloatImag();
1260 } else {
1261 makeComplexInt();
1262 IntReal = v.getComplexIntReal();
1263 IntImag = v.getComplexIntImag();
1264 }
1265 }
John McCall93d91dc2010-05-07 17:22:02 +00001266 };
John McCall45d55e42010-05-07 21:00:08 +00001267
1268 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001269 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001270 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001271 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001272 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001273 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001274 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001275
Richard Smithce40ad62011-11-12 22:28:03 +00001276 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001277 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001278 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001279 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001280 SubobjectDesignator &getLValueDesignator() { return Designator; }
1281 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001282 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001283
Richard Smith2e312c82012-03-03 22:46:17 +00001284 void moveInto(APValue &V) const {
1285 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001286 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1287 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001288 else {
1289 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001290 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001291 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001292 }
John McCall45d55e42010-05-07 21:00:08 +00001293 }
Richard Smith2e312c82012-03-03 22:46:17 +00001294 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001295 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001296 Base = V.getLValueBase();
1297 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001298 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001299 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001300 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001301 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001302 }
1303
Tim Northover01503332017-05-26 02:16:00 +00001304 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001305#ifndef NDEBUG
1306 // We only allow a few types of invalid bases. Enforce that here.
1307 if (BInvalid) {
1308 const auto *E = B.get<const Expr *>();
1309 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1310 "Unexpected type of invalid base");
1311 }
1312#endif
1313
Richard Smithce40ad62011-11-12 22:28:03 +00001314 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001315 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001316 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001317 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001318 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001319 IsNullPtr = false;
1320 }
1321
1322 void setNull(QualType PointerTy, uint64_t TargetVal) {
1323 Base = (Expr *)nullptr;
1324 Offset = CharUnits::fromQuantity(TargetVal);
1325 InvalidBase = false;
1326 CallIndex = 0;
1327 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1328 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001329 }
1330
George Burgess IV3a03fab2015-09-04 21:28:13 +00001331 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1332 set(B, I, true);
1333 }
1334
Richard Smitha8105bc2012-01-06 16:39:00 +00001335 // Check that this LValue is not based on a null pointer. If it is, produce
1336 // a diagnostic and mark the designator as invalid.
1337 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1338 CheckSubobjectKind CSK) {
1339 if (Designator.Invalid)
1340 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001341 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001342 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001343 << CSK;
1344 Designator.setInvalid();
1345 return false;
1346 }
1347 return true;
1348 }
1349
1350 // Check this LValue refers to an object. If not, set the designator to be
1351 // invalid and emit a diagnostic.
1352 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001353 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001354 Designator.checkSubobject(Info, E, CSK);
1355 }
1356
1357 void addDecl(EvalInfo &Info, const Expr *E,
1358 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001359 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1360 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001361 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001362 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1363 if (!Designator.Entries.empty()) {
1364 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1365 Designator.setInvalid();
1366 return;
1367 }
Richard Smithefdb5032017-11-15 03:03:56 +00001368 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1369 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1370 Designator.FirstEntryIsAnUnsizedArray = true;
1371 Designator.addUnsizedArrayUnchecked(ElemTy);
1372 }
George Burgess IVe3763372016-12-22 02:50:20 +00001373 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001374 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001375 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1376 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001377 }
Richard Smith66c96992012-02-18 22:04:06 +00001378 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001379 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1380 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001381 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001382 void clearIsNullPointer() {
1383 IsNullPtr = false;
1384 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001385 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1386 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001387 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1388 // but we're not required to diagnose it and it's valid in C++.)
1389 if (!Index)
1390 return;
1391
1392 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1393 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1394 // offsets.
1395 uint64_t Offset64 = Offset.getQuantity();
1396 uint64_t ElemSize64 = ElementSize.getQuantity();
1397 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1398 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1399
1400 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001401 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001402 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001403 }
1404 void adjustOffset(CharUnits N) {
1405 Offset += N;
1406 if (N.getQuantity())
1407 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001408 }
John McCall45d55e42010-05-07 21:00:08 +00001409 };
Richard Smith027bf112011-11-17 22:56:20 +00001410
1411 struct MemberPtr {
1412 MemberPtr() {}
1413 explicit MemberPtr(const ValueDecl *Decl) :
1414 DeclAndIsDerivedMember(Decl, false), Path() {}
1415
1416 /// The member or (direct or indirect) field referred to by this member
1417 /// pointer, or 0 if this is a null member pointer.
1418 const ValueDecl *getDecl() const {
1419 return DeclAndIsDerivedMember.getPointer();
1420 }
1421 /// Is this actually a member of some type derived from the relevant class?
1422 bool isDerivedMember() const {
1423 return DeclAndIsDerivedMember.getInt();
1424 }
1425 /// Get the class which the declaration actually lives in.
1426 const CXXRecordDecl *getContainingRecord() const {
1427 return cast<CXXRecordDecl>(
1428 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1429 }
1430
Richard Smith2e312c82012-03-03 22:46:17 +00001431 void moveInto(APValue &V) const {
1432 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001433 }
Richard Smith2e312c82012-03-03 22:46:17 +00001434 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001435 assert(V.isMemberPointer());
1436 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1437 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1438 Path.clear();
1439 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1440 Path.insert(Path.end(), P.begin(), P.end());
1441 }
1442
1443 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1444 /// whether the member is a member of some class derived from the class type
1445 /// of the member pointer.
1446 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1447 /// Path - The path of base/derived classes from the member declaration's
1448 /// class (exclusive) to the class type of the member pointer (inclusive).
1449 SmallVector<const CXXRecordDecl*, 4> Path;
1450
1451 /// Perform a cast towards the class of the Decl (either up or down the
1452 /// hierarchy).
1453 bool castBack(const CXXRecordDecl *Class) {
1454 assert(!Path.empty());
1455 const CXXRecordDecl *Expected;
1456 if (Path.size() >= 2)
1457 Expected = Path[Path.size() - 2];
1458 else
1459 Expected = getContainingRecord();
1460 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1461 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1462 // if B does not contain the original member and is not a base or
1463 // derived class of the class containing the original member, the result
1464 // of the cast is undefined.
1465 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1466 // (D::*). We consider that to be a language defect.
1467 return false;
1468 }
1469 Path.pop_back();
1470 return true;
1471 }
1472 /// Perform a base-to-derived member pointer cast.
1473 bool castToDerived(const CXXRecordDecl *Derived) {
1474 if (!getDecl())
1475 return true;
1476 if (!isDerivedMember()) {
1477 Path.push_back(Derived);
1478 return true;
1479 }
1480 if (!castBack(Derived))
1481 return false;
1482 if (Path.empty())
1483 DeclAndIsDerivedMember.setInt(false);
1484 return true;
1485 }
1486 /// Perform a derived-to-base member pointer cast.
1487 bool castToBase(const CXXRecordDecl *Base) {
1488 if (!getDecl())
1489 return true;
1490 if (Path.empty())
1491 DeclAndIsDerivedMember.setInt(true);
1492 if (isDerivedMember()) {
1493 Path.push_back(Base);
1494 return true;
1495 }
1496 return castBack(Base);
1497 }
1498 };
Richard Smith357362d2011-12-13 06:39:58 +00001499
Richard Smith7bb00672012-02-01 01:42:44 +00001500 /// Compare two member pointers, which are assumed to be of the same type.
1501 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1502 if (!LHS.getDecl() || !RHS.getDecl())
1503 return !LHS.getDecl() && !RHS.getDecl();
1504 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1505 return false;
1506 return LHS.Path == RHS.Path;
1507 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001508}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001509
Richard Smith2e312c82012-03-03 22:46:17 +00001510static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001511static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1512 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001513 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001514static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1515 bool InvalidBaseOK = false);
1516static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1517 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001518static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1519 EvalInfo &Info);
1520static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001521static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001522static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001523 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001524static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001525static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001526static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1527 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001528static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001529
1530//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001531// Misc utilities
1532//===----------------------------------------------------------------------===//
1533
Richard Smithd6cc1982017-01-31 02:23:02 +00001534/// Negate an APSInt in place, converting it to a signed form if necessary, and
1535/// preserving its value (by extending by up to one bit as needed).
1536static void negateAsSigned(APSInt &Int) {
1537 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1538 Int = Int.extend(Int.getBitWidth() + 1);
1539 Int.setIsSigned(true);
1540 }
1541 Int = -Int;
1542}
1543
Richard Smith84401042013-06-03 05:03:02 +00001544/// Produce a string describing the given constexpr call.
1545static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1546 unsigned ArgIndex = 0;
1547 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1548 !isa<CXXConstructorDecl>(Frame->Callee) &&
1549 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1550
1551 if (!IsMemberCall)
1552 Out << *Frame->Callee << '(';
1553
1554 if (Frame->This && IsMemberCall) {
1555 APValue Val;
1556 Frame->This->moveInto(Val);
1557 Val.printPretty(Out, Frame->Info.Ctx,
1558 Frame->This->Designator.MostDerivedType);
1559 // FIXME: Add parens around Val if needed.
1560 Out << "->" << *Frame->Callee << '(';
1561 IsMemberCall = false;
1562 }
1563
1564 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1565 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1566 if (ArgIndex > (unsigned)IsMemberCall)
1567 Out << ", ";
1568
1569 const ParmVarDecl *Param = *I;
1570 const APValue &Arg = Frame->Arguments[ArgIndex];
1571 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1572
1573 if (ArgIndex == 0 && IsMemberCall)
1574 Out << "->" << *Frame->Callee << '(';
1575 }
1576
1577 Out << ')';
1578}
1579
Richard Smithd9f663b2013-04-22 15:31:51 +00001580/// Evaluate an expression to see if it had side-effects, and discard its
1581/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001582/// \return \c true if the caller should keep evaluating.
1583static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001584 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001585 if (!Evaluate(Scratch, Info, E))
1586 // We don't need the value, but we might have skipped a side effect here.
1587 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001588 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001589}
1590
Richard Smithd62306a2011-11-10 06:34:14 +00001591/// Should this call expression be treated as a string literal?
1592static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001593 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001594 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1595 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1596}
1597
Richard Smithce40ad62011-11-12 22:28:03 +00001598static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001599 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1600 // constant expression of pointer type that evaluates to...
1601
1602 // ... a null pointer value, or a prvalue core constant expression of type
1603 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001604 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001605
Richard Smithce40ad62011-11-12 22:28:03 +00001606 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1607 // ... the address of an object with static storage duration,
1608 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1609 return VD->hasGlobalStorage();
1610 // ... the address of a function,
1611 return isa<FunctionDecl>(D);
1612 }
1613
1614 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001615 switch (E->getStmtClass()) {
1616 default:
1617 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001618 case Expr::CompoundLiteralExprClass: {
1619 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1620 return CLE->isFileScope() && CLE->isLValue();
1621 }
Richard Smithe6c01442013-06-05 00:46:14 +00001622 case Expr::MaterializeTemporaryExprClass:
1623 // A materialized temporary might have been lifetime-extended to static
1624 // storage duration.
1625 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001626 // A string literal has static storage duration.
1627 case Expr::StringLiteralClass:
1628 case Expr::PredefinedExprClass:
1629 case Expr::ObjCStringLiteralClass:
1630 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001631 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001632 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001633 return true;
1634 case Expr::CallExprClass:
1635 return IsStringLiteralCall(cast<CallExpr>(E));
1636 // For GCC compatibility, &&label has static storage duration.
1637 case Expr::AddrLabelExprClass:
1638 return true;
1639 // A Block literal expression may be used as the initialization value for
1640 // Block variables at global or local static scope.
1641 case Expr::BlockExprClass:
1642 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001643 case Expr::ImplicitValueInitExprClass:
1644 // FIXME:
1645 // We can never form an lvalue with an implicit value initialization as its
1646 // base through expression evaluation, so these only appear in one case: the
1647 // implicit variable declaration we invent when checking whether a constexpr
1648 // constructor can produce a constant expression. We must assume that such
1649 // an expression might be a global lvalue.
1650 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001651 }
John McCall95007602010-05-10 23:27:23 +00001652}
1653
Richard Smithb228a862012-02-15 02:18:13 +00001654static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1655 assert(Base && "no location for a null lvalue");
1656 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1657 if (VD)
1658 Info.Note(VD->getLocation(), diag::note_declared_at);
1659 else
Ted Kremenek28831752012-08-23 20:46:57 +00001660 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001661 diag::note_constexpr_temporary_here);
1662}
1663
Richard Smith80815602011-11-07 05:07:52 +00001664/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001665/// value for an address or reference constant expression. Return true if we
1666/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001667static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1668 QualType Type, const LValue &LVal) {
1669 bool IsReferenceType = Type->isReferenceType();
1670
Richard Smith357362d2011-12-13 06:39:58 +00001671 APValue::LValueBase Base = LVal.getLValueBase();
1672 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1673
Richard Smith0dea49e2012-02-18 04:58:18 +00001674 // Check that the object is a global. Note that the fake 'this' object we
1675 // manufacture when checking potential constant expressions is conservatively
1676 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001677 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001678 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001679 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001680 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001681 << IsReferenceType << !Designator.Entries.empty()
1682 << !!VD << VD;
1683 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001684 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001685 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001686 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001687 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001688 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001689 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001690 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001691 LVal.getLValueCallIndex() == 0) &&
1692 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001693
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001694 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1695 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001696 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001697 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001698 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001699
Hans Wennborg82dd8772014-06-25 22:19:48 +00001700 // A dllimport variable never acts like a constant.
1701 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001702 return false;
1703 }
1704 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1705 // __declspec(dllimport) must be handled very carefully:
1706 // We must never initialize an expression with the thunk in C++.
1707 // Doing otherwise would allow the same id-expression to yield
1708 // different addresses for the same function in different translation
1709 // units. However, this means that we must dynamically initialize the
1710 // expression with the contents of the import address table at runtime.
1711 //
1712 // The C language has no notion of ODR; furthermore, it has no notion of
1713 // dynamic initialization. This means that we are permitted to
1714 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001715 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001716 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001717 }
1718 }
1719
Richard Smitha8105bc2012-01-06 16:39:00 +00001720 // Allow address constant expressions to be past-the-end pointers. This is
1721 // an extension: the standard requires them to point to an object.
1722 if (!IsReferenceType)
1723 return true;
1724
1725 // A reference constant expression must refer to an object.
1726 if (!Base) {
1727 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001728 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001729 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001730 }
1731
Richard Smith357362d2011-12-13 06:39:58 +00001732 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001733 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001734 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001735 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001736 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001737 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001738 }
1739
Richard Smith80815602011-11-07 05:07:52 +00001740 return true;
1741}
1742
Reid Klecknercd016d82017-07-07 22:04:29 +00001743/// Member pointers are constant expressions unless they point to a
1744/// non-virtual dllimport member function.
1745static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1746 SourceLocation Loc,
1747 QualType Type,
1748 const APValue &Value) {
1749 const ValueDecl *Member = Value.getMemberPointerDecl();
1750 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1751 if (!FD)
1752 return true;
1753 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1754}
1755
Richard Smithfddd3842011-12-30 21:15:51 +00001756/// Check that this core constant expression is of literal type, and if not,
1757/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001758static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001759 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001760 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001761 return true;
1762
Richard Smith7525ff62013-05-09 07:14:00 +00001763 // C++1y: A constant initializer for an object o [...] may also invoke
1764 // constexpr constructors for o and its subobjects even if those objects
1765 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001766 //
1767 // C++11 missed this detail for aggregates, so classes like this:
1768 // struct foo_t { union { int i; volatile int j; } u; };
1769 // are not (obviously) initializable like so:
1770 // __attribute__((__require_constant_initialization__))
1771 // static const foo_t x = {{0}};
1772 // because "i" is a subobject with non-literal initialization (due to the
1773 // volatile member of the union). See:
1774 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1775 // Therefore, we use the C++1y behavior.
1776 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001777 return true;
1778
Richard Smithfddd3842011-12-30 21:15:51 +00001779 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001780 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001781 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001782 << E->getType();
1783 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001784 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001785 return false;
1786}
1787
Richard Smith0b0a0b62011-10-29 20:57:55 +00001788/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001789/// constant expression. If not, report an appropriate diagnostic. Does not
1790/// check that the expression is of literal type.
1791static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1792 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001793 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001794 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001795 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001796 return false;
1797 }
1798
Richard Smith77be48a2014-07-31 06:31:19 +00001799 // We allow _Atomic(T) to be initialized from anything that T can be
1800 // initialized from.
1801 if (const AtomicType *AT = Type->getAs<AtomicType>())
1802 Type = AT->getValueType();
1803
Richard Smithb228a862012-02-15 02:18:13 +00001804 // Core issue 1454: For a literal constant expression of array or class type,
1805 // each subobject of its value shall have been initialized by a constant
1806 // expression.
1807 if (Value.isArray()) {
1808 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1809 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1810 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1811 Value.getArrayInitializedElt(I)))
1812 return false;
1813 }
1814 if (!Value.hasArrayFiller())
1815 return true;
1816 return CheckConstantExpression(Info, DiagLoc, EltTy,
1817 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001818 }
Richard Smithb228a862012-02-15 02:18:13 +00001819 if (Value.isUnion() && Value.getUnionField()) {
1820 return CheckConstantExpression(Info, DiagLoc,
1821 Value.getUnionField()->getType(),
1822 Value.getUnionValue());
1823 }
1824 if (Value.isStruct()) {
1825 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1826 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1827 unsigned BaseIndex = 0;
1828 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1829 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1830 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1831 Value.getStructBase(BaseIndex)))
1832 return false;
1833 }
1834 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001835 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001836 if (I->isUnnamedBitfield())
1837 continue;
1838
David Blaikie2d7c57e2012-04-30 02:36:29 +00001839 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1840 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001841 return false;
1842 }
1843 }
1844
1845 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001846 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001847 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001848 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1849 }
1850
Reid Klecknercd016d82017-07-07 22:04:29 +00001851 if (Value.isMemberPointer())
1852 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1853
Richard Smithb228a862012-02-15 02:18:13 +00001854 // Everything else is fine.
1855 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001856}
1857
Benjamin Kramer8407df72015-03-09 16:47:52 +00001858static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001859 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001860}
1861
1862static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001863 if (Value.CallIndex)
1864 return false;
1865 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1866 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001867}
1868
Richard Smithcecf1842011-11-01 21:06:14 +00001869static bool IsWeakLValue(const LValue &Value) {
1870 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001871 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001872}
1873
David Majnemerb5116032014-12-09 23:32:34 +00001874static bool isZeroSized(const LValue &Value) {
1875 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001876 if (Decl && isa<VarDecl>(Decl)) {
1877 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001878 if (Ty->isArrayType())
1879 return Ty->isIncompleteType() ||
1880 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001881 }
1882 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001883}
1884
Richard Smith2e312c82012-03-03 22:46:17 +00001885static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001886 // A null base expression indicates a null pointer. These are always
1887 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001888 if (!Value.getLValueBase()) {
1889 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001890 return true;
1891 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001892
Richard Smith027bf112011-11-17 22:56:20 +00001893 // We have a non-null base. These are generally known to be true, but if it's
1894 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001895 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001896 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001897 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001898}
1899
Richard Smith2e312c82012-03-03 22:46:17 +00001900static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001901 switch (Val.getKind()) {
1902 case APValue::Uninitialized:
1903 return false;
1904 case APValue::Int:
1905 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001906 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001907 case APValue::Float:
1908 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001909 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001910 case APValue::ComplexInt:
1911 Result = Val.getComplexIntReal().getBoolValue() ||
1912 Val.getComplexIntImag().getBoolValue();
1913 return true;
1914 case APValue::ComplexFloat:
1915 Result = !Val.getComplexFloatReal().isZero() ||
1916 !Val.getComplexFloatImag().isZero();
1917 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001918 case APValue::LValue:
1919 return EvalPointerValueAsBool(Val, Result);
1920 case APValue::MemberPointer:
1921 Result = Val.getMemberPointerDecl();
1922 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001923 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001924 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001925 case APValue::Struct:
1926 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001927 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001928 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001929 }
1930
Richard Smith11562c52011-10-28 17:51:58 +00001931 llvm_unreachable("unknown APValue kind");
1932}
1933
1934static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1935 EvalInfo &Info) {
1936 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001937 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001938 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001939 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001940 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001941}
1942
Richard Smith357362d2011-12-13 06:39:58 +00001943template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001944static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001945 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001946 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001947 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001948 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001949}
1950
1951static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1952 QualType SrcType, const APFloat &Value,
1953 QualType DestType, APSInt &Result) {
1954 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001955 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001956 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001957
Richard Smith357362d2011-12-13 06:39:58 +00001958 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001959 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001960 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1961 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001962 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001963 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001964}
1965
Richard Smith357362d2011-12-13 06:39:58 +00001966static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1967 QualType SrcType, QualType DestType,
1968 APFloat &Result) {
1969 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001970 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001971 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1972 APFloat::rmNearestTiesToEven, &ignored)
1973 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001974 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001975 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001976}
1977
Richard Smith911e1422012-01-30 22:27:01 +00001978static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1979 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001980 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001981 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001982 APSInt Result = Value;
1983 // Figure out if this is a truncate, extend or noop cast.
1984 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001985 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001986 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001987 return Result;
1988}
1989
Richard Smith357362d2011-12-13 06:39:58 +00001990static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1991 QualType SrcType, const APSInt &Value,
1992 QualType DestType, APFloat &Result) {
1993 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1994 if (Result.convertFromAPInt(Value, Value.isSigned(),
1995 APFloat::rmNearestTiesToEven)
1996 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001997 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001998 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001999}
2000
Richard Smith49ca8aa2013-08-06 07:09:20 +00002001static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2002 APValue &Value, const FieldDecl *FD) {
2003 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2004
2005 if (!Value.isInt()) {
2006 // Trying to store a pointer-cast-to-integer into a bitfield.
2007 // FIXME: In this case, we should provide the diagnostic for casting
2008 // a pointer to an integer.
2009 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002010 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002011 return false;
2012 }
2013
2014 APSInt &Int = Value.getInt();
2015 unsigned OldBitWidth = Int.getBitWidth();
2016 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2017 if (NewBitWidth < OldBitWidth)
2018 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2019 return true;
2020}
2021
Eli Friedman803acb32011-12-22 03:51:45 +00002022static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2023 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002024 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002025 if (!Evaluate(SVal, Info, E))
2026 return false;
2027 if (SVal.isInt()) {
2028 Res = SVal.getInt();
2029 return true;
2030 }
2031 if (SVal.isFloat()) {
2032 Res = SVal.getFloat().bitcastToAPInt();
2033 return true;
2034 }
2035 if (SVal.isVector()) {
2036 QualType VecTy = E->getType();
2037 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2038 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2039 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2040 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2041 Res = llvm::APInt::getNullValue(VecSize);
2042 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2043 APValue &Elt = SVal.getVectorElt(i);
2044 llvm::APInt EltAsInt;
2045 if (Elt.isInt()) {
2046 EltAsInt = Elt.getInt();
2047 } else if (Elt.isFloat()) {
2048 EltAsInt = Elt.getFloat().bitcastToAPInt();
2049 } else {
2050 // Don't try to handle vectors of anything other than int or float
2051 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002052 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002053 return false;
2054 }
2055 unsigned BaseEltSize = EltAsInt.getBitWidth();
2056 if (BigEndian)
2057 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2058 else
2059 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2060 }
2061 return true;
2062 }
2063 // Give up if the input isn't an int, float, or vector. For example, we
2064 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002065 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002066 return false;
2067}
2068
Richard Smith43e77732013-05-07 04:50:00 +00002069/// Perform the given integer operation, which is known to need at most BitWidth
2070/// bits, and check for overflow in the original type (if that type was not an
2071/// unsigned type).
2072template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002073static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2074 const APSInt &LHS, const APSInt &RHS,
2075 unsigned BitWidth, Operation Op,
2076 APSInt &Result) {
2077 if (LHS.isUnsigned()) {
2078 Result = Op(LHS, RHS);
2079 return true;
2080 }
Richard Smith43e77732013-05-07 04:50:00 +00002081
2082 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002083 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002084 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002085 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002086 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002087 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002088 << Result.toString(10) << E->getType();
2089 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002090 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002091 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002092 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002093}
2094
2095/// Perform the given binary integer operation.
2096static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2097 BinaryOperatorKind Opcode, APSInt RHS,
2098 APSInt &Result) {
2099 switch (Opcode) {
2100 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002101 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002102 return false;
2103 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002104 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2105 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002106 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002107 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2108 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002109 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002110 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2111 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002112 case BO_And: Result = LHS & RHS; return true;
2113 case BO_Xor: Result = LHS ^ RHS; return true;
2114 case BO_Or: Result = LHS | RHS; return true;
2115 case BO_Div:
2116 case BO_Rem:
2117 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002118 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002119 return false;
2120 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002121 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2122 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2123 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002124 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2125 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002126 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2127 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002128 return true;
2129 case BO_Shl: {
2130 if (Info.getLangOpts().OpenCL)
2131 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2132 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2133 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2134 RHS.isUnsigned());
2135 else if (RHS.isSigned() && RHS.isNegative()) {
2136 // During constant-folding, a negative shift is an opposite shift. Such
2137 // a shift is not a constant expression.
2138 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2139 RHS = -RHS;
2140 goto shift_right;
2141 }
2142 shift_left:
2143 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2144 // the shifted type.
2145 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2146 if (SA != RHS) {
2147 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2148 << RHS << E->getType() << LHS.getBitWidth();
2149 } else if (LHS.isSigned()) {
2150 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2151 // operand, and must not overflow the corresponding unsigned type.
2152 if (LHS.isNegative())
2153 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2154 else if (LHS.countLeadingZeros() < SA)
2155 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2156 }
2157 Result = LHS << SA;
2158 return true;
2159 }
2160 case BO_Shr: {
2161 if (Info.getLangOpts().OpenCL)
2162 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2163 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2164 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2165 RHS.isUnsigned());
2166 else if (RHS.isSigned() && RHS.isNegative()) {
2167 // During constant-folding, a negative shift is an opposite shift. Such a
2168 // shift is not a constant expression.
2169 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2170 RHS = -RHS;
2171 goto shift_left;
2172 }
2173 shift_right:
2174 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2175 // shifted type.
2176 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2177 if (SA != RHS)
2178 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2179 << RHS << E->getType() << LHS.getBitWidth();
2180 Result = LHS >> SA;
2181 return true;
2182 }
2183
2184 case BO_LT: Result = LHS < RHS; return true;
2185 case BO_GT: Result = LHS > RHS; return true;
2186 case BO_LE: Result = LHS <= RHS; return true;
2187 case BO_GE: Result = LHS >= RHS; return true;
2188 case BO_EQ: Result = LHS == RHS; return true;
2189 case BO_NE: Result = LHS != RHS; return true;
2190 }
2191}
2192
Richard Smith861b5b52013-05-07 23:34:45 +00002193/// Perform the given binary floating-point operation, in-place, on LHS.
2194static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2195 APFloat &LHS, BinaryOperatorKind Opcode,
2196 const APFloat &RHS) {
2197 switch (Opcode) {
2198 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002199 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002200 return false;
2201 case BO_Mul:
2202 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2203 break;
2204 case BO_Add:
2205 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2206 break;
2207 case BO_Sub:
2208 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2209 break;
2210 case BO_Div:
2211 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2212 break;
2213 }
2214
Richard Smith0c6124b2015-12-03 01:36:22 +00002215 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002216 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002217 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002218 }
Richard Smith861b5b52013-05-07 23:34:45 +00002219 return true;
2220}
2221
Richard Smitha8105bc2012-01-06 16:39:00 +00002222/// Cast an lvalue referring to a base subobject to a derived class, by
2223/// truncating the lvalue's path to the given length.
2224static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2225 const RecordDecl *TruncatedType,
2226 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002227 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002228
2229 // Check we actually point to a derived class object.
2230 if (TruncatedElements == D.Entries.size())
2231 return true;
2232 assert(TruncatedElements >= D.MostDerivedPathLength &&
2233 "not casting to a derived class");
2234 if (!Result.checkSubobject(Info, E, CSK_Derived))
2235 return false;
2236
2237 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002238 const RecordDecl *RD = TruncatedType;
2239 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002240 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002241 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2242 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002243 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002244 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002245 else
Richard Smithd62306a2011-11-10 06:34:14 +00002246 Result.Offset -= Layout.getBaseClassOffset(Base);
2247 RD = Base;
2248 }
Richard Smith027bf112011-11-17 22:56:20 +00002249 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002250 return true;
2251}
2252
John McCalld7bca762012-05-01 00:38:49 +00002253static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002254 const CXXRecordDecl *Derived,
2255 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002256 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002257 if (!RL) {
2258 if (Derived->isInvalidDecl()) return false;
2259 RL = &Info.Ctx.getASTRecordLayout(Derived);
2260 }
2261
Richard Smithd62306a2011-11-10 06:34:14 +00002262 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002263 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002264 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002265}
2266
Richard Smitha8105bc2012-01-06 16:39:00 +00002267static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002268 const CXXRecordDecl *DerivedDecl,
2269 const CXXBaseSpecifier *Base) {
2270 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2271
John McCalld7bca762012-05-01 00:38:49 +00002272 if (!Base->isVirtual())
2273 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002274
Richard Smitha8105bc2012-01-06 16:39:00 +00002275 SubobjectDesignator &D = Obj.Designator;
2276 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002277 return false;
2278
Richard Smitha8105bc2012-01-06 16:39:00 +00002279 // Extract most-derived object and corresponding type.
2280 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2281 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2282 return false;
2283
2284 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002285 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002286 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2287 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002288 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002289 return true;
2290}
2291
Richard Smith84401042013-06-03 05:03:02 +00002292static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2293 QualType Type, LValue &Result) {
2294 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2295 PathE = E->path_end();
2296 PathI != PathE; ++PathI) {
2297 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2298 *PathI))
2299 return false;
2300 Type = (*PathI)->getType();
2301 }
2302 return true;
2303}
2304
Richard Smithd62306a2011-11-10 06:34:14 +00002305/// Update LVal to refer to the given field, which must be a member of the type
2306/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002307static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002308 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002309 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002310 if (!RL) {
2311 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002312 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002313 }
Richard Smithd62306a2011-11-10 06:34:14 +00002314
2315 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002316 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002317 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002318 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002319}
2320
Richard Smith1b78b3d2012-01-25 22:15:11 +00002321/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002322static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002323 LValue &LVal,
2324 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002325 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002326 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002327 return false;
2328 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002329}
2330
Richard Smithd62306a2011-11-10 06:34:14 +00002331/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002332static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2333 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002334 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2335 // extension.
2336 if (Type->isVoidType() || Type->isFunctionType()) {
2337 Size = CharUnits::One();
2338 return true;
2339 }
2340
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002341 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002342 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002343 return false;
2344 }
2345
Richard Smithd62306a2011-11-10 06:34:14 +00002346 if (!Type->isConstantSizeType()) {
2347 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002348 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002349 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002350 return false;
2351 }
2352
2353 Size = Info.Ctx.getTypeSizeInChars(Type);
2354 return true;
2355}
2356
2357/// Update a pointer value to model pointer arithmetic.
2358/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002359/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002360/// \param LVal - The pointer value to be updated.
2361/// \param EltTy - The pointee type represented by LVal.
2362/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002363static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2364 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002365 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002366 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002367 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002368 return false;
2369
Yaxun Liu402804b2016-12-15 08:09:08 +00002370 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002371 return true;
2372}
2373
Richard Smithd6cc1982017-01-31 02:23:02 +00002374static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2375 LValue &LVal, QualType EltTy,
2376 int64_t Adjustment) {
2377 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2378 APSInt::get(Adjustment));
2379}
2380
Richard Smith66c96992012-02-18 22:04:06 +00002381/// Update an lvalue to refer to a component of a complex number.
2382/// \param Info - Information about the ongoing evaluation.
2383/// \param LVal - The lvalue to be updated.
2384/// \param EltTy - The complex number's component type.
2385/// \param Imag - False for the real component, true for the imaginary.
2386static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2387 LValue &LVal, QualType EltTy,
2388 bool Imag) {
2389 if (Imag) {
2390 CharUnits SizeOfComponent;
2391 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2392 return false;
2393 LVal.Offset += SizeOfComponent;
2394 }
2395 LVal.addComplex(Info, E, EltTy, Imag);
2396 return true;
2397}
2398
Faisal Vali051e3a22017-02-16 04:12:21 +00002399static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2400 QualType Type, const LValue &LVal,
2401 APValue &RVal);
2402
Richard Smith27908702011-10-24 17:54:18 +00002403/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002404///
2405/// \param Info Information about the ongoing evaluation.
2406/// \param E An expression to be used when printing diagnostics.
2407/// \param VD The variable whose initializer should be obtained.
2408/// \param Frame The frame in which the variable was created. Must be null
2409/// if this variable is not local to the evaluation.
2410/// \param Result Filled in with a pointer to the value of the variable.
2411static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2412 const VarDecl *VD, CallStackFrame *Frame,
2413 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002414
Richard Smith254a73d2011-10-28 22:34:42 +00002415 // If this is a parameter to an active constexpr function call, perform
2416 // argument substitution.
2417 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002418 // Assume arguments of a potential constant expression are unknown
2419 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002420 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002421 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002422 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002423 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002424 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002425 }
Richard Smith3229b742013-05-05 21:17:10 +00002426 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002427 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002428 }
Richard Smith27908702011-10-24 17:54:18 +00002429
Richard Smithd9f663b2013-04-22 15:31:51 +00002430 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002431 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002432 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002433 if (!Result) {
2434 // Assume variables referenced within a lambda's call operator that were
2435 // not declared within the call operator are captures and during checking
2436 // of a potential constant expression, assume they are unknown constant
2437 // expressions.
2438 assert(isLambdaCallOperator(Frame->Callee) &&
2439 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2440 "missing value for local variable");
2441 if (Info.checkingPotentialConstantExpression())
2442 return false;
2443 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002444 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002445 diag::note_unimplemented_constexpr_lambda_feature_ast)
2446 << "captures not currently allowed";
2447 return false;
2448 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002449 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002450 }
2451
Richard Smithd0b4dd62011-12-19 06:19:21 +00002452 // Dig out the initializer, and use the declaration which it's attached to.
2453 const Expr *Init = VD->getAnyInitializer(VD);
2454 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002455 // If we're checking a potential constant expression, the variable could be
2456 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002457 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002458 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002459 return false;
2460 }
2461
Richard Smithd62306a2011-11-10 06:34:14 +00002462 // If we're currently evaluating the initializer of this declaration, use that
2463 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002464 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002465 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002466 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002467 }
2468
Richard Smithcecf1842011-11-01 21:06:14 +00002469 // Never evaluate the initializer of a weak variable. We can't be sure that
2470 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002471 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002472 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002473 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002474 }
Richard Smithcecf1842011-11-01 21:06:14 +00002475
Richard Smithd0b4dd62011-12-19 06:19:21 +00002476 // Check that we can fold the initializer. In C++, we will have already done
2477 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002478 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002479 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002480 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002481 Notes.size() + 1) << VD;
2482 Info.Note(VD->getLocation(), diag::note_declared_at);
2483 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002484 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002485 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002486 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002487 Notes.size() + 1) << VD;
2488 Info.Note(VD->getLocation(), diag::note_declared_at);
2489 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002490 }
Richard Smith27908702011-10-24 17:54:18 +00002491
Richard Smith3229b742013-05-05 21:17:10 +00002492 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002493 return true;
Richard Smith27908702011-10-24 17:54:18 +00002494}
2495
Richard Smith11562c52011-10-28 17:51:58 +00002496static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002497 Qualifiers Quals = T.getQualifiers();
2498 return Quals.hasConst() && !Quals.hasVolatile();
2499}
2500
Richard Smithe97cbd72011-11-11 04:05:33 +00002501/// Get the base index of the given base class within an APValue representing
2502/// the given derived class.
2503static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2504 const CXXRecordDecl *Base) {
2505 Base = Base->getCanonicalDecl();
2506 unsigned Index = 0;
2507 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2508 E = Derived->bases_end(); I != E; ++I, ++Index) {
2509 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2510 return Index;
2511 }
2512
2513 llvm_unreachable("base class missing from derived class's bases list");
2514}
2515
Richard Smith3da88fa2013-04-26 14:36:30 +00002516/// Extract the value of a character from a string literal.
2517static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2518 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002519 // FIXME: Support MakeStringConstant
2520 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2521 std::string Str;
2522 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2523 assert(Index <= Str.size() && "Index too large");
2524 return APSInt::getUnsigned(Str.c_str()[Index]);
2525 }
2526
Alexey Bataevec474782014-10-09 08:45:04 +00002527 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2528 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002529 const StringLiteral *S = cast<StringLiteral>(Lit);
2530 const ConstantArrayType *CAT =
2531 Info.Ctx.getAsConstantArrayType(S->getType());
2532 assert(CAT && "string literal isn't an array");
2533 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002534 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002535
2536 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002537 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002538 if (Index < S->getLength())
2539 Value = S->getCodeUnit(Index);
2540 return Value;
2541}
2542
Richard Smith3da88fa2013-04-26 14:36:30 +00002543// Expand a string literal into an array of characters.
2544static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2545 APValue &Result) {
2546 const StringLiteral *S = cast<StringLiteral>(Lit);
2547 const ConstantArrayType *CAT =
2548 Info.Ctx.getAsConstantArrayType(S->getType());
2549 assert(CAT && "string literal isn't an array");
2550 QualType CharType = CAT->getElementType();
2551 assert(CharType->isIntegerType() && "unexpected character type");
2552
2553 unsigned Elts = CAT->getSize().getZExtValue();
2554 Result = APValue(APValue::UninitArray(),
2555 std::min(S->getLength(), Elts), Elts);
2556 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2557 CharType->isUnsignedIntegerType());
2558 if (Result.hasArrayFiller())
2559 Result.getArrayFiller() = APValue(Value);
2560 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2561 Value = S->getCodeUnit(I);
2562 Result.getArrayInitializedElt(I) = APValue(Value);
2563 }
2564}
2565
2566// Expand an array so that it has more than Index filled elements.
2567static void expandArray(APValue &Array, unsigned Index) {
2568 unsigned Size = Array.getArraySize();
2569 assert(Index < Size);
2570
2571 // Always at least double the number of elements for which we store a value.
2572 unsigned OldElts = Array.getArrayInitializedElts();
2573 unsigned NewElts = std::max(Index+1, OldElts * 2);
2574 NewElts = std::min(Size, std::max(NewElts, 8u));
2575
2576 // Copy the data across.
2577 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2578 for (unsigned I = 0; I != OldElts; ++I)
2579 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2580 for (unsigned I = OldElts; I != NewElts; ++I)
2581 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2582 if (NewValue.hasArrayFiller())
2583 NewValue.getArrayFiller() = Array.getArrayFiller();
2584 Array.swap(NewValue);
2585}
2586
Richard Smithb01fe402014-09-16 01:24:02 +00002587/// Determine whether a type would actually be read by an lvalue-to-rvalue
2588/// conversion. If it's of class type, we may assume that the copy operation
2589/// is trivial. Note that this is never true for a union type with fields
2590/// (because the copy always "reads" the active member) and always true for
2591/// a non-class type.
2592static bool isReadByLvalueToRvalueConversion(QualType T) {
2593 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2594 if (!RD || (RD->isUnion() && !RD->field_empty()))
2595 return true;
2596 if (RD->isEmpty())
2597 return false;
2598
2599 for (auto *Field : RD->fields())
2600 if (isReadByLvalueToRvalueConversion(Field->getType()))
2601 return true;
2602
2603 for (auto &BaseSpec : RD->bases())
2604 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2605 return true;
2606
2607 return false;
2608}
2609
2610/// Diagnose an attempt to read from any unreadable field within the specified
2611/// type, which might be a class type.
2612static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2613 QualType T) {
2614 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2615 if (!RD)
2616 return false;
2617
2618 if (!RD->hasMutableFields())
2619 return false;
2620
2621 for (auto *Field : RD->fields()) {
2622 // If we're actually going to read this field in some way, then it can't
2623 // be mutable. If we're in a union, then assigning to a mutable field
2624 // (even an empty one) can change the active member, so that's not OK.
2625 // FIXME: Add core issue number for the union case.
2626 if (Field->isMutable() &&
2627 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002628 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002629 Info.Note(Field->getLocation(), diag::note_declared_at);
2630 return true;
2631 }
2632
2633 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2634 return true;
2635 }
2636
2637 for (auto &BaseSpec : RD->bases())
2638 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2639 return true;
2640
2641 // All mutable fields were empty, and thus not actually read.
2642 return false;
2643}
2644
Richard Smith861b5b52013-05-07 23:34:45 +00002645/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002646enum AccessKinds {
2647 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002648 AK_Assign,
2649 AK_Increment,
2650 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002651};
2652
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002653namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002654/// A handle to a complete object (an object that is not a subobject of
2655/// another object).
2656struct CompleteObject {
2657 /// The value of the complete object.
2658 APValue *Value;
2659 /// The type of the complete object.
2660 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002661 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002662
Craig Topper36250ad2014-05-12 05:36:57 +00002663 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002664 CompleteObject(APValue *Value, QualType Type,
2665 bool LifetimeStartedInEvaluation)
2666 : Value(Value), Type(Type),
2667 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002668 assert(Value && "missing value for complete object");
2669 }
2670
Aaron Ballman67347662015-02-15 22:00:28 +00002671 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002672};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002673} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002674
Richard Smith3da88fa2013-04-26 14:36:30 +00002675/// Find the designated sub-object of an rvalue.
2676template<typename SubobjectHandler>
2677typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002678findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002679 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002680 if (Sub.Invalid)
2681 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002682 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002683 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002684 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002685 Info.FFDiag(E, Sub.isOnePastTheEnd()
2686 ? diag::note_constexpr_access_past_end
2687 : diag::note_constexpr_access_unsized_array)
2688 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002689 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002690 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002691 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002692 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002693
Richard Smith3229b742013-05-05 21:17:10 +00002694 APValue *O = Obj.Value;
2695 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002696 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002697 const bool MayReadMutableMembers =
2698 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002699
Richard Smithd62306a2011-11-10 06:34:14 +00002700 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002701 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2702 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002703 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002704 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002705 return handler.failed();
2706 }
2707
Richard Smith49ca8aa2013-08-06 07:09:20 +00002708 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002709 // If we are reading an object of class type, there may still be more
2710 // things we need to check: if there are any mutable subobjects, we
2711 // cannot perform this read. (This only happens when performing a trivial
2712 // copy or assignment.)
2713 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002714 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002715 return handler.failed();
2716
Richard Smith49ca8aa2013-08-06 07:09:20 +00002717 if (!handler.found(*O, ObjType))
2718 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002719
Richard Smith49ca8aa2013-08-06 07:09:20 +00002720 // If we modified a bit-field, truncate it to the right width.
2721 if (handler.AccessKind != AK_Read &&
2722 LastField && LastField->isBitField() &&
2723 !truncateBitfieldValue(Info, E, *O, LastField))
2724 return false;
2725
2726 return true;
2727 }
2728
Craig Topper36250ad2014-05-12 05:36:57 +00002729 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002730 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002731 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002732 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002733 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002734 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002735 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002736 // Note, it should not be possible to form a pointer with a valid
2737 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002738 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002739 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002740 << handler.AccessKind;
2741 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002742 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002743 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002744 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002745
2746 ObjType = CAT->getElementType();
2747
Richard Smith14a94132012-02-17 03:35:37 +00002748 // An array object is represented as either an Array APValue or as an
2749 // LValue which refers to a string literal.
2750 if (O->isLValue()) {
2751 assert(I == N - 1 && "extracting subobject of character?");
2752 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002753 if (handler.AccessKind != AK_Read)
2754 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2755 *O);
2756 else
2757 return handler.foundString(*O, ObjType, Index);
2758 }
2759
2760 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002761 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002762 else if (handler.AccessKind != AK_Read) {
2763 expandArray(*O, Index);
2764 O = &O->getArrayInitializedElt(Index);
2765 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002766 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002767 } else if (ObjType->isAnyComplexType()) {
2768 // Next subobject is a complex number.
2769 uint64_t Index = Sub.Entries[I].ArrayIndex;
2770 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002771 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002772 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002773 << handler.AccessKind;
2774 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002775 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002776 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002777 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002778
2779 bool WasConstQualified = ObjType.isConstQualified();
2780 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2781 if (WasConstQualified)
2782 ObjType.addConst();
2783
Richard Smith66c96992012-02-18 22:04:06 +00002784 assert(I == N - 1 && "extracting subobject of scalar?");
2785 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002786 return handler.found(Index ? O->getComplexIntImag()
2787 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002788 } else {
2789 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002790 return handler.found(Index ? O->getComplexFloatImag()
2791 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002792 }
Richard Smithd62306a2011-11-10 06:34:14 +00002793 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002794 // In C++14 onwards, it is permitted to read a mutable member whose
2795 // lifetime began within the evaluation.
2796 // FIXME: Should we also allow this in C++11?
2797 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2798 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002799 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002800 << Field;
2801 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002802 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002803 }
2804
Richard Smithd62306a2011-11-10 06:34:14 +00002805 // Next subobject is a class, struct or union field.
2806 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2807 if (RD->isUnion()) {
2808 const FieldDecl *UnionField = O->getUnionField();
2809 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002810 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002811 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002812 << handler.AccessKind << Field << !UnionField << UnionField;
2813 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002814 }
Richard Smithd62306a2011-11-10 06:34:14 +00002815 O = &O->getUnionValue();
2816 } else
2817 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002818
2819 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002820 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002821 if (WasConstQualified && !Field->isMutable())
2822 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002823
2824 if (ObjType.isVolatileQualified()) {
2825 if (Info.getLangOpts().CPlusPlus) {
2826 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002827 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002828 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002829 Info.Note(Field->getLocation(), diag::note_declared_at);
2830 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002831 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002832 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002833 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002834 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002835
2836 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002837 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002838 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002839 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2840 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2841 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002842
2843 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002844 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002845 if (WasConstQualified)
2846 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002847 }
2848 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002849}
2850
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002851namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002852struct ExtractSubobjectHandler {
2853 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002854 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002855
2856 static const AccessKinds AccessKind = AK_Read;
2857
2858 typedef bool result_type;
2859 bool failed() { return false; }
2860 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002861 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002862 return true;
2863 }
2864 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002865 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002866 return true;
2867 }
2868 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002869 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002870 return true;
2871 }
2872 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002873 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002874 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2875 return true;
2876 }
2877};
Richard Smith3229b742013-05-05 21:17:10 +00002878} // end anonymous namespace
2879
Richard Smith3da88fa2013-04-26 14:36:30 +00002880const AccessKinds ExtractSubobjectHandler::AccessKind;
2881
2882/// Extract the designated sub-object of an rvalue.
2883static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002884 const CompleteObject &Obj,
2885 const SubobjectDesignator &Sub,
2886 APValue &Result) {
2887 ExtractSubobjectHandler Handler = { Info, Result };
2888 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002889}
2890
Richard Smith3229b742013-05-05 21:17:10 +00002891namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002892struct ModifySubobjectHandler {
2893 EvalInfo &Info;
2894 APValue &NewVal;
2895 const Expr *E;
2896
2897 typedef bool result_type;
2898 static const AccessKinds AccessKind = AK_Assign;
2899
2900 bool checkConst(QualType QT) {
2901 // Assigning to a const object has undefined behavior.
2902 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002903 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002904 return false;
2905 }
2906 return true;
2907 }
2908
2909 bool failed() { return false; }
2910 bool found(APValue &Subobj, QualType SubobjType) {
2911 if (!checkConst(SubobjType))
2912 return false;
2913 // We've been given ownership of NewVal, so just swap it in.
2914 Subobj.swap(NewVal);
2915 return true;
2916 }
2917 bool found(APSInt &Value, QualType SubobjType) {
2918 if (!checkConst(SubobjType))
2919 return false;
2920 if (!NewVal.isInt()) {
2921 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002922 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002923 return false;
2924 }
2925 Value = NewVal.getInt();
2926 return true;
2927 }
2928 bool found(APFloat &Value, QualType SubobjType) {
2929 if (!checkConst(SubobjType))
2930 return false;
2931 Value = NewVal.getFloat();
2932 return true;
2933 }
2934 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2935 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2936 }
2937};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002938} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002939
Richard Smith3229b742013-05-05 21:17:10 +00002940const AccessKinds ModifySubobjectHandler::AccessKind;
2941
Richard Smith3da88fa2013-04-26 14:36:30 +00002942/// Update the designated sub-object of an rvalue to the given value.
2943static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002944 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002945 const SubobjectDesignator &Sub,
2946 APValue &NewVal) {
2947 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002948 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002949}
2950
Richard Smith84f6dcf2012-02-02 01:16:57 +00002951/// Find the position where two subobject designators diverge, or equivalently
2952/// the length of the common initial subsequence.
2953static unsigned FindDesignatorMismatch(QualType ObjType,
2954 const SubobjectDesignator &A,
2955 const SubobjectDesignator &B,
2956 bool &WasArrayIndex) {
2957 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2958 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002959 if (!ObjType.isNull() &&
2960 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002961 // Next subobject is an array element.
2962 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2963 WasArrayIndex = true;
2964 return I;
2965 }
Richard Smith66c96992012-02-18 22:04:06 +00002966 if (ObjType->isAnyComplexType())
2967 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2968 else
2969 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002970 } else {
2971 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2972 WasArrayIndex = false;
2973 return I;
2974 }
2975 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2976 // Next subobject is a field.
2977 ObjType = FD->getType();
2978 else
2979 // Next subobject is a base class.
2980 ObjType = QualType();
2981 }
2982 }
2983 WasArrayIndex = false;
2984 return I;
2985}
2986
2987/// Determine whether the given subobject designators refer to elements of the
2988/// same array object.
2989static bool AreElementsOfSameArray(QualType ObjType,
2990 const SubobjectDesignator &A,
2991 const SubobjectDesignator &B) {
2992 if (A.Entries.size() != B.Entries.size())
2993 return false;
2994
George Burgess IVa51c4072015-10-16 01:49:01 +00002995 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002996 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2997 // A is a subobject of the array element.
2998 return false;
2999
3000 // If A (and B) designates an array element, the last entry will be the array
3001 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3002 // of length 1' case, and the entire path must match.
3003 bool WasArrayIndex;
3004 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3005 return CommonLength >= A.Entries.size() - IsArray;
3006}
3007
Richard Smith3229b742013-05-05 21:17:10 +00003008/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003009static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3010 AccessKinds AK, const LValue &LVal,
3011 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003012 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003013 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003014 return CompleteObject();
3015 }
3016
Craig Topper36250ad2014-05-12 05:36:57 +00003017 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00003018 if (LVal.CallIndex) {
3019 Frame = Info.getCallFrame(LVal.CallIndex);
3020 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003021 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003022 << AK << LVal.Base.is<const ValueDecl*>();
3023 NoteLValueLocation(Info, LVal.Base);
3024 return CompleteObject();
3025 }
Richard Smith3229b742013-05-05 21:17:10 +00003026 }
3027
3028 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3029 // is not a constant expression (even if the object is non-volatile). We also
3030 // apply this rule to C++98, in order to conform to the expected 'volatile'
3031 // semantics.
3032 if (LValType.isVolatileQualified()) {
3033 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003034 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003035 << AK << LValType;
3036 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003037 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003038 return CompleteObject();
3039 }
3040
3041 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003042 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003043 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003044 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003045
3046 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3047 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3048 // In C++11, constexpr, non-volatile variables initialized with constant
3049 // expressions are constant expressions too. Inside constexpr functions,
3050 // parameters are constant expressions even if they're non-const.
3051 // In C++1y, objects local to a constant expression (those with a Frame) are
3052 // both readable and writable inside constant expressions.
3053 // In C, such things can also be folded, although they are not ICEs.
3054 const VarDecl *VD = dyn_cast<VarDecl>(D);
3055 if (VD) {
3056 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3057 VD = VDef;
3058 }
3059 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003060 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003061 return CompleteObject();
3062 }
3063
3064 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003065 if (BaseType.isVolatileQualified()) {
3066 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003067 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003068 << AK << 1 << VD;
3069 Info.Note(VD->getLocation(), diag::note_declared_at);
3070 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003071 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003072 }
3073 return CompleteObject();
3074 }
3075
3076 // Unless we're looking at a local variable or argument in a constexpr call,
3077 // the variable we're reading must be const.
3078 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003079 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003080 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3081 // OK, we can read and modify an object if we're in the process of
3082 // evaluating its initializer, because its lifetime began in this
3083 // evaluation.
3084 } else if (AK != AK_Read) {
3085 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003086 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003087 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003088 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003089 // OK, we can read this variable.
3090 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003091 // In OpenCL if a variable is in constant address space it is a const value.
3092 if (!(BaseType.isConstQualified() ||
3093 (Info.getLangOpts().OpenCL &&
3094 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003095 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003096 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003097 Info.Note(VD->getLocation(), diag::note_declared_at);
3098 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003099 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003100 }
3101 return CompleteObject();
3102 }
3103 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3104 // We support folding of const floating-point types, in order to make
3105 // static const data members of such types (supported as an extension)
3106 // more useful.
3107 if (Info.getLangOpts().CPlusPlus11) {
3108 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3109 Info.Note(VD->getLocation(), diag::note_declared_at);
3110 } else {
3111 Info.CCEDiag(E);
3112 }
George Burgess IVb5316982016-12-27 05:33:20 +00003113 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3114 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3115 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003116 } else {
3117 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003118 if (Info.checkingPotentialConstantExpression() &&
3119 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3120 // The definition of this variable could be constexpr. We can't
3121 // access it right now, but may be able to in future.
3122 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003123 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003124 Info.Note(VD->getLocation(), diag::note_declared_at);
3125 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003126 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003127 }
3128 return CompleteObject();
3129 }
3130 }
3131
3132 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3133 return CompleteObject();
3134 } else {
3135 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3136
3137 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003138 if (const MaterializeTemporaryExpr *MTE =
3139 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3140 assert(MTE->getStorageDuration() == SD_Static &&
3141 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003142
Richard Smithe6c01442013-06-05 00:46:14 +00003143 // Per C++1y [expr.const]p2:
3144 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3145 // - a [...] glvalue of integral or enumeration type that refers to
3146 // a non-volatile const object [...]
3147 // [...]
3148 // - a [...] glvalue of literal type that refers to a non-volatile
3149 // object whose lifetime began within the evaluation of e.
3150 //
3151 // C++11 misses the 'began within the evaluation of e' check and
3152 // instead allows all temporaries, including things like:
3153 // int &&r = 1;
3154 // int x = ++r;
3155 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003156 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003157 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3158 const ValueDecl *ED = MTE->getExtendingDecl();
3159 if (!(BaseType.isConstQualified() &&
3160 BaseType->isIntegralOrEnumerationType()) &&
3161 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003162 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003163 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3164 return CompleteObject();
3165 }
3166
3167 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3168 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003169 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003170 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003171 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003172 return CompleteObject();
3173 }
3174 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003175 BaseVal = Frame->getTemporary(Base);
3176 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003177 }
Richard Smith3229b742013-05-05 21:17:10 +00003178
3179 // Volatile temporary objects cannot be accessed in constant expressions.
3180 if (BaseType.isVolatileQualified()) {
3181 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003182 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003183 << AK << 0;
3184 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3185 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003186 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003187 }
3188 return CompleteObject();
3189 }
3190 }
3191
Richard Smith7525ff62013-05-09 07:14:00 +00003192 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003193 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003194 // object under construction.
Erik Pilkington42925492017-10-04 00:18:55 +00003195 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) {
Richard Smith7525ff62013-05-09 07:14:00 +00003196 BaseType = Info.Ctx.getCanonicalType(BaseType);
3197 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003198 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003199 }
3200
Richard Smith9defb7d2018-02-21 03:38:30 +00003201 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003202 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003203 //
3204 // FIXME: Not all local state is mutable. Allow local constant subobjects
3205 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003206 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3207 Info.EvalStatus.HasSideEffects) ||
3208 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003209 return CompleteObject();
3210
Richard Smith9defb7d2018-02-21 03:38:30 +00003211 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003212}
3213
Richard Smith243ef902013-05-05 23:31:59 +00003214/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3215/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3216/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003217///
3218/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003219/// \param Conv - The expression for which we are performing the conversion.
3220/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003221/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3222/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003223/// \param LVal - The glvalue on which we are attempting to perform this action.
3224/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003225static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003226 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003227 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003228 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003229 return false;
3230
Richard Smith3229b742013-05-05 21:17:10 +00003231 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003232 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003233 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003234 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3235 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3236 // initializer until now for such expressions. Such an expression can't be
3237 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003238 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003239 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003240 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003241 }
Richard Smith3229b742013-05-05 21:17:10 +00003242 APValue Lit;
3243 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3244 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003245 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003246 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003247 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003248 // We represent a string literal array as an lvalue pointing at the
3249 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003250 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003251 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smith9defb7d2018-02-21 03:38:30 +00003252 CompleteObject StrObj(&Str, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003253 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003254 }
Richard Smith11562c52011-10-28 17:51:58 +00003255 }
3256
Richard Smith3229b742013-05-05 21:17:10 +00003257 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3258 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003259}
3260
3261/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003262static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003263 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003264 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003265 return false;
3266
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003267 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003268 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003269 return false;
3270 }
3271
Richard Smith3229b742013-05-05 21:17:10 +00003272 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Aaron Ballmana5038552018-01-09 13:07:03 +00003273 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3274}
3275
3276namespace {
3277struct CompoundAssignSubobjectHandler {
3278 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003279 const Expr *E;
3280 QualType PromotedLHSType;
3281 BinaryOperatorKind Opcode;
3282 const APValue &RHS;
3283
3284 static const AccessKinds AccessKind = AK_Assign;
3285
3286 typedef bool result_type;
3287
3288 bool checkConst(QualType QT) {
3289 // Assigning to a const object has undefined behavior.
3290 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003291 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003292 return false;
3293 }
3294 return true;
3295 }
3296
3297 bool failed() { return false; }
3298 bool found(APValue &Subobj, QualType SubobjType) {
3299 switch (Subobj.getKind()) {
3300 case APValue::Int:
3301 return found(Subobj.getInt(), SubobjType);
3302 case APValue::Float:
3303 return found(Subobj.getFloat(), SubobjType);
3304 case APValue::ComplexInt:
3305 case APValue::ComplexFloat:
3306 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003307 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003308 return false;
3309 case APValue::LValue:
3310 return foundPointer(Subobj, SubobjType);
3311 default:
3312 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003313 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003314 return false;
3315 }
3316 }
3317 bool found(APSInt &Value, QualType SubobjType) {
3318 if (!checkConst(SubobjType))
3319 return false;
3320
3321 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3322 // We don't support compound assignment on integer-cast-to-pointer
3323 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003324 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003325 return false;
3326 }
3327
3328 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3329 SubobjType, Value);
3330 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3331 return false;
3332 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3333 return true;
3334 }
3335 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003336 return checkConst(SubobjType) &&
3337 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3338 Value) &&
3339 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3340 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003341 }
3342 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3343 if (!checkConst(SubobjType))
3344 return false;
3345
3346 QualType PointeeType;
3347 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3348 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003349
3350 if (PointeeType.isNull() || !RHS.isInt() ||
3351 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003352 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003353 return false;
3354 }
3355
Richard Smithd6cc1982017-01-31 02:23:02 +00003356 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003357 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003358 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003359
3360 LValue LVal;
3361 LVal.setFrom(Info.Ctx, Subobj);
3362 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3363 return false;
3364 LVal.moveInto(Subobj);
3365 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003366 }
3367 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3368 llvm_unreachable("shouldn't encounter string elements here");
3369 }
3370};
3371} // end anonymous namespace
3372
3373const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3374
3375/// Perform a compound assignment of LVal <op>= RVal.
3376static bool handleCompoundAssignment(
3377 EvalInfo &Info, const Expr *E,
3378 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3379 BinaryOperatorKind Opcode, const APValue &RVal) {
3380 if (LVal.Designator.Invalid)
3381 return false;
3382
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003383 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003384 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003385 return false;
3386 }
3387
3388 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3389 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3390 RVal };
3391 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3392}
3393
Aaron Ballmana5038552018-01-09 13:07:03 +00003394namespace {
3395struct IncDecSubobjectHandler {
3396 EvalInfo &Info;
3397 const UnaryOperator *E;
3398 AccessKinds AccessKind;
3399 APValue *Old;
3400
Richard Smith243ef902013-05-05 23:31:59 +00003401 typedef bool result_type;
3402
3403 bool checkConst(QualType QT) {
3404 // Assigning to a const object has undefined behavior.
3405 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003406 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003407 return false;
3408 }
3409 return true;
3410 }
3411
3412 bool failed() { return false; }
3413 bool found(APValue &Subobj, QualType SubobjType) {
3414 // Stash the old value. Also clear Old, so we don't clobber it later
3415 // if we're post-incrementing a complex.
3416 if (Old) {
3417 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003418 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003419 }
3420
3421 switch (Subobj.getKind()) {
3422 case APValue::Int:
3423 return found(Subobj.getInt(), SubobjType);
3424 case APValue::Float:
3425 return found(Subobj.getFloat(), SubobjType);
3426 case APValue::ComplexInt:
3427 return found(Subobj.getComplexIntReal(),
3428 SubobjType->castAs<ComplexType>()->getElementType()
3429 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3430 case APValue::ComplexFloat:
3431 return found(Subobj.getComplexFloatReal(),
3432 SubobjType->castAs<ComplexType>()->getElementType()
3433 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3434 case APValue::LValue:
3435 return foundPointer(Subobj, SubobjType);
3436 default:
3437 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003438 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003439 return false;
3440 }
3441 }
3442 bool found(APSInt &Value, QualType SubobjType) {
3443 if (!checkConst(SubobjType))
3444 return false;
3445
3446 if (!SubobjType->isIntegerType()) {
3447 // We don't support increment / decrement on integer-cast-to-pointer
3448 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003449 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003450 return false;
3451 }
3452
3453 if (Old) *Old = APValue(Value);
3454
3455 // bool arithmetic promotes to int, and the conversion back to bool
3456 // doesn't reduce mod 2^n, so special-case it.
3457 if (SubobjType->isBooleanType()) {
3458 if (AccessKind == AK_Increment)
3459 Value = 1;
3460 else
3461 Value = !Value;
3462 return true;
3463 }
3464
3465 bool WasNegative = Value.isNegative();
Aaron Ballmana5038552018-01-09 13:07:03 +00003466 if (AccessKind == AK_Increment) {
3467 ++Value;
3468
3469 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3470 APSInt ActualValue(Value, /*IsUnsigned*/true);
3471 return HandleOverflow(Info, E, ActualValue, SubobjType);
3472 }
3473 } else {
3474 --Value;
3475
3476 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3477 unsigned BitWidth = Value.getBitWidth();
3478 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3479 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003480 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003481 }
3482 }
3483 return true;
3484 }
3485 bool found(APFloat &Value, QualType SubobjType) {
3486 if (!checkConst(SubobjType))
3487 return false;
3488
3489 if (Old) *Old = APValue(Value);
3490
3491 APFloat One(Value.getSemantics(), 1);
3492 if (AccessKind == AK_Increment)
3493 Value.add(One, APFloat::rmNearestTiesToEven);
3494 else
3495 Value.subtract(One, APFloat::rmNearestTiesToEven);
3496 return true;
3497 }
3498 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3499 if (!checkConst(SubobjType))
3500 return false;
3501
3502 QualType PointeeType;
3503 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3504 PointeeType = PT->getPointeeType();
3505 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003506 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003507 return false;
3508 }
3509
3510 LValue LVal;
3511 LVal.setFrom(Info.Ctx, Subobj);
3512 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3513 AccessKind == AK_Increment ? 1 : -1))
3514 return false;
3515 LVal.moveInto(Subobj);
3516 return true;
3517 }
3518 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3519 llvm_unreachable("shouldn't encounter string elements here");
3520 }
3521};
3522} // end anonymous namespace
3523
3524/// Perform an increment or decrement on LVal.
3525static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3526 QualType LValType, bool IsIncrement, APValue *Old) {
3527 if (LVal.Designator.Invalid)
3528 return false;
3529
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003530 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003531 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003532 return false;
3533 }
Aaron Ballmana5038552018-01-09 13:07:03 +00003534
3535 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3536 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3537 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3538 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3539}
3540
Richard Smithe97cbd72011-11-11 04:05:33 +00003541/// Build an lvalue for the object argument of a member function call.
3542static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3543 LValue &This) {
3544 if (Object->getType()->isPointerType())
3545 return EvaluatePointer(Object, This, Info);
3546
3547 if (Object->isGLValue())
3548 return EvaluateLValue(Object, This, Info);
3549
Richard Smithd9f663b2013-04-22 15:31:51 +00003550 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003551 return EvaluateTemporary(Object, This, Info);
3552
Faisal Valie690b7a2016-07-02 22:34:24 +00003553 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003554 return false;
3555}
3556
3557/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3558/// lvalue referring to the result.
3559///
3560/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003561/// \param LV - An lvalue referring to the base of the member pointer.
3562/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003563/// \param IncludeMember - Specifies whether the member itself is included in
3564/// the resulting LValue subobject designator. This is not possible when
3565/// creating a bound member function.
3566/// \return The field or method declaration to which the member pointer refers,
3567/// or 0 if evaluation fails.
3568static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003569 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003570 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003571 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003572 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003573 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003574 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003575 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003576
3577 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3578 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003579 if (!MemPtr.getDecl()) {
3580 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003581 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003582 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003583 }
Richard Smith253c2a32012-01-27 01:14:48 +00003584
Richard Smith027bf112011-11-17 22:56:20 +00003585 if (MemPtr.isDerivedMember()) {
3586 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003587 // The end of the derived-to-base path for the base object must match the
3588 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003589 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003590 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003591 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003592 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003593 }
Richard Smith027bf112011-11-17 22:56:20 +00003594 unsigned PathLengthToMember =
3595 LV.Designator.Entries.size() - MemPtr.Path.size();
3596 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3597 const CXXRecordDecl *LVDecl = getAsBaseClass(
3598 LV.Designator.Entries[PathLengthToMember + I]);
3599 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003600 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003601 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003602 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003603 }
Richard Smith027bf112011-11-17 22:56:20 +00003604 }
3605
3606 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003607 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003608 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003609 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003610 } else if (!MemPtr.Path.empty()) {
3611 // Extend the LValue path with the member pointer's path.
3612 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3613 MemPtr.Path.size() + IncludeMember);
3614
3615 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003616 if (const PointerType *PT = LVType->getAs<PointerType>())
3617 LVType = PT->getPointeeType();
3618 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3619 assert(RD && "member pointer access on non-class-type expression");
3620 // The first class in the path is that of the lvalue.
3621 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3622 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003623 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003624 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003625 RD = Base;
3626 }
3627 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003628 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3629 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003630 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003631 }
3632
3633 // Add the member. Note that we cannot build bound member functions here.
3634 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003635 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003636 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003637 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003638 } else if (const IndirectFieldDecl *IFD =
3639 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003640 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003641 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003642 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003643 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003644 }
Richard Smith027bf112011-11-17 22:56:20 +00003645 }
3646
3647 return MemPtr.getDecl();
3648}
3649
Richard Smith84401042013-06-03 05:03:02 +00003650static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3651 const BinaryOperator *BO,
3652 LValue &LV,
3653 bool IncludeMember = true) {
3654 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3655
3656 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003657 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003658 MemberPtr MemPtr;
3659 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3660 }
Craig Topper36250ad2014-05-12 05:36:57 +00003661 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003662 }
3663
3664 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3665 BO->getRHS(), IncludeMember);
3666}
3667
Richard Smith027bf112011-11-17 22:56:20 +00003668/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3669/// the provided lvalue, which currently refers to the base object.
3670static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3671 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003672 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003673 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003674 return false;
3675
Richard Smitha8105bc2012-01-06 16:39:00 +00003676 QualType TargetQT = E->getType();
3677 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3678 TargetQT = PT->getPointeeType();
3679
3680 // Check this cast lands within the final derived-to-base subobject path.
3681 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003682 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003683 << D.MostDerivedType << TargetQT;
3684 return false;
3685 }
3686
Richard Smith027bf112011-11-17 22:56:20 +00003687 // Check the type of the final cast. We don't need to check the path,
3688 // since a cast can only be formed if the path is unique.
3689 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003690 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3691 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003692 if (NewEntriesSize == D.MostDerivedPathLength)
3693 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3694 else
Richard Smith027bf112011-11-17 22:56:20 +00003695 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003696 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003697 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003698 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003699 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003700 }
Richard Smith027bf112011-11-17 22:56:20 +00003701
3702 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003703 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003704}
3705
Mike Stump876387b2009-10-27 22:09:17 +00003706namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003707enum EvalStmtResult {
3708 /// Evaluation failed.
3709 ESR_Failed,
3710 /// Hit a 'return' statement.
3711 ESR_Returned,
3712 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003713 ESR_Succeeded,
3714 /// Hit a 'continue' statement.
3715 ESR_Continue,
3716 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003717 ESR_Break,
3718 /// Still scanning for 'case' or 'default' statement.
3719 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003720};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003721}
Richard Smith254a73d2011-10-28 22:34:42 +00003722
Richard Smith97fcf4b2016-08-14 23:15:52 +00003723static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3724 // We don't need to evaluate the initializer for a static local.
3725 if (!VD->hasLocalStorage())
3726 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003727
Richard Smith97fcf4b2016-08-14 23:15:52 +00003728 LValue Result;
3729 Result.set(VD, Info.CurrentCall->Index);
3730 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003731
Richard Smith97fcf4b2016-08-14 23:15:52 +00003732 const Expr *InitE = VD->getInit();
3733 if (!InitE) {
3734 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3735 << false << VD->getType();
3736 Val = APValue();
3737 return false;
3738 }
Richard Smith51f03172013-06-20 03:00:05 +00003739
Richard Smith97fcf4b2016-08-14 23:15:52 +00003740 if (InitE->isValueDependent())
3741 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003742
Richard Smith97fcf4b2016-08-14 23:15:52 +00003743 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3744 // Wipe out any partially-computed value, to allow tracking that this
3745 // evaluation failed.
3746 Val = APValue();
3747 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003748 }
3749
3750 return true;
3751}
3752
Richard Smith97fcf4b2016-08-14 23:15:52 +00003753static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3754 bool OK = true;
3755
3756 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3757 OK &= EvaluateVarDecl(Info, VD);
3758
3759 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3760 for (auto *BD : DD->bindings())
3761 if (auto *VD = BD->getHoldingVar())
3762 OK &= EvaluateDecl(Info, VD);
3763
3764 return OK;
3765}
3766
3767
Richard Smith4e18ca52013-05-06 05:56:11 +00003768/// Evaluate a condition (either a variable declaration or an expression).
3769static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3770 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003771 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003772 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3773 return false;
3774 return EvaluateAsBooleanCondition(Cond, Result, Info);
3775}
3776
Richard Smith89210072016-04-04 23:29:43 +00003777namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003778/// \brief A location where the result (returned value) of evaluating a
3779/// statement should be stored.
3780struct StmtResult {
3781 /// The APValue that should be filled in with the returned value.
3782 APValue &Value;
3783 /// The location containing the result, if any (used to support RVO).
3784 const LValue *Slot;
3785};
Richard Smith89210072016-04-04 23:29:43 +00003786}
Richard Smith52a980a2015-08-28 02:43:42 +00003787
3788static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003789 const Stmt *S,
3790 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003791
3792/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003793static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003794 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003795 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003796 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003797 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003798 case ESR_Break:
3799 return ESR_Succeeded;
3800 case ESR_Succeeded:
3801 case ESR_Continue:
3802 return ESR_Continue;
3803 case ESR_Failed:
3804 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003805 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003806 return ESR;
3807 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003808 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003809}
3810
Richard Smith496ddcf2013-05-12 17:32:42 +00003811/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003812static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003813 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003814 BlockScopeRAII Scope(Info);
3815
Richard Smith496ddcf2013-05-12 17:32:42 +00003816 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003817 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003818 {
3819 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003820 if (const Stmt *Init = SS->getInit()) {
3821 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3822 if (ESR != ESR_Succeeded)
3823 return ESR;
3824 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003825 if (SS->getConditionVariable() &&
3826 !EvaluateDecl(Info, SS->getConditionVariable()))
3827 return ESR_Failed;
3828 if (!EvaluateInteger(SS->getCond(), Value, Info))
3829 return ESR_Failed;
3830 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003831
3832 // Find the switch case corresponding to the value of the condition.
3833 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003834 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003835 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3836 SC = SC->getNextSwitchCase()) {
3837 if (isa<DefaultStmt>(SC)) {
3838 Found = SC;
3839 continue;
3840 }
3841
3842 const CaseStmt *CS = cast<CaseStmt>(SC);
3843 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3844 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3845 : LHS;
3846 if (LHS <= Value && Value <= RHS) {
3847 Found = SC;
3848 break;
3849 }
3850 }
3851
3852 if (!Found)
3853 return ESR_Succeeded;
3854
3855 // Search the switch body for the switch case and evaluate it from there.
3856 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3857 case ESR_Break:
3858 return ESR_Succeeded;
3859 case ESR_Succeeded:
3860 case ESR_Continue:
3861 case ESR_Failed:
3862 case ESR_Returned:
3863 return ESR;
3864 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003865 // This can only happen if the switch case is nested within a statement
3866 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003867 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003868 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003869 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003870 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003871}
3872
Richard Smith254a73d2011-10-28 22:34:42 +00003873// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003874static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003875 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003876 if (!Info.nextStep(S))
3877 return ESR_Failed;
3878
Richard Smith496ddcf2013-05-12 17:32:42 +00003879 // If we're hunting down a 'case' or 'default' label, recurse through
3880 // substatements until we hit the label.
3881 if (Case) {
3882 // FIXME: We don't start the lifetime of objects whose initialization we
3883 // jump over. However, such objects must be of class type with a trivial
3884 // default constructor that initialize all subobjects, so must be empty,
3885 // so this almost never matters.
3886 switch (S->getStmtClass()) {
3887 case Stmt::CompoundStmtClass:
3888 // FIXME: Precompute which substatement of a compound statement we
3889 // would jump to, and go straight there rather than performing a
3890 // linear scan each time.
3891 case Stmt::LabelStmtClass:
3892 case Stmt::AttributedStmtClass:
3893 case Stmt::DoStmtClass:
3894 break;
3895
3896 case Stmt::CaseStmtClass:
3897 case Stmt::DefaultStmtClass:
3898 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003899 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003900 break;
3901
3902 case Stmt::IfStmtClass: {
3903 // FIXME: Precompute which side of an 'if' we would jump to, and go
3904 // straight there rather than scanning both sides.
3905 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003906
3907 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3908 // preceded by our switch label.
3909 BlockScopeRAII Scope(Info);
3910
Richard Smith496ddcf2013-05-12 17:32:42 +00003911 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3912 if (ESR != ESR_CaseNotFound || !IS->getElse())
3913 return ESR;
3914 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3915 }
3916
3917 case Stmt::WhileStmtClass: {
3918 EvalStmtResult ESR =
3919 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3920 if (ESR != ESR_Continue)
3921 return ESR;
3922 break;
3923 }
3924
3925 case Stmt::ForStmtClass: {
3926 const ForStmt *FS = cast<ForStmt>(S);
3927 EvalStmtResult ESR =
3928 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3929 if (ESR != ESR_Continue)
3930 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003931 if (FS->getInc()) {
3932 FullExpressionRAII IncScope(Info);
3933 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3934 return ESR_Failed;
3935 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003936 break;
3937 }
3938
3939 case Stmt::DeclStmtClass:
3940 // FIXME: If the variable has initialization that can't be jumped over,
3941 // bail out of any immediately-surrounding compound-statement too.
3942 default:
3943 return ESR_CaseNotFound;
3944 }
3945 }
3946
Richard Smith254a73d2011-10-28 22:34:42 +00003947 switch (S->getStmtClass()) {
3948 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003949 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003950 // Don't bother evaluating beyond an expression-statement which couldn't
3951 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003952 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003953 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003954 return ESR_Failed;
3955 return ESR_Succeeded;
3956 }
3957
Faisal Valie690b7a2016-07-02 22:34:24 +00003958 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003959 return ESR_Failed;
3960
3961 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003962 return ESR_Succeeded;
3963
Richard Smithd9f663b2013-04-22 15:31:51 +00003964 case Stmt::DeclStmtClass: {
3965 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003966 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003967 // Each declaration initialization is its own full-expression.
3968 // FIXME: This isn't quite right; if we're performing aggregate
3969 // initialization, each braced subexpression is its own full-expression.
3970 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003971 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003972 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003973 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003974 return ESR_Succeeded;
3975 }
3976
Richard Smith357362d2011-12-13 06:39:58 +00003977 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003978 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003979 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003980 if (RetExpr &&
3981 !(Result.Slot
3982 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3983 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003984 return ESR_Failed;
3985 return ESR_Returned;
3986 }
Richard Smith254a73d2011-10-28 22:34:42 +00003987
3988 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003989 BlockScopeRAII Scope(Info);
3990
Richard Smith254a73d2011-10-28 22:34:42 +00003991 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003992 for (const auto *BI : CS->body()) {
3993 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003994 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003995 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003996 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003997 return ESR;
3998 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003999 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004000 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004001
4002 case Stmt::IfStmtClass: {
4003 const IfStmt *IS = cast<IfStmt>(S);
4004
4005 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004006 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004007 if (const Stmt *Init = IS->getInit()) {
4008 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4009 if (ESR != ESR_Succeeded)
4010 return ESR;
4011 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004012 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004013 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004014 return ESR_Failed;
4015
4016 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4017 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4018 if (ESR != ESR_Succeeded)
4019 return ESR;
4020 }
4021 return ESR_Succeeded;
4022 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004023
4024 case Stmt::WhileStmtClass: {
4025 const WhileStmt *WS = cast<WhileStmt>(S);
4026 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004027 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004028 bool Continue;
4029 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4030 Continue))
4031 return ESR_Failed;
4032 if (!Continue)
4033 break;
4034
4035 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4036 if (ESR != ESR_Continue)
4037 return ESR;
4038 }
4039 return ESR_Succeeded;
4040 }
4041
4042 case Stmt::DoStmtClass: {
4043 const DoStmt *DS = cast<DoStmt>(S);
4044 bool Continue;
4045 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004046 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004047 if (ESR != ESR_Continue)
4048 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004049 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004050
Richard Smith08d6a2c2013-07-24 07:11:57 +00004051 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004052 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4053 return ESR_Failed;
4054 } while (Continue);
4055 return ESR_Succeeded;
4056 }
4057
4058 case Stmt::ForStmtClass: {
4059 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004060 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004061 if (FS->getInit()) {
4062 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4063 if (ESR != ESR_Succeeded)
4064 return ESR;
4065 }
4066 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004067 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004068 bool Continue = true;
4069 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4070 FS->getCond(), Continue))
4071 return ESR_Failed;
4072 if (!Continue)
4073 break;
4074
4075 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4076 if (ESR != ESR_Continue)
4077 return ESR;
4078
Richard Smith08d6a2c2013-07-24 07:11:57 +00004079 if (FS->getInc()) {
4080 FullExpressionRAII IncScope(Info);
4081 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4082 return ESR_Failed;
4083 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004084 }
4085 return ESR_Succeeded;
4086 }
4087
Richard Smith896e0d72013-05-06 06:51:17 +00004088 case Stmt::CXXForRangeStmtClass: {
4089 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004090 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004091
4092 // Initialize the __range variable.
4093 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4094 if (ESR != ESR_Succeeded)
4095 return ESR;
4096
4097 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004098 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4099 if (ESR != ESR_Succeeded)
4100 return ESR;
4101 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004102 if (ESR != ESR_Succeeded)
4103 return ESR;
4104
4105 while (true) {
4106 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004107 {
4108 bool Continue = true;
4109 FullExpressionRAII CondExpr(Info);
4110 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4111 return ESR_Failed;
4112 if (!Continue)
4113 break;
4114 }
Richard Smith896e0d72013-05-06 06:51:17 +00004115
4116 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004117 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004118 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4119 if (ESR != ESR_Succeeded)
4120 return ESR;
4121
4122 // Loop body.
4123 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4124 if (ESR != ESR_Continue)
4125 return ESR;
4126
4127 // Increment: ++__begin
4128 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4129 return ESR_Failed;
4130 }
4131
4132 return ESR_Succeeded;
4133 }
4134
Richard Smith496ddcf2013-05-12 17:32:42 +00004135 case Stmt::SwitchStmtClass:
4136 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4137
Richard Smith4e18ca52013-05-06 05:56:11 +00004138 case Stmt::ContinueStmtClass:
4139 return ESR_Continue;
4140
4141 case Stmt::BreakStmtClass:
4142 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004143
4144 case Stmt::LabelStmtClass:
4145 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4146
4147 case Stmt::AttributedStmtClass:
4148 // As a general principle, C++11 attributes can be ignored without
4149 // any semantic impact.
4150 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4151 Case);
4152
4153 case Stmt::CaseStmtClass:
4154 case Stmt::DefaultStmtClass:
4155 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004156 }
4157}
4158
Richard Smithcc36f692011-12-22 02:22:31 +00004159/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4160/// default constructor. If so, we'll fold it whether or not it's marked as
4161/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4162/// so we need special handling.
4163static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004164 const CXXConstructorDecl *CD,
4165 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004166 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4167 return false;
4168
Richard Smith66e05fe2012-01-18 05:21:49 +00004169 // Value-initialization does not call a trivial default constructor, so such a
4170 // call is a core constant expression whether or not the constructor is
4171 // constexpr.
4172 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004173 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004174 // FIXME: If DiagDecl is an implicitly-declared special member function,
4175 // we should be much more explicit about why it's not constexpr.
4176 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4177 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4178 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004179 } else {
4180 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4181 }
4182 }
4183 return true;
4184}
4185
Richard Smith357362d2011-12-13 06:39:58 +00004186/// CheckConstexprFunction - Check that a function can be called in a constant
4187/// expression.
4188static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4189 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004190 const FunctionDecl *Definition,
4191 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004192 // Potential constant expressions can contain calls to declared, but not yet
4193 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004194 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004195 Declaration->isConstexpr())
4196 return false;
4197
Richard Smith0838f3a2013-05-14 05:18:44 +00004198 // Bail out with no diagnostic if the function declaration itself is invalid.
4199 // We will have produced a relevant diagnostic while parsing it.
4200 if (Declaration->isInvalidDecl())
4201 return false;
4202
Richard Smith357362d2011-12-13 06:39:58 +00004203 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004204 if (Definition && Definition->isConstexpr() &&
4205 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004206 return true;
4207
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004208 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004209 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004210
Richard Smith5179eb72016-06-28 19:03:57 +00004211 // If this function is not constexpr because it is an inherited
4212 // non-constexpr constructor, diagnose that directly.
4213 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4214 if (CD && CD->isInheritingConstructor()) {
4215 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004216 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004217 DiagDecl = CD = Inherited;
4218 }
4219
4220 // FIXME: If DiagDecl is an implicitly-declared special member function
4221 // or an inheriting constructor, we should be much more explicit about why
4222 // it's not constexpr.
4223 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004224 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004225 << CD->getInheritedConstructor().getConstructor()->getParent();
4226 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004227 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004228 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004229 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4230 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004231 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004232 }
4233 return false;
4234}
4235
Richard Smithbe6dd812014-11-19 21:27:17 +00004236/// Determine if a class has any fields that might need to be copied by a
4237/// trivial copy or move operation.
4238static bool hasFields(const CXXRecordDecl *RD) {
4239 if (!RD || RD->isEmpty())
4240 return false;
4241 for (auto *FD : RD->fields()) {
4242 if (FD->isUnnamedBitfield())
4243 continue;
4244 return true;
4245 }
4246 for (auto &Base : RD->bases())
4247 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4248 return true;
4249 return false;
4250}
4251
Richard Smithd62306a2011-11-10 06:34:14 +00004252namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004253typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004254}
4255
4256/// EvaluateArgs - Evaluate the arguments to a function call.
4257static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4258 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004259 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004260 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004261 I != E; ++I) {
4262 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4263 // If we're checking for a potential constant expression, evaluate all
4264 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004265 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004266 return false;
4267 Success = false;
4268 }
4269 }
4270 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004271}
4272
Richard Smith254a73d2011-10-28 22:34:42 +00004273/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004274static bool HandleFunctionCall(SourceLocation CallLoc,
4275 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004276 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004277 EvalInfo &Info, APValue &Result,
4278 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004279 ArgVector ArgValues(Args.size());
4280 if (!EvaluateArgs(Args, ArgValues, Info))
4281 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004282
Richard Smith253c2a32012-01-27 01:14:48 +00004283 if (!Info.CheckCallLimit(CallLoc))
4284 return false;
4285
4286 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004287
4288 // For a trivial copy or move assignment, perform an APValue copy. This is
4289 // essential for unions, where the operations performed by the assignment
4290 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004291 //
4292 // Skip this for non-union classes with no fields; in that case, the defaulted
4293 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004294 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004295 if (MD && MD->isDefaulted() &&
4296 (MD->getParent()->isUnion() ||
4297 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004298 assert(This &&
4299 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4300 LValue RHS;
4301 RHS.setFrom(Info.Ctx, ArgValues[0]);
4302 APValue RHSValue;
4303 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4304 RHS, RHSValue))
4305 return false;
4306 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4307 RHSValue))
4308 return false;
4309 This->moveInto(Result);
4310 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004311 } else if (MD && isLambdaCallOperator(MD)) {
4312 // We're in a lambda; determine the lambda capture field maps.
4313 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4314 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004315 }
4316
Richard Smith52a980a2015-08-28 02:43:42 +00004317 StmtResult Ret = {Result, ResultSlot};
4318 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004319 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004320 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004321 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004322 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004323 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004324 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004325}
4326
Richard Smithd62306a2011-11-10 06:34:14 +00004327/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004328static bool HandleConstructorCall(const Expr *E, const LValue &This,
4329 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004330 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004331 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004332 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004333 if (!Info.CheckCallLimit(CallLoc))
4334 return false;
4335
Richard Smith3607ffe2012-02-13 03:54:03 +00004336 const CXXRecordDecl *RD = Definition->getParent();
4337 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004338 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004339 return false;
4340 }
4341
Erik Pilkington42925492017-10-04 00:18:55 +00004342 EvalInfo::EvaluatingConstructorRAII EvalObj(
4343 Info, {This.getLValueBase(), This.CallIndex});
Richard Smith5179eb72016-06-28 19:03:57 +00004344 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004345
Richard Smith52a980a2015-08-28 02:43:42 +00004346 // FIXME: Creating an APValue just to hold a nonexistent return value is
4347 // wasteful.
4348 APValue RetVal;
4349 StmtResult Ret = {RetVal, nullptr};
4350
Richard Smith5179eb72016-06-28 19:03:57 +00004351 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004352 if (Definition->isDelegatingConstructor()) {
4353 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004354 {
4355 FullExpressionRAII InitScope(Info);
4356 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4357 return false;
4358 }
Richard Smith52a980a2015-08-28 02:43:42 +00004359 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004360 }
4361
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004362 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004363 // essential for unions (or classes with anonymous union members), where the
4364 // operations performed by the constructor cannot be represented by
4365 // ctor-initializers.
4366 //
4367 // Skip this for empty non-union classes; we should not perform an
4368 // lvalue-to-rvalue conversion on them because their copy constructor does not
4369 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004370 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004371 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004372 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004373 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004374 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004375 return handleLValueToRValueConversion(
4376 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4377 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004378 }
4379
4380 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004381 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004382 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004383 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004384
John McCalld7bca762012-05-01 00:38:49 +00004385 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004386 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4387
Richard Smith08d6a2c2013-07-24 07:11:57 +00004388 // A scope for temporaries lifetime-extended by reference members.
4389 BlockScopeRAII LifetimeExtendedScope(Info);
4390
Richard Smith253c2a32012-01-27 01:14:48 +00004391 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004392 unsigned BasesSeen = 0;
4393#ifndef NDEBUG
4394 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4395#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004396 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004397 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004398 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004399 APValue *Value = &Result;
4400
4401 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004402 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004403 if (I->isBaseInitializer()) {
4404 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004405#ifndef NDEBUG
4406 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004407 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004408 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4409 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4410 "base class initializers not in expected order");
4411 ++BaseIt;
4412#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004413 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004414 BaseType->getAsCXXRecordDecl(), &Layout))
4415 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004416 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004417 } else if ((FD = I->getMember())) {
4418 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004419 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004420 if (RD->isUnion()) {
4421 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004422 Value = &Result.getUnionValue();
4423 } else {
4424 Value = &Result.getStructField(FD->getFieldIndex());
4425 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004426 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004427 // Walk the indirect field decl's chain to find the object to initialize,
4428 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004429 auto IndirectFieldChain = IFD->chain();
4430 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004431 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004432 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4433 // Switch the union field if it differs. This happens if we had
4434 // preceding zero-initialization, and we're now initializing a union
4435 // subobject other than the first.
4436 // FIXME: In this case, the values of the other subobjects are
4437 // specified, since zero-initialization sets all padding bits to zero.
4438 if (Value->isUninit() ||
4439 (Value->isUnion() && Value->getUnionField() != FD)) {
4440 if (CD->isUnion())
4441 *Value = APValue(FD);
4442 else
4443 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004444 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004445 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004446 // Store Subobject as its parent before updating it for the last element
4447 // in the chain.
4448 if (C == IndirectFieldChain.back())
4449 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004450 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004451 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004452 if (CD->isUnion())
4453 Value = &Value->getUnionValue();
4454 else
4455 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004456 }
Richard Smithd62306a2011-11-10 06:34:14 +00004457 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004458 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004459 }
Richard Smith253c2a32012-01-27 01:14:48 +00004460
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004461 // Need to override This for implicit field initializers as in this case
4462 // This refers to innermost anonymous struct/union containing initializer,
4463 // not to currently constructed class.
4464 const Expr *Init = I->getInit();
4465 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4466 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004467 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004468 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4469 (FD && FD->isBitField() &&
4470 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004471 // If we're checking for a potential constant expression, evaluate all
4472 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004473 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004474 return false;
4475 Success = false;
4476 }
Richard Smithd62306a2011-11-10 06:34:14 +00004477 }
4478
Richard Smithd9f663b2013-04-22 15:31:51 +00004479 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004480 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004481}
4482
Richard Smith5179eb72016-06-28 19:03:57 +00004483static bool HandleConstructorCall(const Expr *E, const LValue &This,
4484 ArrayRef<const Expr*> Args,
4485 const CXXConstructorDecl *Definition,
4486 EvalInfo &Info, APValue &Result) {
4487 ArgVector ArgValues(Args.size());
4488 if (!EvaluateArgs(Args, ArgValues, Info))
4489 return false;
4490
4491 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4492 Info, Result);
4493}
4494
Eli Friedman9a156e52008-11-12 09:44:48 +00004495//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004496// Generic Evaluation
4497//===----------------------------------------------------------------------===//
4498namespace {
4499
Aaron Ballman68af21c2014-01-03 19:26:43 +00004500template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004501class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004502 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004503private:
Richard Smith52a980a2015-08-28 02:43:42 +00004504 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004505 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004506 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004507 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004508 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004509 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004510 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004511
Richard Smith17100ba2012-02-16 02:46:34 +00004512 // Check whether a conditional operator with a non-constant condition is a
4513 // potential constant expression. If neither arm is a potential constant
4514 // expression, then the conditional operator is not either.
4515 template<typename ConditionalOperator>
4516 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004517 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004518
4519 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004520 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004521 {
Richard Smith17100ba2012-02-16 02:46:34 +00004522 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004523 StmtVisitorTy::Visit(E->getFalseExpr());
4524 if (Diag.empty())
4525 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004526 }
Richard Smith17100ba2012-02-16 02:46:34 +00004527
George Burgess IV8c892b52016-05-25 22:31:54 +00004528 {
4529 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004530 Diag.clear();
4531 StmtVisitorTy::Visit(E->getTrueExpr());
4532 if (Diag.empty())
4533 return;
4534 }
4535
4536 Error(E, diag::note_constexpr_conditional_never_const);
4537 }
4538
4539
4540 template<typename ConditionalOperator>
4541 bool HandleConditionalOperator(const ConditionalOperator *E) {
4542 bool BoolResult;
4543 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004544 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004545 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004546 return false;
4547 }
4548 if (Info.noteFailure()) {
4549 StmtVisitorTy::Visit(E->getTrueExpr());
4550 StmtVisitorTy::Visit(E->getFalseExpr());
4551 }
Richard Smith17100ba2012-02-16 02:46:34 +00004552 return false;
4553 }
4554
4555 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4556 return StmtVisitorTy::Visit(EvalExpr);
4557 }
4558
Peter Collingbournee9200682011-05-13 03:29:01 +00004559protected:
4560 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004561 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004562 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4563
Richard Smith92b1ce02011-12-12 09:28:41 +00004564 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004565 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004566 }
4567
Aaron Ballman68af21c2014-01-03 19:26:43 +00004568 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004569
4570public:
4571 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4572
4573 EvalInfo &getEvalInfo() { return Info; }
4574
Richard Smithf57d8cb2011-12-09 22:58:01 +00004575 /// Report an evaluation error. This should only be called when an error is
4576 /// first discovered. When propagating an error, just return false.
4577 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004578 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004579 return false;
4580 }
4581 bool Error(const Expr *E) {
4582 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4583 }
4584
Aaron Ballman68af21c2014-01-03 19:26:43 +00004585 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004586 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004587 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004588 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004589 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004590 }
4591
Aaron Ballman68af21c2014-01-03 19:26:43 +00004592 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004593 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004594 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004595 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004596 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004597 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004598 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004599 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004600 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004601 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004602 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004603 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004604 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004605 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004606 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004607 // The initializer may not have been parsed yet, or might be erroneous.
4608 if (!E->getExpr())
4609 return Error(E);
4610 return StmtVisitorTy::Visit(E->getExpr());
4611 }
Richard Smith5894a912011-12-19 22:12:41 +00004612 // We cannot create any objects for which cleanups are required, so there is
4613 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004614 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004615 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004616
Aaron Ballman68af21c2014-01-03 19:26:43 +00004617 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004618 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4619 return static_cast<Derived*>(this)->VisitCastExpr(E);
4620 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004621 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004622 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4623 return static_cast<Derived*>(this)->VisitCastExpr(E);
4624 }
4625
Aaron Ballman68af21c2014-01-03 19:26:43 +00004626 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004627 switch (E->getOpcode()) {
4628 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004629 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004630
4631 case BO_Comma:
4632 VisitIgnoredValue(E->getLHS());
4633 return StmtVisitorTy::Visit(E->getRHS());
4634
4635 case BO_PtrMemD:
4636 case BO_PtrMemI: {
4637 LValue Obj;
4638 if (!HandleMemberPointerAccess(Info, E, Obj))
4639 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004640 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004641 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004642 return false;
4643 return DerivedSuccess(Result, E);
4644 }
4645 }
4646 }
4647
Aaron Ballman68af21c2014-01-03 19:26:43 +00004648 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004649 // Evaluate and cache the common expression. We treat it as a temporary,
4650 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004651 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004652 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004653 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004654
Richard Smith17100ba2012-02-16 02:46:34 +00004655 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004656 }
4657
Aaron Ballman68af21c2014-01-03 19:26:43 +00004658 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004659 bool IsBcpCall = false;
4660 // If the condition (ignoring parens) is a __builtin_constant_p call,
4661 // the result is a constant expression if it can be folded without
4662 // side-effects. This is an important GNU extension. See GCC PR38377
4663 // for discussion.
4664 if (const CallExpr *CallCE =
4665 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004666 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004667 IsBcpCall = true;
4668
4669 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4670 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004671 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004672 return false;
4673
Richard Smith6d4c6582013-11-05 22:18:15 +00004674 FoldConstant Fold(Info, IsBcpCall);
4675 if (!HandleConditionalOperator(E)) {
4676 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004677 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004678 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004679
4680 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004681 }
4682
Aaron Ballman68af21c2014-01-03 19:26:43 +00004683 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004684 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4685 return DerivedSuccess(*Value, E);
4686
4687 const Expr *Source = E->getSourceExpr();
4688 if (!Source)
4689 return Error(E);
4690 if (Source == E) { // sanity checking.
4691 assert(0 && "OpaqueValueExpr recursively refers to itself");
4692 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004693 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004694 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004695 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004696
Aaron Ballman68af21c2014-01-03 19:26:43 +00004697 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004698 APValue Result;
4699 if (!handleCallExpr(E, Result, nullptr))
4700 return false;
4701 return DerivedSuccess(Result, E);
4702 }
4703
4704 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004705 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004706 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004707 QualType CalleeType = Callee->getType();
4708
Craig Topper36250ad2014-05-12 05:36:57 +00004709 const FunctionDecl *FD = nullptr;
4710 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004711 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004712 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004713
Richard Smithe97cbd72011-11-11 04:05:33 +00004714 // Extract function decl and 'this' pointer from the callee.
4715 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004716 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004717 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4718 // Explicit bound member calls, such as x.f() or p->g();
4719 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004720 return false;
4721 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004722 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004723 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004724 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4725 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004726 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4727 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004728 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004729 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004730 return Error(Callee);
4731
4732 FD = dyn_cast<FunctionDecl>(Member);
4733 if (!FD)
4734 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004735 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004736 LValue Call;
4737 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004738 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004739
Richard Smitha8105bc2012-01-06 16:39:00 +00004740 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004741 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004742 FD = dyn_cast_or_null<FunctionDecl>(
4743 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004744 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004745 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004746 // Don't call function pointers which have been cast to some other type.
4747 // Per DR (no number yet), the caller and callee can differ in noexcept.
4748 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4749 CalleeType->getPointeeType(), FD->getType())) {
4750 return Error(E);
4751 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004752
4753 // Overloaded operator calls to member functions are represented as normal
4754 // calls with '*this' as the first argument.
4755 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4756 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004757 // FIXME: When selecting an implicit conversion for an overloaded
4758 // operator delete, we sometimes try to evaluate calls to conversion
4759 // operators without a 'this' parameter!
4760 if (Args.empty())
4761 return Error(E);
4762
Nick Lewycky13073a62017-06-12 21:15:44 +00004763 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004764 return false;
4765 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004766 Args = Args.slice(1);
Daniel Jasperffdee092017-05-02 19:21:42 +00004767 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004768 // Map the static invoker for the lambda back to the call operator.
4769 // Conveniently, we don't have to slice out the 'this' argument (as is
4770 // being done for the non-static case), since a static member function
4771 // doesn't have an implicit argument passed in.
4772 const CXXRecordDecl *ClosureClass = MD->getParent();
4773 assert(
4774 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4775 "Number of captures must be zero for conversion to function-ptr");
4776
4777 const CXXMethodDecl *LambdaCallOp =
4778 ClosureClass->getLambdaCallOperator();
4779
4780 // Set 'FD', the function that will be called below, to the call
4781 // operator. If the closure object represents a generic lambda, find
4782 // the corresponding specialization of the call operator.
4783
4784 if (ClosureClass->isGenericLambda()) {
4785 assert(MD->isFunctionTemplateSpecialization() &&
4786 "A generic lambda's static-invoker function must be a "
4787 "template specialization");
4788 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4789 FunctionTemplateDecl *CallOpTemplate =
4790 LambdaCallOp->getDescribedFunctionTemplate();
4791 void *InsertPos = nullptr;
4792 FunctionDecl *CorrespondingCallOpSpecialization =
4793 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4794 assert(CorrespondingCallOpSpecialization &&
4795 "We must always have a function call operator specialization "
4796 "that corresponds to our static invoker specialization");
4797 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4798 } else
4799 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004800 }
4801
Daniel Jasperffdee092017-05-02 19:21:42 +00004802
Richard Smithe97cbd72011-11-11 04:05:33 +00004803 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004804 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004805
Richard Smith47b34932012-02-01 02:39:43 +00004806 if (This && !This->checkSubobject(Info, E, CSK_This))
4807 return false;
4808
Richard Smith3607ffe2012-02-13 03:54:03 +00004809 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4810 // calls to such functions in constant expressions.
4811 if (This && !HasQualifier &&
4812 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4813 return Error(E, diag::note_constexpr_virtual_call);
4814
Craig Topper36250ad2014-05-12 05:36:57 +00004815 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004816 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004817
Nick Lewycky13073a62017-06-12 21:15:44 +00004818 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4819 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004820 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004821 return false;
4822
Richard Smith52a980a2015-08-28 02:43:42 +00004823 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004824 }
4825
Aaron Ballman68af21c2014-01-03 19:26:43 +00004826 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004827 return StmtVisitorTy::Visit(E->getInitializer());
4828 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004829 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004830 if (E->getNumInits() == 0)
4831 return DerivedZeroInitialization(E);
4832 if (E->getNumInits() == 1)
4833 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004834 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004835 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004836 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004837 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004838 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004839 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004840 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004841 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004842 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004843 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004844 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004845
Richard Smithd62306a2011-11-10 06:34:14 +00004846 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004847 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004848 assert(!E->isArrow() && "missing call to bound member function?");
4849
Richard Smith2e312c82012-03-03 22:46:17 +00004850 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004851 if (!Evaluate(Val, Info, E->getBase()))
4852 return false;
4853
4854 QualType BaseTy = E->getBase()->getType();
4855
4856 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004857 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004858 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004859 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004860 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4861
Richard Smith9defb7d2018-02-21 03:38:30 +00004862 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00004863 SubobjectDesignator Designator(BaseTy);
4864 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004865
Richard Smith3229b742013-05-05 21:17:10 +00004866 APValue Result;
4867 return extractSubobject(Info, E, Obj, Designator, Result) &&
4868 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004869 }
4870
Aaron Ballman68af21c2014-01-03 19:26:43 +00004871 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004872 switch (E->getCastKind()) {
4873 default:
4874 break;
4875
Richard Smitha23ab512013-05-23 00:30:41 +00004876 case CK_AtomicToNonAtomic: {
4877 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004878 // This does not need to be done in place even for class/array types:
4879 // atomic-to-non-atomic conversion implies copying the object
4880 // representation.
4881 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004882 return false;
4883 return DerivedSuccess(AtomicVal, E);
4884 }
4885
Richard Smith11562c52011-10-28 17:51:58 +00004886 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004887 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004888 return StmtVisitorTy::Visit(E->getSubExpr());
4889
4890 case CK_LValueToRValue: {
4891 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004892 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4893 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004894 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004895 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004896 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004897 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004898 return false;
4899 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004900 }
4901 }
4902
Richard Smithf57d8cb2011-12-09 22:58:01 +00004903 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004904 }
4905
Aaron Ballman68af21c2014-01-03 19:26:43 +00004906 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004907 return VisitUnaryPostIncDec(UO);
4908 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004909 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004910 return VisitUnaryPostIncDec(UO);
4911 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004912 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004913 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004914 return Error(UO);
4915
4916 LValue LVal;
4917 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4918 return false;
4919 APValue RVal;
4920 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4921 UO->isIncrementOp(), &RVal))
4922 return false;
4923 return DerivedSuccess(RVal, UO);
4924 }
4925
Aaron Ballman68af21c2014-01-03 19:26:43 +00004926 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004927 // We will have checked the full-expressions inside the statement expression
4928 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004929 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004930 return Error(E);
4931
Richard Smith08d6a2c2013-07-24 07:11:57 +00004932 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004933 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004934 if (CS->body_empty())
4935 return true;
4936
Richard Smith51f03172013-06-20 03:00:05 +00004937 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4938 BE = CS->body_end();
4939 /**/; ++BI) {
4940 if (BI + 1 == BE) {
4941 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4942 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004943 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004944 diag::note_constexpr_stmt_expr_unsupported);
4945 return false;
4946 }
4947 return this->Visit(FinalExpr);
4948 }
4949
4950 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004951 StmtResult Result = { ReturnValue, nullptr };
4952 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004953 if (ESR != ESR_Succeeded) {
4954 // FIXME: If the statement-expression terminated due to 'return',
4955 // 'break', or 'continue', it would be nice to propagate that to
4956 // the outer statement evaluation rather than bailing out.
4957 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004958 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004959 diag::note_constexpr_stmt_expr_unsupported);
4960 return false;
4961 }
4962 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004963
4964 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004965 }
4966
Richard Smith4a678122011-10-24 18:44:57 +00004967 /// Visit a value which is evaluated, but whose value is ignored.
4968 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004969 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004970 }
David Majnemere9807b22016-02-26 04:23:19 +00004971
4972 /// Potentially visit a MemberExpr's base expression.
4973 void VisitIgnoredBaseExpression(const Expr *E) {
4974 // While MSVC doesn't evaluate the base expression, it does diagnose the
4975 // presence of side-effecting behavior.
4976 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4977 return;
4978 VisitIgnoredValue(E);
4979 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004980};
4981
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004982}
Peter Collingbournee9200682011-05-13 03:29:01 +00004983
4984//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004985// Common base class for lvalue and temporary evaluation.
4986//===----------------------------------------------------------------------===//
4987namespace {
4988template<class Derived>
4989class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004990 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004991protected:
4992 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004993 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004994 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004995 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004996
4997 bool Success(APValue::LValueBase B) {
4998 Result.set(B);
4999 return true;
5000 }
5001
George Burgess IVf9013bf2017-02-10 22:52:29 +00005002 bool evaluatePointer(const Expr *E, LValue &Result) {
5003 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5004 }
5005
Richard Smith027bf112011-11-17 22:56:20 +00005006public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005007 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5008 : ExprEvaluatorBaseTy(Info), Result(Result),
5009 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005010
Richard Smith2e312c82012-03-03 22:46:17 +00005011 bool Success(const APValue &V, const Expr *E) {
5012 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005013 return true;
5014 }
Richard Smith027bf112011-11-17 22:56:20 +00005015
Richard Smith027bf112011-11-17 22:56:20 +00005016 bool VisitMemberExpr(const MemberExpr *E) {
5017 // Handle non-static data members.
5018 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005019 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005020 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005021 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005022 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005023 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005024 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005025 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005026 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005027 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005028 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005029 BaseTy = E->getBase()->getType();
5030 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005031 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005032 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005033 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005034 Result.setInvalid(E);
5035 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005036 }
Richard Smith027bf112011-11-17 22:56:20 +00005037
Richard Smith1b78b3d2012-01-25 22:15:11 +00005038 const ValueDecl *MD = E->getMemberDecl();
5039 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5040 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5041 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5042 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005043 if (!HandleLValueMember(this->Info, E, Result, FD))
5044 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005045 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005046 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5047 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005048 } else
5049 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005050
Richard Smith1b78b3d2012-01-25 22:15:11 +00005051 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005052 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005053 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005054 RefValue))
5055 return false;
5056 return Success(RefValue, E);
5057 }
5058 return true;
5059 }
5060
5061 bool VisitBinaryOperator(const BinaryOperator *E) {
5062 switch (E->getOpcode()) {
5063 default:
5064 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5065
5066 case BO_PtrMemD:
5067 case BO_PtrMemI:
5068 return HandleMemberPointerAccess(this->Info, E, Result);
5069 }
5070 }
5071
5072 bool VisitCastExpr(const CastExpr *E) {
5073 switch (E->getCastKind()) {
5074 default:
5075 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5076
5077 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005078 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005079 if (!this->Visit(E->getSubExpr()))
5080 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005081
5082 // Now figure out the necessary offset to add to the base LV to get from
5083 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005084 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5085 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005086 }
5087 }
5088};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005089}
Richard Smith027bf112011-11-17 22:56:20 +00005090
5091//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005092// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005093//
5094// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5095// function designators (in C), decl references to void objects (in C), and
5096// temporaries (if building with -Wno-address-of-temporary).
5097//
5098// LValue evaluation produces values comprising a base expression of one of the
5099// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005100// - Declarations
5101// * VarDecl
5102// * FunctionDecl
5103// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005104// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005105// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005106// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005107// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005108// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005109// * ObjCEncodeExpr
5110// * AddrLabelExpr
5111// * BlockExpr
5112// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005113// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005114// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005115// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005116// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5117// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005118// * A MaterializeTemporaryExpr that has static storage duration, with no
5119// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005120// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005121//===----------------------------------------------------------------------===//
5122namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005123class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005124 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005125public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005126 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5127 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005128
Richard Smith11562c52011-10-28 17:51:58 +00005129 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005130 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005131
Peter Collingbournee9200682011-05-13 03:29:01 +00005132 bool VisitDeclRefExpr(const DeclRefExpr *E);
5133 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005134 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005135 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5136 bool VisitMemberExpr(const MemberExpr *E);
5137 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5138 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005139 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005140 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005141 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5142 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005143 bool VisitUnaryReal(const UnaryOperator *E);
5144 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005145 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5146 return VisitUnaryPreIncDec(UO);
5147 }
5148 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5149 return VisitUnaryPreIncDec(UO);
5150 }
Richard Smith3229b742013-05-05 21:17:10 +00005151 bool VisitBinAssign(const BinaryOperator *BO);
5152 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005153
Peter Collingbournee9200682011-05-13 03:29:01 +00005154 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005155 switch (E->getCastKind()) {
5156 default:
Richard Smith027bf112011-11-17 22:56:20 +00005157 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005158
Eli Friedmance3e02a2011-10-11 00:13:24 +00005159 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005160 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005161 if (!Visit(E->getSubExpr()))
5162 return false;
5163 Result.Designator.setInvalid();
5164 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005165
Richard Smith027bf112011-11-17 22:56:20 +00005166 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005167 if (!Visit(E->getSubExpr()))
5168 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005169 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005170 }
5171 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005172};
5173} // end anonymous namespace
5174
Richard Smith11562c52011-10-28 17:51:58 +00005175/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005176/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005177/// * function designators in C, and
5178/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005179/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005180static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5181 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005182 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005183 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005184 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005185}
5186
Peter Collingbournee9200682011-05-13 03:29:01 +00005187bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005188 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005189 return Success(FD);
5190 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005191 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005192 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005193 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005194 return Error(E);
5195}
Richard Smith733237d2011-10-24 23:14:33 +00005196
Faisal Vali0528a312016-11-13 06:09:16 +00005197
Richard Smith11562c52011-10-28 17:51:58 +00005198bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005199
5200 // If we are within a lambda's call operator, check whether the 'VD' referred
5201 // to within 'E' actually represents a lambda-capture that maps to a
5202 // data-member/field within the closure object, and if so, evaluate to the
5203 // field or what the field refers to.
5204 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5205 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5206 if (Info.checkingPotentialConstantExpression())
5207 return false;
5208 // Start with 'Result' referring to the complete closure object...
5209 Result = *Info.CurrentCall->This;
5210 // ... then update it to refer to the field of the closure object
5211 // that represents the capture.
5212 if (!HandleLValueMember(Info, E, Result, FD))
5213 return false;
5214 // And if the field is of reference type, update 'Result' to refer to what
5215 // the field refers to.
5216 if (FD->getType()->isReferenceType()) {
5217 APValue RVal;
5218 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5219 RVal))
5220 return false;
5221 Result.setFrom(Info.Ctx, RVal);
5222 }
5223 return true;
5224 }
5225 }
Craig Topper36250ad2014-05-12 05:36:57 +00005226 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005227 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5228 // Only if a local variable was declared in the function currently being
5229 // evaluated, do we expect to be able to find its value in the current
5230 // frame. (Otherwise it was likely declared in an enclosing context and
5231 // could either have a valid evaluatable value (for e.g. a constexpr
5232 // variable) or be ill-formed (and trigger an appropriate evaluation
5233 // diagnostic)).
5234 if (Info.CurrentCall->Callee &&
5235 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5236 Frame = Info.CurrentCall;
5237 }
5238 }
Richard Smith3229b742013-05-05 21:17:10 +00005239
Richard Smithfec09922011-11-01 16:57:24 +00005240 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005241 if (Frame) {
5242 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005243 return true;
5244 }
Richard Smithce40ad62011-11-12 22:28:03 +00005245 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005246 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005247
Richard Smith3229b742013-05-05 21:17:10 +00005248 APValue *V;
5249 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005250 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005251 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005252 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005253 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005254 return false;
5255 }
Richard Smith3229b742013-05-05 21:17:10 +00005256 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005257}
5258
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005259bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5260 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005261 // Walk through the expression to find the materialized temporary itself.
5262 SmallVector<const Expr *, 2> CommaLHSs;
5263 SmallVector<SubobjectAdjustment, 2> Adjustments;
5264 const Expr *Inner = E->GetTemporaryExpr()->
5265 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005266
Richard Smith84401042013-06-03 05:03:02 +00005267 // If we passed any comma operators, evaluate their LHSs.
5268 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5269 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5270 return false;
5271
Richard Smithe6c01442013-06-05 00:46:14 +00005272 // A materialized temporary with static storage duration can appear within the
5273 // result of a constant expression evaluation, so we need to preserve its
5274 // value for use outside this evaluation.
5275 APValue *Value;
5276 if (E->getStorageDuration() == SD_Static) {
5277 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005278 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005279 Result.set(E);
5280 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005281 Value = &Info.CurrentCall->
5282 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005283 Result.set(E, Info.CurrentCall->Index);
5284 }
5285
Richard Smithea4ad5d2013-06-06 08:19:16 +00005286 QualType Type = Inner->getType();
5287
Richard Smith84401042013-06-03 05:03:02 +00005288 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005289 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5290 (E->getStorageDuration() == SD_Static &&
5291 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5292 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005293 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005294 }
Richard Smith84401042013-06-03 05:03:02 +00005295
5296 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005297 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5298 --I;
5299 switch (Adjustments[I].Kind) {
5300 case SubobjectAdjustment::DerivedToBaseAdjustment:
5301 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5302 Type, Result))
5303 return false;
5304 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5305 break;
5306
5307 case SubobjectAdjustment::FieldAdjustment:
5308 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5309 return false;
5310 Type = Adjustments[I].Field->getType();
5311 break;
5312
5313 case SubobjectAdjustment::MemberPointerAdjustment:
5314 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5315 Adjustments[I].Ptr.RHS))
5316 return false;
5317 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5318 break;
5319 }
5320 }
5321
5322 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005323}
5324
Peter Collingbournee9200682011-05-13 03:29:01 +00005325bool
5326LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005327 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5328 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005329 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5330 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005331 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005332}
5333
Richard Smith6e525142011-12-27 12:18:28 +00005334bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005335 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005336 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005337
Faisal Valie690b7a2016-07-02 22:34:24 +00005338 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005339 << E->getExprOperand()->getType()
5340 << E->getExprOperand()->getSourceRange();
5341 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005342}
5343
Francois Pichet0066db92012-04-16 04:08:35 +00005344bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5345 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005346}
Francois Pichet0066db92012-04-16 04:08:35 +00005347
Peter Collingbournee9200682011-05-13 03:29:01 +00005348bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005349 // Handle static data members.
5350 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005351 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005352 return VisitVarDecl(E, VD);
5353 }
5354
Richard Smith254a73d2011-10-28 22:34:42 +00005355 // Handle static member functions.
5356 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5357 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005358 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005359 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005360 }
5361 }
5362
Richard Smithd62306a2011-11-10 06:34:14 +00005363 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005364 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005365}
5366
Peter Collingbournee9200682011-05-13 03:29:01 +00005367bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005368 // FIXME: Deal with vectors as array subscript bases.
5369 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005370 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005371
Nick Lewyckyad888682017-04-27 07:27:36 +00005372 bool Success = true;
5373 if (!evaluatePointer(E->getBase(), Result)) {
5374 if (!Info.noteFailure())
5375 return false;
5376 Success = false;
5377 }
Mike Stump11289f42009-09-09 15:08:12 +00005378
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005379 APSInt Index;
5380 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005381 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005382
Nick Lewyckyad888682017-04-27 07:27:36 +00005383 return Success &&
5384 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005385}
Eli Friedman9a156e52008-11-12 09:44:48 +00005386
Peter Collingbournee9200682011-05-13 03:29:01 +00005387bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005388 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005389}
5390
Richard Smith66c96992012-02-18 22:04:06 +00005391bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5392 if (!Visit(E->getSubExpr()))
5393 return false;
5394 // __real is a no-op on scalar lvalues.
5395 if (E->getSubExpr()->getType()->isAnyComplexType())
5396 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5397 return true;
5398}
5399
5400bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5401 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5402 "lvalue __imag__ on scalar?");
5403 if (!Visit(E->getSubExpr()))
5404 return false;
5405 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5406 return true;
5407}
5408
Richard Smith243ef902013-05-05 23:31:59 +00005409bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005410 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005411 return Error(UO);
5412
5413 if (!this->Visit(UO->getSubExpr()))
5414 return false;
5415
Richard Smith243ef902013-05-05 23:31:59 +00005416 return handleIncDec(
5417 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005418 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005419}
5420
5421bool LValueExprEvaluator::VisitCompoundAssignOperator(
5422 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005423 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005424 return Error(CAO);
5425
Richard Smith3229b742013-05-05 21:17:10 +00005426 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005427
5428 // The overall lvalue result is the result of evaluating the LHS.
5429 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005430 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005431 Evaluate(RHS, this->Info, CAO->getRHS());
5432 return false;
5433 }
5434
Richard Smith3229b742013-05-05 21:17:10 +00005435 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5436 return false;
5437
Richard Smith43e77732013-05-07 04:50:00 +00005438 return handleCompoundAssignment(
5439 this->Info, CAO,
5440 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5441 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005442}
5443
5444bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005445 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005446 return Error(E);
5447
Richard Smith3229b742013-05-05 21:17:10 +00005448 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005449
5450 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005451 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005452 Evaluate(NewVal, this->Info, E->getRHS());
5453 return false;
5454 }
5455
Richard Smith3229b742013-05-05 21:17:10 +00005456 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5457 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005458
5459 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005460 NewVal);
5461}
5462
Eli Friedman9a156e52008-11-12 09:44:48 +00005463//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005464// Pointer Evaluation
5465//===----------------------------------------------------------------------===//
5466
George Burgess IVe3763372016-12-22 02:50:20 +00005467/// \brief Attempts to compute the number of bytes available at the pointer
5468/// returned by a function with the alloc_size attribute. Returns true if we
5469/// were successful. Places an unsigned number into `Result`.
5470///
5471/// This expects the given CallExpr to be a call to a function with an
5472/// alloc_size attribute.
5473static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5474 const CallExpr *Call,
5475 llvm::APInt &Result) {
5476 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5477
Joel E. Denny81508102018-03-13 14:51:22 +00005478 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5479 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005480 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5481 if (Call->getNumArgs() <= SizeArgNo)
5482 return false;
5483
5484 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5485 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5486 return false;
5487 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5488 return false;
5489 Into = Into.zextOrSelf(BitsInSizeT);
5490 return true;
5491 };
5492
5493 APSInt SizeOfElem;
5494 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5495 return false;
5496
Joel E. Denny81508102018-03-13 14:51:22 +00005497 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005498 Result = std::move(SizeOfElem);
5499 return true;
5500 }
5501
5502 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00005503 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005504 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5505 return false;
5506
5507 bool Overflow;
5508 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5509 if (Overflow)
5510 return false;
5511
5512 Result = std::move(BytesAvailable);
5513 return true;
5514}
5515
5516/// \brief Convenience function. LVal's base must be a call to an alloc_size
5517/// function.
5518static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5519 const LValue &LVal,
5520 llvm::APInt &Result) {
5521 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5522 "Can't get the size of a non alloc_size function");
5523 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5524 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5525 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5526}
5527
5528/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5529/// a function with the alloc_size attribute. If it was possible to do so, this
5530/// function will return true, make Result's Base point to said function call,
5531/// and mark Result's Base as invalid.
5532static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5533 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005534 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005535 return false;
5536
5537 // Because we do no form of static analysis, we only support const variables.
5538 //
5539 // Additionally, we can't support parameters, nor can we support static
5540 // variables (in the latter case, use-before-assign isn't UB; in the former,
5541 // we have no clue what they'll be assigned to).
5542 const auto *VD =
5543 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5544 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5545 return false;
5546
5547 const Expr *Init = VD->getAnyInitializer();
5548 if (!Init)
5549 return false;
5550
5551 const Expr *E = Init->IgnoreParens();
5552 if (!tryUnwrapAllocSizeCall(E))
5553 return false;
5554
5555 // Store E instead of E unwrapped so that the type of the LValue's base is
5556 // what the user wanted.
5557 Result.setInvalid(E);
5558
5559 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005560 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005561 return true;
5562}
5563
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005564namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005565class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005566 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005567 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005568 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005569
Peter Collingbournee9200682011-05-13 03:29:01 +00005570 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005571 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005572 return true;
5573 }
George Burgess IVe3763372016-12-22 02:50:20 +00005574
George Burgess IVf9013bf2017-02-10 22:52:29 +00005575 bool evaluateLValue(const Expr *E, LValue &Result) {
5576 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5577 }
5578
5579 bool evaluatePointer(const Expr *E, LValue &Result) {
5580 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5581 }
5582
George Burgess IVe3763372016-12-22 02:50:20 +00005583 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005584public:
Mike Stump11289f42009-09-09 15:08:12 +00005585
George Burgess IVf9013bf2017-02-10 22:52:29 +00005586 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5587 : ExprEvaluatorBaseTy(info), Result(Result),
5588 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005589
Richard Smith2e312c82012-03-03 22:46:17 +00005590 bool Success(const APValue &V, const Expr *E) {
5591 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005592 return true;
5593 }
Richard Smithfddd3842011-12-30 21:15:51 +00005594 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005595 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5596 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005597 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005598 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005599
John McCall45d55e42010-05-07 21:00:08 +00005600 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005601 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005602 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005603 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005604 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005605 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5606 if (Info.noteFailure())
5607 EvaluateIgnoredValue(Info, E->getSubExpr());
5608 return Error(E);
5609 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005610 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005611 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005612 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005613 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005614 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005615 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005616 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005617 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005618 }
Richard Smithd62306a2011-11-10 06:34:14 +00005619 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005620 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005621 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005622 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005623 if (!Info.CurrentCall->This) {
5624 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005625 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005626 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005627 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005628 return false;
5629 }
Richard Smithd62306a2011-11-10 06:34:14 +00005630 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005631 // If we are inside a lambda's call operator, the 'this' expression refers
5632 // to the enclosing '*this' object (either by value or reference) which is
5633 // either copied into the closure object's field that represents the '*this'
5634 // or refers to '*this'.
5635 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5636 // Update 'Result' to refer to the data member/field of the closure object
5637 // that represents the '*this' capture.
5638 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005639 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005640 return false;
5641 // If we captured '*this' by reference, replace the field with its referent.
5642 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5643 ->isPointerType()) {
5644 APValue RVal;
5645 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5646 RVal))
5647 return false;
5648
5649 Result.setFrom(Info.Ctx, RVal);
5650 }
5651 }
Richard Smithd62306a2011-11-10 06:34:14 +00005652 return true;
5653 }
John McCallc07a0c72011-02-17 10:25:35 +00005654
Eli Friedman449fe542009-03-23 04:56:01 +00005655 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005656};
Chris Lattner05706e882008-07-11 18:11:29 +00005657} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005658
George Burgess IVf9013bf2017-02-10 22:52:29 +00005659static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5660 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005661 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005662 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005663}
5664
John McCall45d55e42010-05-07 21:00:08 +00005665bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005666 if (E->getOpcode() != BO_Add &&
5667 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005668 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005669
Chris Lattner05706e882008-07-11 18:11:29 +00005670 const Expr *PExp = E->getLHS();
5671 const Expr *IExp = E->getRHS();
5672 if (IExp->getType()->isPointerType())
5673 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005674
George Burgess IVf9013bf2017-02-10 22:52:29 +00005675 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005676 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005677 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005678
John McCall45d55e42010-05-07 21:00:08 +00005679 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005680 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005681 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005682
Richard Smith96e0c102011-11-04 02:25:55 +00005683 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005684 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005685
Ted Kremenek28831752012-08-23 20:46:57 +00005686 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005687 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005688}
Eli Friedman9a156e52008-11-12 09:44:48 +00005689
John McCall45d55e42010-05-07 21:00:08 +00005690bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005691 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005692}
Mike Stump11289f42009-09-09 15:08:12 +00005693
Peter Collingbournee9200682011-05-13 03:29:01 +00005694bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5695 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005696
Eli Friedman847a2bc2009-12-27 05:43:15 +00005697 switch (E->getCastKind()) {
5698 default:
5699 break;
5700
John McCalle3027922010-08-25 11:45:40 +00005701 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005702 case CK_CPointerToObjCPointerCast:
5703 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005704 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005705 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005706 if (!Visit(SubExpr))
5707 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005708 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5709 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5710 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005711 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005712 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005713 if (SubExpr->getType()->isVoidPointerType())
5714 CCEDiag(E, diag::note_constexpr_invalid_cast)
5715 << 3 << SubExpr->getType();
5716 else
5717 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5718 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005719 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5720 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005721 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005722
Anders Carlsson18275092010-10-31 20:41:46 +00005723 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005724 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005725 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005726 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005727 if (!Result.Base && Result.Offset.isZero())
5728 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005729
Richard Smithd62306a2011-11-10 06:34:14 +00005730 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005731 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005732 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5733 castAs<PointerType>()->getPointeeType(),
5734 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005735
Richard Smith027bf112011-11-17 22:56:20 +00005736 case CK_BaseToDerived:
5737 if (!Visit(E->getSubExpr()))
5738 return false;
5739 if (!Result.Base && Result.Offset.isZero())
5740 return true;
5741 return HandleBaseToDerivedCast(Info, E, Result);
5742
Richard Smith0b0a0b62011-10-29 20:57:55 +00005743 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005744 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005745 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005746
John McCalle3027922010-08-25 11:45:40 +00005747 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005748 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5749
Richard Smith2e312c82012-03-03 22:46:17 +00005750 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005751 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005752 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005753
John McCall45d55e42010-05-07 21:00:08 +00005754 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005755 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5756 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005757 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005758 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005759 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005760 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005761 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005762 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005763 return true;
5764 } else {
5765 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005766 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005767 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005768 }
5769 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005770
5771 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005772 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005773 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005774 return false;
5775 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005776 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005777 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005778 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005779 return false;
5780 }
Richard Smith96e0c102011-11-04 02:25:55 +00005781 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005782 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5783 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005784 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005785 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005786 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005787 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005788 }
Richard Smithdd785442011-10-31 20:57:44 +00005789
John McCalle3027922010-08-25 11:45:40 +00005790 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005791 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005792
5793 case CK_LValueToRValue: {
5794 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005795 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005796 return false;
5797
5798 APValue RVal;
5799 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5800 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5801 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005802 return InvalidBaseOK &&
5803 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005804 return Success(RVal, E);
5805 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005806 }
5807
Richard Smith11562c52011-10-28 17:51:58 +00005808 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005809}
Chris Lattner05706e882008-07-11 18:11:29 +00005810
Hal Finkel0dd05d42014-10-03 17:18:37 +00005811static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5812 // C++ [expr.alignof]p3:
5813 // When alignof is applied to a reference type, the result is the
5814 // alignment of the referenced type.
5815 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5816 T = Ref->getPointeeType();
5817
5818 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005819 if (T.getQualifiers().hasUnaligned())
5820 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005821 return Info.Ctx.toCharUnitsFromBits(
5822 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5823}
5824
5825static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5826 E = E->IgnoreParens();
5827
5828 // The kinds of expressions that we have special-case logic here for
5829 // should be kept up to date with the special checks for those
5830 // expressions in Sema.
5831
5832 // alignof decl is always accepted, even if it doesn't make sense: we default
5833 // to 1 in those cases.
5834 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5835 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5836 /*RefAsPointee*/true);
5837
5838 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5839 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5840 /*RefAsPointee*/true);
5841
5842 return GetAlignOfType(Info, E->getType());
5843}
5844
George Burgess IVe3763372016-12-22 02:50:20 +00005845// To be clear: this happily visits unsupported builtins. Better name welcomed.
5846bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5847 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5848 return true;
5849
George Burgess IVf9013bf2017-02-10 22:52:29 +00005850 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005851 return false;
5852
5853 Result.setInvalid(E);
5854 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005855 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005856 return true;
5857}
5858
Peter Collingbournee9200682011-05-13 03:29:01 +00005859bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005860 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005861 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005862
Richard Smith6328cbd2016-11-16 00:57:23 +00005863 if (unsigned BuiltinOp = E->getBuiltinCallee())
5864 return VisitBuiltinCallExpr(E, BuiltinOp);
5865
George Burgess IVe3763372016-12-22 02:50:20 +00005866 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005867}
5868
5869bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5870 unsigned BuiltinOp) {
5871 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005872 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005873 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005874 case Builtin::BI__builtin_assume_aligned: {
5875 // We need to be very careful here because: if the pointer does not have the
5876 // asserted alignment, then the behavior is undefined, and undefined
5877 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005878 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005879 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005880
Hal Finkel0dd05d42014-10-03 17:18:37 +00005881 LValue OffsetResult(Result);
5882 APSInt Alignment;
5883 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5884 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005885 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005886
5887 if (E->getNumArgs() > 2) {
5888 APSInt Offset;
5889 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5890 return false;
5891
Richard Smith642a2362017-01-30 23:30:26 +00005892 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005893 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5894 }
5895
5896 // If there is a base object, then it must have the correct alignment.
5897 if (OffsetResult.Base) {
5898 CharUnits BaseAlignment;
5899 if (const ValueDecl *VD =
5900 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5901 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5902 } else {
5903 BaseAlignment =
5904 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5905 }
5906
5907 if (BaseAlignment < Align) {
5908 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005909 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005910 CCEDiag(E->getArg(0),
5911 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005912 << (unsigned)BaseAlignment.getQuantity()
5913 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005914 return false;
5915 }
5916 }
5917
5918 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005919 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005920 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005921
Richard Smith642a2362017-01-30 23:30:26 +00005922 (OffsetResult.Base
5923 ? CCEDiag(E->getArg(0),
5924 diag::note_constexpr_baa_insufficient_alignment) << 1
5925 : CCEDiag(E->getArg(0),
5926 diag::note_constexpr_baa_value_insufficient_alignment))
5927 << (int)OffsetResult.Offset.getQuantity()
5928 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005929 return false;
5930 }
5931
5932 return true;
5933 }
Richard Smithe9507952016-11-12 01:39:56 +00005934
5935 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005936 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005937 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005938 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005939 if (Info.getLangOpts().CPlusPlus11)
5940 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5941 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005942 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005943 else
5944 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005945 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00005946 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005947 case Builtin::BI__builtin_wcschr:
5948 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005949 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005950 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005951 if (!Visit(E->getArg(0)))
5952 return false;
5953 APSInt Desired;
5954 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5955 return false;
5956 uint64_t MaxLength = uint64_t(-1);
5957 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005958 BuiltinOp != Builtin::BIwcschr &&
5959 BuiltinOp != Builtin::BI__builtin_strchr &&
5960 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005961 APSInt N;
5962 if (!EvaluateInteger(E->getArg(2), N, Info))
5963 return false;
5964 MaxLength = N.getExtValue();
5965 }
5966
Richard Smith8110c9d2016-11-29 19:45:17 +00005967 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005968
Richard Smith8110c9d2016-11-29 19:45:17 +00005969 // Figure out what value we're actually looking for (after converting to
5970 // the corresponding unsigned type if necessary).
5971 uint64_t DesiredVal;
5972 bool StopAtNull = false;
5973 switch (BuiltinOp) {
5974 case Builtin::BIstrchr:
5975 case Builtin::BI__builtin_strchr:
5976 // strchr compares directly to the passed integer, and therefore
5977 // always fails if given an int that is not a char.
5978 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5979 E->getArg(1)->getType(),
5980 Desired),
5981 Desired))
5982 return ZeroInitialization(E);
5983 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005984 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00005985 case Builtin::BImemchr:
5986 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005987 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005988 // memchr compares by converting both sides to unsigned char. That's also
5989 // correct for strchr if we get this far (to cope with plain char being
5990 // unsigned in the strchr case).
5991 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5992 break;
Richard Smithe9507952016-11-12 01:39:56 +00005993
Richard Smith8110c9d2016-11-29 19:45:17 +00005994 case Builtin::BIwcschr:
5995 case Builtin::BI__builtin_wcschr:
5996 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005997 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00005998 case Builtin::BIwmemchr:
5999 case Builtin::BI__builtin_wmemchr:
6000 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6001 DesiredVal = Desired.getZExtValue();
6002 break;
6003 }
Richard Smithe9507952016-11-12 01:39:56 +00006004
6005 for (; MaxLength; --MaxLength) {
6006 APValue Char;
6007 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6008 !Char.isInt())
6009 return false;
6010 if (Char.getInt().getZExtValue() == DesiredVal)
6011 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006012 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006013 break;
6014 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6015 return false;
6016 }
6017 // Not found: return nullptr.
6018 return ZeroInitialization(E);
6019 }
6020
Richard Smith6cbd65d2013-07-11 02:27:57 +00006021 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006022 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006023 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006024}
Chris Lattner05706e882008-07-11 18:11:29 +00006025
6026//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006027// Member Pointer Evaluation
6028//===----------------------------------------------------------------------===//
6029
6030namespace {
6031class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006032 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006033 MemberPtr &Result;
6034
6035 bool Success(const ValueDecl *D) {
6036 Result = MemberPtr(D);
6037 return true;
6038 }
6039public:
6040
6041 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6042 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6043
Richard Smith2e312c82012-03-03 22:46:17 +00006044 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006045 Result.setFrom(V);
6046 return true;
6047 }
Richard Smithfddd3842011-12-30 21:15:51 +00006048 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006049 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006050 }
6051
6052 bool VisitCastExpr(const CastExpr *E);
6053 bool VisitUnaryAddrOf(const UnaryOperator *E);
6054};
6055} // end anonymous namespace
6056
6057static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6058 EvalInfo &Info) {
6059 assert(E->isRValue() && E->getType()->isMemberPointerType());
6060 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6061}
6062
6063bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6064 switch (E->getCastKind()) {
6065 default:
6066 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6067
6068 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006069 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006070 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006071
6072 case CK_BaseToDerivedMemberPointer: {
6073 if (!Visit(E->getSubExpr()))
6074 return false;
6075 if (E->path_empty())
6076 return true;
6077 // Base-to-derived member pointer casts store the path in derived-to-base
6078 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6079 // the wrong end of the derived->base arc, so stagger the path by one class.
6080 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6081 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6082 PathI != PathE; ++PathI) {
6083 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6084 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6085 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006086 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006087 }
6088 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6089 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006090 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006091 return true;
6092 }
6093
6094 case CK_DerivedToBaseMemberPointer:
6095 if (!Visit(E->getSubExpr()))
6096 return false;
6097 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6098 PathE = E->path_end(); PathI != PathE; ++PathI) {
6099 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6100 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6101 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006102 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006103 }
6104 return true;
6105 }
6106}
6107
6108bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6109 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6110 // member can be formed.
6111 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6112}
6113
6114//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006115// Record Evaluation
6116//===----------------------------------------------------------------------===//
6117
6118namespace {
6119 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006120 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006121 const LValue &This;
6122 APValue &Result;
6123 public:
6124
6125 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6126 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6127
Richard Smith2e312c82012-03-03 22:46:17 +00006128 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006129 Result = V;
6130 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006131 }
Richard Smithb8348f52016-05-12 22:16:28 +00006132 bool ZeroInitialization(const Expr *E) {
6133 return ZeroInitialization(E, E->getType());
6134 }
6135 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006136
Richard Smith52a980a2015-08-28 02:43:42 +00006137 bool VisitCallExpr(const CallExpr *E) {
6138 return handleCallExpr(E, Result, &This);
6139 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006140 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006141 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006142 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6143 return VisitCXXConstructExpr(E, E->getType());
6144 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006145 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006146 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006147 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006148 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006149 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006150}
Richard Smithd62306a2011-11-10 06:34:14 +00006151
Richard Smithfddd3842011-12-30 21:15:51 +00006152/// Perform zero-initialization on an object of non-union class type.
6153/// C++11 [dcl.init]p5:
6154/// To zero-initialize an object or reference of type T means:
6155/// [...]
6156/// -- if T is a (possibly cv-qualified) non-union class type,
6157/// each non-static data member and each base-class subobject is
6158/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006159static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6160 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006161 const LValue &This, APValue &Result) {
6162 assert(!RD->isUnion() && "Expected non-union class type");
6163 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6164 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006165 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006166
John McCalld7bca762012-05-01 00:38:49 +00006167 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006168 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6169
6170 if (CD) {
6171 unsigned Index = 0;
6172 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006173 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006174 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6175 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006176 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6177 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006178 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006179 Result.getStructBase(Index)))
6180 return false;
6181 }
6182 }
6183
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006184 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006185 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006186 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006187 continue;
6188
6189 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006190 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006191 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006192
David Blaikie2d7c57e2012-04-30 02:36:29 +00006193 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006194 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006195 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006196 return false;
6197 }
6198
6199 return true;
6200}
6201
Richard Smithb8348f52016-05-12 22:16:28 +00006202bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6203 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006204 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006205 if (RD->isUnion()) {
6206 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6207 // object's first non-static named data member is zero-initialized
6208 RecordDecl::field_iterator I = RD->field_begin();
6209 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006210 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006211 return true;
6212 }
6213
6214 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006215 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006216 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006217 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006218 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006219 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006220 }
6221
Richard Smith5d108602012-02-17 00:44:16 +00006222 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006223 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006224 return false;
6225 }
6226
Richard Smitha8105bc2012-01-06 16:39:00 +00006227 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006228}
6229
Richard Smithe97cbd72011-11-11 04:05:33 +00006230bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6231 switch (E->getCastKind()) {
6232 default:
6233 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6234
6235 case CK_ConstructorConversion:
6236 return Visit(E->getSubExpr());
6237
6238 case CK_DerivedToBase:
6239 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006240 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006241 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006242 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006243 if (!DerivedObject.isStruct())
6244 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006245
6246 // Derived-to-base rvalue conversion: just slice off the derived part.
6247 APValue *Value = &DerivedObject;
6248 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6249 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6250 PathE = E->path_end(); PathI != PathE; ++PathI) {
6251 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6252 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6253 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6254 RD = Base;
6255 }
6256 Result = *Value;
6257 return true;
6258 }
6259 }
6260}
6261
Richard Smithd62306a2011-11-10 06:34:14 +00006262bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006263 if (E->isTransparent())
6264 return Visit(E->getInit(0));
6265
Richard Smithd62306a2011-11-10 06:34:14 +00006266 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006267 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006268 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6269
6270 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006271 const FieldDecl *Field = E->getInitializedFieldInUnion();
6272 Result = APValue(Field);
6273 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006274 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006275
6276 // If the initializer list for a union does not contain any elements, the
6277 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006278 // FIXME: The element should be initialized from an initializer list.
6279 // Is this difference ever observable for initializer lists which
6280 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006281 ImplicitValueInitExpr VIE(Field->getType());
6282 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6283
Richard Smithd62306a2011-11-10 06:34:14 +00006284 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006285 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6286 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006287
6288 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6289 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6290 isa<CXXDefaultInitExpr>(InitExpr));
6291
Richard Smithb228a862012-02-15 02:18:13 +00006292 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006293 }
6294
Richard Smith872307e2016-03-08 22:17:41 +00006295 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006296 if (Result.isUninit())
6297 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6298 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006299 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006300 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006301
6302 // Initialize base classes.
6303 if (CXXRD) {
6304 for (const auto &Base : CXXRD->bases()) {
6305 assert(ElementNo < E->getNumInits() && "missing init for base class");
6306 const Expr *Init = E->getInit(ElementNo);
6307
6308 LValue Subobject = This;
6309 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6310 return false;
6311
6312 APValue &FieldVal = Result.getStructBase(ElementNo);
6313 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006314 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006315 return false;
6316 Success = false;
6317 }
6318 ++ElementNo;
6319 }
6320 }
6321
6322 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006323 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006324 // Anonymous bit-fields are not considered members of the class for
6325 // purposes of aggregate initialization.
6326 if (Field->isUnnamedBitfield())
6327 continue;
6328
6329 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006330
Richard Smith253c2a32012-01-27 01:14:48 +00006331 bool HaveInit = ElementNo < E->getNumInits();
6332
6333 // FIXME: Diagnostics here should point to the end of the initializer
6334 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006335 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006336 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006337 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006338
6339 // Perform an implicit value-initialization for members beyond the end of
6340 // the initializer list.
6341 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006342 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006343
Richard Smith852c9db2013-04-20 22:23:05 +00006344 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6345 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6346 isa<CXXDefaultInitExpr>(Init));
6347
Richard Smith49ca8aa2013-08-06 07:09:20 +00006348 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6349 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6350 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006351 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006352 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006353 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006354 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006355 }
6356 }
6357
Richard Smith253c2a32012-01-27 01:14:48 +00006358 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006359}
6360
Richard Smithb8348f52016-05-12 22:16:28 +00006361bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6362 QualType T) {
6363 // Note that E's type is not necessarily the type of our class here; we might
6364 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006365 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006366 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6367
Richard Smithfddd3842011-12-30 21:15:51 +00006368 bool ZeroInit = E->requiresZeroInitialization();
6369 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006370 // If we've already performed zero-initialization, we're already done.
6371 if (!Result.isUninit())
6372 return true;
6373
Richard Smithda3f4fd2014-03-05 23:32:50 +00006374 // We can get here in two different ways:
6375 // 1) We're performing value-initialization, and should zero-initialize
6376 // the object, or
6377 // 2) We're performing default-initialization of an object with a trivial
6378 // constexpr default constructor, in which case we should start the
6379 // lifetimes of all the base subobjects (there can be no data member
6380 // subobjects in this case) per [basic.life]p1.
6381 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006382 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006383 }
6384
Craig Topper36250ad2014-05-12 05:36:57 +00006385 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006386 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006387
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006388 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006389 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006390
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006391 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006392 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006393 if (const MaterializeTemporaryExpr *ME
6394 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6395 return Visit(ME->GetTemporaryExpr());
6396
Richard Smithb8348f52016-05-12 22:16:28 +00006397 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006398 return false;
6399
Craig Topper5fc8fc22014-08-27 06:28:36 +00006400 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006401 return HandleConstructorCall(E, This, Args,
6402 cast<CXXConstructorDecl>(Definition), Info,
6403 Result);
6404}
6405
6406bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6407 const CXXInheritedCtorInitExpr *E) {
6408 if (!Info.CurrentCall) {
6409 assert(Info.checkingPotentialConstantExpression());
6410 return false;
6411 }
6412
6413 const CXXConstructorDecl *FD = E->getConstructor();
6414 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6415 return false;
6416
6417 const FunctionDecl *Definition = nullptr;
6418 auto Body = FD->getBody(Definition);
6419
6420 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6421 return false;
6422
6423 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006424 cast<CXXConstructorDecl>(Definition), Info,
6425 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006426}
6427
Richard Smithcc1b96d2013-06-12 22:31:48 +00006428bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6429 const CXXStdInitializerListExpr *E) {
6430 const ConstantArrayType *ArrayType =
6431 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6432
6433 LValue Array;
6434 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6435 return false;
6436
6437 // Get a pointer to the first element of the array.
6438 Array.addArray(Info, E, ArrayType);
6439
6440 // FIXME: Perform the checks on the field types in SemaInit.
6441 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6442 RecordDecl::field_iterator Field = Record->field_begin();
6443 if (Field == Record->field_end())
6444 return Error(E);
6445
6446 // Start pointer.
6447 if (!Field->getType()->isPointerType() ||
6448 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6449 ArrayType->getElementType()))
6450 return Error(E);
6451
6452 // FIXME: What if the initializer_list type has base classes, etc?
6453 Result = APValue(APValue::UninitStruct(), 0, 2);
6454 Array.moveInto(Result.getStructField(0));
6455
6456 if (++Field == Record->field_end())
6457 return Error(E);
6458
6459 if (Field->getType()->isPointerType() &&
6460 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6461 ArrayType->getElementType())) {
6462 // End pointer.
6463 if (!HandleLValueArrayAdjustment(Info, E, Array,
6464 ArrayType->getElementType(),
6465 ArrayType->getSize().getZExtValue()))
6466 return false;
6467 Array.moveInto(Result.getStructField(1));
6468 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6469 // Length.
6470 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6471 else
6472 return Error(E);
6473
6474 if (++Field != Record->field_end())
6475 return Error(E);
6476
6477 return true;
6478}
6479
Faisal Valic72a08c2017-01-09 03:02:53 +00006480bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6481 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6482 if (ClosureClass->isInvalidDecl()) return false;
6483
6484 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006485
Faisal Vali051e3a22017-02-16 04:12:21 +00006486 const size_t NumFields =
6487 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006488
6489 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6490 E->capture_init_end()) &&
6491 "The number of lambda capture initializers should equal the number of "
6492 "fields within the closure type");
6493
Faisal Vali051e3a22017-02-16 04:12:21 +00006494 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6495 // Iterate through all the lambda's closure object's fields and initialize
6496 // them.
6497 auto *CaptureInitIt = E->capture_init_begin();
6498 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6499 bool Success = true;
6500 for (const auto *Field : ClosureClass->fields()) {
6501 assert(CaptureInitIt != E->capture_init_end());
6502 // Get the initializer for this field
6503 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006504
Faisal Vali051e3a22017-02-16 04:12:21 +00006505 // If there is no initializer, either this is a VLA or an error has
6506 // occurred.
6507 if (!CurFieldInit)
6508 return Error(E);
6509
6510 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6511 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6512 if (!Info.keepEvaluatingAfterFailure())
6513 return false;
6514 Success = false;
6515 }
6516 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006517 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006518 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006519}
6520
Richard Smithd62306a2011-11-10 06:34:14 +00006521static bool EvaluateRecord(const Expr *E, const LValue &This,
6522 APValue &Result, EvalInfo &Info) {
6523 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006524 "can't evaluate expression as a record rvalue");
6525 return RecordExprEvaluator(Info, This, Result).Visit(E);
6526}
6527
6528//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006529// Temporary Evaluation
6530//
6531// Temporaries are represented in the AST as rvalues, but generally behave like
6532// lvalues. The full-object of which the temporary is a subobject is implicitly
6533// materialized so that a reference can bind to it.
6534//===----------------------------------------------------------------------===//
6535namespace {
6536class TemporaryExprEvaluator
6537 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6538public:
6539 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006540 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006541
6542 /// Visit an expression which constructs the value of this temporary.
6543 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006544 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006545 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6546 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006547 }
6548
6549 bool VisitCastExpr(const CastExpr *E) {
6550 switch (E->getCastKind()) {
6551 default:
6552 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6553
6554 case CK_ConstructorConversion:
6555 return VisitConstructExpr(E->getSubExpr());
6556 }
6557 }
6558 bool VisitInitListExpr(const InitListExpr *E) {
6559 return VisitConstructExpr(E);
6560 }
6561 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6562 return VisitConstructExpr(E);
6563 }
6564 bool VisitCallExpr(const CallExpr *E) {
6565 return VisitConstructExpr(E);
6566 }
Richard Smith513955c2014-12-17 19:24:30 +00006567 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6568 return VisitConstructExpr(E);
6569 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006570 bool VisitLambdaExpr(const LambdaExpr *E) {
6571 return VisitConstructExpr(E);
6572 }
Richard Smith027bf112011-11-17 22:56:20 +00006573};
6574} // end anonymous namespace
6575
6576/// Evaluate an expression of record type as a temporary.
6577static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006578 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006579 return TemporaryExprEvaluator(Info, Result).Visit(E);
6580}
6581
6582//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006583// Vector Evaluation
6584//===----------------------------------------------------------------------===//
6585
6586namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006587 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006588 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006589 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006590 public:
Mike Stump11289f42009-09-09 15:08:12 +00006591
Richard Smith2d406342011-10-22 21:10:00 +00006592 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6593 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006594
Craig Topper9798b932015-09-29 04:30:05 +00006595 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006596 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6597 // FIXME: remove this APValue copy.
6598 Result = APValue(V.data(), V.size());
6599 return true;
6600 }
Richard Smith2e312c82012-03-03 22:46:17 +00006601 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006602 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006603 Result = V;
6604 return true;
6605 }
Richard Smithfddd3842011-12-30 21:15:51 +00006606 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006607
Richard Smith2d406342011-10-22 21:10:00 +00006608 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006609 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006610 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006611 bool VisitInitListExpr(const InitListExpr *E);
6612 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006613 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006614 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006615 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006616 };
6617} // end anonymous namespace
6618
6619static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006620 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006621 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006622}
6623
George Burgess IV533ff002015-12-11 00:23:35 +00006624bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006625 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006626 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006627
Richard Smith161f09a2011-12-06 22:44:34 +00006628 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006629 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006630
Eli Friedmanc757de22011-03-25 00:43:55 +00006631 switch (E->getCastKind()) {
6632 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006633 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006634 if (SETy->isIntegerType()) {
6635 APSInt IntResult;
6636 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006637 return false;
6638 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006639 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006640 APFloat FloatResult(0.0);
6641 if (!EvaluateFloat(SE, FloatResult, Info))
6642 return false;
6643 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006644 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006645 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006646 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006647
6648 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006649 SmallVector<APValue, 4> Elts(NElts, Val);
6650 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006651 }
Eli Friedman803acb32011-12-22 03:51:45 +00006652 case CK_BitCast: {
6653 // Evaluate the operand into an APInt we can extract from.
6654 llvm::APInt SValInt;
6655 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6656 return false;
6657 // Extract the elements
6658 QualType EltTy = VTy->getElementType();
6659 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6660 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6661 SmallVector<APValue, 4> Elts;
6662 if (EltTy->isRealFloatingType()) {
6663 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006664 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006665 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006666 FloatEltSize = 80;
6667 for (unsigned i = 0; i < NElts; i++) {
6668 llvm::APInt Elt;
6669 if (BigEndian)
6670 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6671 else
6672 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006673 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006674 }
6675 } else if (EltTy->isIntegerType()) {
6676 for (unsigned i = 0; i < NElts; i++) {
6677 llvm::APInt Elt;
6678 if (BigEndian)
6679 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6680 else
6681 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6682 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6683 }
6684 } else {
6685 return Error(E);
6686 }
6687 return Success(Elts, E);
6688 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006689 default:
Richard Smith11562c52011-10-28 17:51:58 +00006690 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006691 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006692}
6693
Richard Smith2d406342011-10-22 21:10:00 +00006694bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006695VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006696 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006697 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006698 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006699
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006700 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006701 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006702
Eli Friedmanb9c71292012-01-03 23:24:20 +00006703 // The number of initializers can be less than the number of
6704 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006705 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006706 // should be initialized with zeroes.
6707 unsigned CountInits = 0, CountElts = 0;
6708 while (CountElts < NumElements) {
6709 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006710 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006711 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006712 APValue v;
6713 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6714 return Error(E);
6715 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006716 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006717 Elements.push_back(v.getVectorElt(j));
6718 CountElts += vlen;
6719 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006720 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006721 if (CountInits < NumInits) {
6722 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006723 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006724 } else // trailing integer zero.
6725 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6726 Elements.push_back(APValue(sInt));
6727 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006728 } else {
6729 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006730 if (CountInits < NumInits) {
6731 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006732 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006733 } else // trailing float zero.
6734 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6735 Elements.push_back(APValue(f));
6736 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006737 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006738 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006739 }
Richard Smith2d406342011-10-22 21:10:00 +00006740 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006741}
6742
Richard Smith2d406342011-10-22 21:10:00 +00006743bool
Richard Smithfddd3842011-12-30 21:15:51 +00006744VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006745 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006746 QualType EltTy = VT->getElementType();
6747 APValue ZeroElement;
6748 if (EltTy->isIntegerType())
6749 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6750 else
6751 ZeroElement =
6752 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6753
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006754 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006755 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006756}
6757
Richard Smith2d406342011-10-22 21:10:00 +00006758bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006759 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006760 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006761}
6762
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006763//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006764// Array Evaluation
6765//===----------------------------------------------------------------------===//
6766
6767namespace {
6768 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006769 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006770 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006771 APValue &Result;
6772 public:
6773
Richard Smithd62306a2011-11-10 06:34:14 +00006774 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6775 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006776
6777 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006778 assert((V.isArray() || V.isLValue()) &&
6779 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006780 Result = V;
6781 return true;
6782 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006783
Richard Smithfddd3842011-12-30 21:15:51 +00006784 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006785 const ConstantArrayType *CAT =
6786 Info.Ctx.getAsConstantArrayType(E->getType());
6787 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006788 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006789
6790 Result = APValue(APValue::UninitArray(), 0,
6791 CAT->getSize().getZExtValue());
6792 if (!Result.hasArrayFiller()) return true;
6793
Richard Smithfddd3842011-12-30 21:15:51 +00006794 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006795 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006796 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006797 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006798 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006799 }
6800
Richard Smith52a980a2015-08-28 02:43:42 +00006801 bool VisitCallExpr(const CallExpr *E) {
6802 return handleCallExpr(E, Result, &This);
6803 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006804 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006805 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006806 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006807 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6808 const LValue &Subobject,
6809 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006810 };
6811} // end anonymous namespace
6812
Richard Smithd62306a2011-11-10 06:34:14 +00006813static bool EvaluateArray(const Expr *E, const LValue &This,
6814 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006815 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006816 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006817}
6818
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006819// Return true iff the given array filler may depend on the element index.
6820static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
6821 // For now, just whitelist non-class value-initialization and initialization
6822 // lists comprised of them.
6823 if (isa<ImplicitValueInitExpr>(FillerExpr))
6824 return false;
6825 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
6826 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
6827 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
6828 return true;
6829 }
6830 return false;
6831 }
6832 return true;
6833}
6834
Richard Smithf3e9e432011-11-07 09:22:26 +00006835bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6836 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6837 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006838 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006839
Richard Smithca2cfbf2011-12-22 01:07:19 +00006840 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6841 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006842 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006843 LValue LV;
6844 if (!EvaluateLValue(E->getInit(0), LV, Info))
6845 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006846 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006847 LV.moveInto(Val);
6848 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006849 }
6850
Richard Smith253c2a32012-01-27 01:14:48 +00006851 bool Success = true;
6852
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006853 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6854 "zero-initialized array shouldn't have any initialized elts");
6855 APValue Filler;
6856 if (Result.isArray() && Result.hasArrayFiller())
6857 Filler = Result.getArrayFiller();
6858
Richard Smith9543c5e2013-04-22 14:44:29 +00006859 unsigned NumEltsToInit = E->getNumInits();
6860 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006861 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006862
6863 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006864 // array element.
6865 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00006866 NumEltsToInit = NumElts;
6867
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006868 DEBUG(llvm::dbgs() << "The number of elements to initialize: " <<
6869 NumEltsToInit << ".\n");
6870
Richard Smith9543c5e2013-04-22 14:44:29 +00006871 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006872
6873 // If the array was previously zero-initialized, preserve the
6874 // zero-initialized values.
6875 if (!Filler.isUninit()) {
6876 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6877 Result.getArrayInitializedElt(I) = Filler;
6878 if (Result.hasArrayFiller())
6879 Result.getArrayFiller() = Filler;
6880 }
6881
Richard Smithd62306a2011-11-10 06:34:14 +00006882 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006883 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006884 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6885 const Expr *Init =
6886 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006887 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006888 Info, Subobject, Init) ||
6889 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006890 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006891 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006892 return false;
6893 Success = false;
6894 }
Richard Smithd62306a2011-11-10 06:34:14 +00006895 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006896
Richard Smith9543c5e2013-04-22 14:44:29 +00006897 if (!Result.hasArrayFiller())
6898 return Success;
6899
6900 // If we get here, we have a trivial filler, which we can just evaluate
6901 // once and splat over the rest of the array elements.
6902 assert(FillerExpr && "no array filler for incomplete init list");
6903 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6904 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006905}
6906
Richard Smith410306b2016-12-12 02:53:20 +00006907bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6908 if (E->getCommonExpr() &&
6909 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6910 Info, E->getCommonExpr()->getSourceExpr()))
6911 return false;
6912
6913 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6914
6915 uint64_t Elements = CAT->getSize().getZExtValue();
6916 Result = APValue(APValue::UninitArray(), Elements, Elements);
6917
6918 LValue Subobject = This;
6919 Subobject.addArray(Info, E, CAT);
6920
6921 bool Success = true;
6922 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6923 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6924 Info, Subobject, E->getSubExpr()) ||
6925 !HandleLValueArrayAdjustment(Info, E, Subobject,
6926 CAT->getElementType(), 1)) {
6927 if (!Info.noteFailure())
6928 return false;
6929 Success = false;
6930 }
6931 }
6932
6933 return Success;
6934}
6935
Richard Smith027bf112011-11-17 22:56:20 +00006936bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006937 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6938}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006939
Richard Smith9543c5e2013-04-22 14:44:29 +00006940bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6941 const LValue &Subobject,
6942 APValue *Value,
6943 QualType Type) {
6944 bool HadZeroInit = !Value->isUninit();
6945
6946 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6947 unsigned N = CAT->getSize().getZExtValue();
6948
6949 // Preserve the array filler if we had prior zero-initialization.
6950 APValue Filler =
6951 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6952 : APValue();
6953
6954 *Value = APValue(APValue::UninitArray(), N, N);
6955
6956 if (HadZeroInit)
6957 for (unsigned I = 0; I != N; ++I)
6958 Value->getArrayInitializedElt(I) = Filler;
6959
6960 // Initialize the elements.
6961 LValue ArrayElt = Subobject;
6962 ArrayElt.addArray(Info, E, CAT);
6963 for (unsigned I = 0; I != N; ++I)
6964 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6965 CAT->getElementType()) ||
6966 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6967 CAT->getElementType(), 1))
6968 return false;
6969
6970 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006971 }
Richard Smith027bf112011-11-17 22:56:20 +00006972
Richard Smith9543c5e2013-04-22 14:44:29 +00006973 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006974 return Error(E);
6975
Richard Smithb8348f52016-05-12 22:16:28 +00006976 return RecordExprEvaluator(Info, Subobject, *Value)
6977 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006978}
6979
Richard Smithf3e9e432011-11-07 09:22:26 +00006980//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006981// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006982//
6983// As a GNU extension, we support casting pointers to sufficiently-wide integer
6984// types and back in constant folding. Integer values are thus represented
6985// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006986//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006987
6988namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006989class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006990 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006991 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006992public:
Richard Smith2e312c82012-03-03 22:46:17 +00006993 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006994 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006995
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006996 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006997 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006998 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006999 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007000 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007001 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007002 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007003 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007004 return true;
7005 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007006 bool Success(const llvm::APSInt &SI, const Expr *E) {
7007 return Success(SI, E, Result);
7008 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007009
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007010 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00007011 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007012 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007013 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007014 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007015 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007016 Result.getInt().setIsUnsigned(
7017 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007018 return true;
7019 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007020 bool Success(const llvm::APInt &I, const Expr *E) {
7021 return Success(I, E, Result);
7022 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007023
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007024 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00007025 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007026 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007027 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007028 return true;
7029 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007030 bool Success(uint64_t Value, const Expr *E) {
7031 return Success(Value, E, Result);
7032 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007033
Ken Dyckdbc01912011-03-11 02:13:43 +00007034 bool Success(CharUnits Size, const Expr *E) {
7035 return Success(Size.getQuantity(), E);
7036 }
7037
Richard Smith2e312c82012-03-03 22:46:17 +00007038 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007039 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007040 Result = V;
7041 return true;
7042 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007043 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007044 }
Mike Stump11289f42009-09-09 15:08:12 +00007045
Richard Smithfddd3842011-12-30 21:15:51 +00007046 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007047
Peter Collingbournee9200682011-05-13 03:29:01 +00007048 //===--------------------------------------------------------------------===//
7049 // Visitor Methods
7050 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007051
Chris Lattner7174bf32008-07-12 00:38:25 +00007052 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007053 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007054 }
7055 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007056 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007057 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007058
7059 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7060 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007061 if (CheckReferencedDecl(E, E->getDecl()))
7062 return true;
7063
7064 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007065 }
7066 bool VisitMemberExpr(const MemberExpr *E) {
7067 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007068 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007069 return true;
7070 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007071
7072 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007073 }
7074
Peter Collingbournee9200682011-05-13 03:29:01 +00007075 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007076 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007077 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007078 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007079 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007080
Peter Collingbournee9200682011-05-13 03:29:01 +00007081 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007082 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007083
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007084 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007085 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007086 }
Mike Stump11289f42009-09-09 15:08:12 +00007087
Ted Kremeneke65b0862012-03-06 20:05:56 +00007088 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7089 return Success(E->getValue(), E);
7090 }
Richard Smith410306b2016-12-12 02:53:20 +00007091
7092 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7093 if (Info.ArrayInitIndex == uint64_t(-1)) {
7094 // We were asked to evaluate this subexpression independent of the
7095 // enclosing ArrayInitLoopExpr. We can't do that.
7096 Info.FFDiag(E);
7097 return false;
7098 }
7099 return Success(Info.ArrayInitIndex, E);
7100 }
Daniel Jasperffdee092017-05-02 19:21:42 +00007101
Richard Smith4ce706a2011-10-11 21:43:33 +00007102 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007103 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007104 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007105 }
7106
Douglas Gregor29c42f22012-02-24 07:38:34 +00007107 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7108 return Success(E->getValue(), E);
7109 }
7110
John Wiegley6242b6a2011-04-28 00:16:57 +00007111 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7112 return Success(E->getValue(), E);
7113 }
7114
John Wiegleyf9f65842011-04-25 06:54:41 +00007115 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7116 return Success(E->getValue(), E);
7117 }
7118
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007119 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007120 bool VisitUnaryImag(const UnaryOperator *E);
7121
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007122 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007123 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007124
Eli Friedman4e7a2412009-02-27 04:45:43 +00007125 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007126};
Chris Lattner05706e882008-07-11 18:11:29 +00007127} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007128
Richard Smith11562c52011-10-28 17:51:58 +00007129/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7130/// produce either the integer value or a pointer.
7131///
7132/// GCC has a heinous extension which folds casts between pointer types and
7133/// pointer-sized integral types. We support this by allowing the evaluation of
7134/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7135/// Some simple arithmetic on such values is supported (they are treated much
7136/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007137static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007138 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007139 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007140 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007141}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007142
Richard Smithf57d8cb2011-12-09 22:58:01 +00007143static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007144 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007145 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007146 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007147 if (!Val.isInt()) {
7148 // FIXME: It would be better to produce the diagnostic for casting
7149 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007150 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007151 return false;
7152 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007153 Result = Val.getInt();
7154 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007155}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007156
Richard Smithf57d8cb2011-12-09 22:58:01 +00007157/// Check whether the given declaration can be directly converted to an integral
7158/// rvalue. If not, no diagnostic is produced; there are other things we can
7159/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007160bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007161 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007162 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007163 // Check for signedness/width mismatches between E type and ECD value.
7164 bool SameSign = (ECD->getInitVal().isSigned()
7165 == E->getType()->isSignedIntegerOrEnumerationType());
7166 bool SameWidth = (ECD->getInitVal().getBitWidth()
7167 == Info.Ctx.getIntWidth(E->getType()));
7168 if (SameSign && SameWidth)
7169 return Success(ECD->getInitVal(), E);
7170 else {
7171 // Get rid of mismatch (otherwise Success assertions will fail)
7172 // by computing a new value matching the type of E.
7173 llvm::APSInt Val = ECD->getInitVal();
7174 if (!SameSign)
7175 Val.setIsSigned(!ECD->getInitVal().isSigned());
7176 if (!SameWidth)
7177 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7178 return Success(Val, E);
7179 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007180 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007181 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007182}
7183
Chris Lattner86ee2862008-10-06 06:40:35 +00007184/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7185/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007186static int EvaluateBuiltinClassifyType(const CallExpr *E,
7187 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007188 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007189 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007190 enum gcc_type_class {
7191 no_type_class = -1,
7192 void_type_class, integer_type_class, char_type_class,
7193 enumeral_type_class, boolean_type_class,
7194 pointer_type_class, reference_type_class, offset_type_class,
7195 real_type_class, complex_type_class,
7196 function_type_class, method_type_class,
7197 record_type_class, union_type_class,
7198 array_type_class, string_type_class,
7199 lang_type_class
7200 };
Mike Stump11289f42009-09-09 15:08:12 +00007201
7202 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007203 // ideal, however it is what gcc does.
7204 if (E->getNumArgs() == 0)
7205 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007206
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007207 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7208 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7209
7210 switch (CanTy->getTypeClass()) {
7211#define TYPE(ID, BASE)
7212#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7213#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7214#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7215#include "clang/AST/TypeNodes.def"
7216 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7217
7218 case Type::Builtin:
7219 switch (BT->getKind()) {
7220#define BUILTIN_TYPE(ID, SINGLETON_ID)
7221#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7222#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7223#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7224#include "clang/AST/BuiltinTypes.def"
7225 case BuiltinType::Void:
7226 return void_type_class;
7227
7228 case BuiltinType::Bool:
7229 return boolean_type_class;
7230
7231 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7232 case BuiltinType::UChar:
7233 case BuiltinType::UShort:
7234 case BuiltinType::UInt:
7235 case BuiltinType::ULong:
7236 case BuiltinType::ULongLong:
7237 case BuiltinType::UInt128:
7238 return integer_type_class;
7239
7240 case BuiltinType::NullPtr:
7241 return pointer_type_class;
7242
7243 case BuiltinType::WChar_U:
7244 case BuiltinType::Char16:
7245 case BuiltinType::Char32:
7246 case BuiltinType::ObjCId:
7247 case BuiltinType::ObjCClass:
7248 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007249#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7250 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007251#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007252 case BuiltinType::OCLSampler:
7253 case BuiltinType::OCLEvent:
7254 case BuiltinType::OCLClkEvent:
7255 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007256 case BuiltinType::OCLReserveID:
7257 case BuiltinType::Dependent:
7258 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7259 };
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007260 break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007261
7262 case Type::Enum:
7263 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7264 break;
7265
7266 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007267 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007268 break;
7269
7270 case Type::MemberPointer:
7271 if (CanTy->isMemberDataPointerType())
7272 return offset_type_class;
7273 else {
7274 // We expect member pointers to be either data or function pointers,
7275 // nothing else.
7276 assert(CanTy->isMemberFunctionPointerType());
7277 return method_type_class;
7278 }
7279
7280 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007281 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007282
7283 case Type::FunctionNoProto:
7284 case Type::FunctionProto:
7285 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7286
7287 case Type::Record:
7288 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7289 switch (RT->getDecl()->getTagKind()) {
7290 case TagTypeKind::TTK_Struct:
7291 case TagTypeKind::TTK_Class:
7292 case TagTypeKind::TTK_Interface:
7293 return record_type_class;
7294
7295 case TagTypeKind::TTK_Enum:
7296 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7297
7298 case TagTypeKind::TTK_Union:
7299 return union_type_class;
7300 }
7301 }
David Blaikie83d382b2011-09-23 05:06:16 +00007302 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007303
7304 case Type::ConstantArray:
7305 case Type::VariableArray:
7306 case Type::IncompleteArray:
7307 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7308
7309 case Type::BlockPointer:
7310 case Type::LValueReference:
7311 case Type::RValueReference:
7312 case Type::Vector:
7313 case Type::ExtVector:
7314 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007315 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007316 case Type::ObjCObject:
7317 case Type::ObjCInterface:
7318 case Type::ObjCObjectPointer:
7319 case Type::Pipe:
7320 case Type::Atomic:
7321 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7322 }
7323
7324 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007325}
7326
Richard Smith5fab0c92011-12-28 19:48:30 +00007327/// EvaluateBuiltinConstantPForLValue - Determine the result of
7328/// __builtin_constant_p when applied to the given lvalue.
7329///
7330/// An lvalue is only "constant" if it is a pointer or reference to the first
7331/// character of a string literal.
7332template<typename LValue>
7333static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007334 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007335 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7336}
7337
7338/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7339/// GCC as we can manage.
7340static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7341 QualType ArgType = Arg->getType();
7342
7343 // __builtin_constant_p always has one operand. The rules which gcc follows
7344 // are not precisely documented, but are as follows:
7345 //
7346 // - If the operand is of integral, floating, complex or enumeration type,
7347 // and can be folded to a known value of that type, it returns 1.
7348 // - If the operand and can be folded to a pointer to the first character
7349 // of a string literal (or such a pointer cast to an integral type), it
7350 // returns 1.
7351 //
7352 // Otherwise, it returns 0.
7353 //
7354 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7355 // its support for this does not currently work.
7356 if (ArgType->isIntegralOrEnumerationType()) {
7357 Expr::EvalResult Result;
7358 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7359 return false;
7360
7361 APValue &V = Result.Val;
7362 if (V.getKind() == APValue::Int)
7363 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007364 if (V.getKind() == APValue::LValue)
7365 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007366 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7367 return Arg->isEvaluatable(Ctx);
7368 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7369 LValue LV;
7370 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007371 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007372 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7373 : EvaluatePointer(Arg, LV, Info)) &&
7374 !Status.HasSideEffects)
7375 return EvaluateBuiltinConstantPForLValue(LV);
7376 }
7377
7378 // Anything else isn't considered to be sufficiently constant.
7379 return false;
7380}
7381
John McCall95007602010-05-10 23:27:23 +00007382/// Retrieves the "underlying object type" of the given expression,
7383/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007384static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007385 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7386 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007387 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007388 } else if (const Expr *E = B.get<const Expr*>()) {
7389 if (isa<CompoundLiteralExpr>(E))
7390 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007391 }
7392
7393 return QualType();
7394}
7395
George Burgess IV3a03fab2015-09-04 21:28:13 +00007396/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007397/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007398/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007399/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7400///
7401/// Always returns an RValue with a pointer representation.
7402static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7403 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7404
7405 auto *NoParens = E->IgnoreParens();
7406 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007407 if (Cast == nullptr)
7408 return NoParens;
7409
7410 // We only conservatively allow a few kinds of casts, because this code is
7411 // inherently a simple solution that seeks to support the common case.
7412 auto CastKind = Cast->getCastKind();
7413 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7414 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007415 return NoParens;
7416
7417 auto *SubExpr = Cast->getSubExpr();
7418 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7419 return NoParens;
7420 return ignorePointerCastsAndParens(SubExpr);
7421}
7422
George Burgess IVa51c4072015-10-16 01:49:01 +00007423/// Checks to see if the given LValue's Designator is at the end of the LValue's
7424/// record layout. e.g.
7425/// struct { struct { int a, b; } fst, snd; } obj;
7426/// obj.fst // no
7427/// obj.snd // yes
7428/// obj.fst.a // no
7429/// obj.fst.b // no
7430/// obj.snd.a // no
7431/// obj.snd.b // yes
7432///
7433/// Please note: this function is specialized for how __builtin_object_size
7434/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007435///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007436/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7437/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007438static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7439 assert(!LVal.Designator.Invalid);
7440
George Burgess IV4168d752016-06-27 19:40:41 +00007441 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7442 const RecordDecl *Parent = FD->getParent();
7443 Invalid = Parent->isInvalidDecl();
7444 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007445 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007446 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007447 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7448 };
7449
7450 auto &Base = LVal.getLValueBase();
7451 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7452 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007453 bool Invalid;
7454 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7455 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007456 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007457 for (auto *FD : IFD->chain()) {
7458 bool Invalid;
7459 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7460 return Invalid;
7461 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007462 }
7463 }
7464
George Burgess IVe3763372016-12-22 02:50:20 +00007465 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007466 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007467 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007468 // If we don't know the array bound, conservatively assume we're looking at
7469 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007470 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007471 if (BaseType->isIncompleteArrayType())
7472 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7473 else
7474 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007475 }
7476
7477 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7478 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007479 if (BaseType->isArrayType()) {
7480 // Because __builtin_object_size treats arrays as objects, we can ignore
7481 // the index iff this is the last array in the Designator.
7482 if (I + 1 == E)
7483 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007484 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7485 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007486 if (Index + 1 != CAT->getSize())
7487 return false;
7488 BaseType = CAT->getElementType();
7489 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007490 const auto *CT = BaseType->castAs<ComplexType>();
7491 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007492 if (Index != 1)
7493 return false;
7494 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007495 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007496 bool Invalid;
7497 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7498 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007499 BaseType = FD->getType();
7500 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007501 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007502 return false;
7503 }
7504 }
7505 return true;
7506}
7507
George Burgess IVe3763372016-12-22 02:50:20 +00007508/// Tests to see if the LValue has a user-specified designator (that isn't
7509/// necessarily valid). Note that this always returns 'true' if the LValue has
7510/// an unsized array as its first designator entry, because there's currently no
7511/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007512static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007513 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007514 return false;
7515
George Burgess IVe3763372016-12-22 02:50:20 +00007516 if (!LVal.Designator.Entries.empty())
7517 return LVal.Designator.isMostDerivedAnUnsizedArray();
7518
George Burgess IVa51c4072015-10-16 01:49:01 +00007519 if (!LVal.InvalidBase)
7520 return true;
7521
George Burgess IVe3763372016-12-22 02:50:20 +00007522 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7523 // the LValueBase.
7524 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7525 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007526}
7527
George Burgess IVe3763372016-12-22 02:50:20 +00007528/// Attempts to detect a user writing into a piece of memory that's impossible
7529/// to figure out the size of by just using types.
7530static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7531 const SubobjectDesignator &Designator = LVal.Designator;
7532 // Notes:
7533 // - Users can only write off of the end when we have an invalid base. Invalid
7534 // bases imply we don't know where the memory came from.
7535 // - We used to be a bit more aggressive here; we'd only be conservative if
7536 // the array at the end was flexible, or if it had 0 or 1 elements. This
7537 // broke some common standard library extensions (PR30346), but was
7538 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7539 // with some sort of whitelist. OTOH, it seems that GCC is always
7540 // conservative with the last element in structs (if it's an array), so our
7541 // current behavior is more compatible than a whitelisting approach would
7542 // be.
7543 return LVal.InvalidBase &&
7544 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7545 Designator.MostDerivedIsArrayElement &&
7546 isDesignatorAtObjectEnd(Ctx, LVal);
7547}
7548
7549/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7550/// Fails if the conversion would cause loss of precision.
7551static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7552 CharUnits &Result) {
7553 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7554 if (Int.ugt(CharUnitsMax))
7555 return false;
7556 Result = CharUnits::fromQuantity(Int.getZExtValue());
7557 return true;
7558}
7559
7560/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7561/// determine how many bytes exist from the beginning of the object to either
7562/// the end of the current subobject, or the end of the object itself, depending
7563/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007564///
George Burgess IVe3763372016-12-22 02:50:20 +00007565/// If this returns false, the value of Result is undefined.
7566static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7567 unsigned Type, const LValue &LVal,
7568 CharUnits &EndOffset) {
7569 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007570
George Burgess IV7fb7e362017-01-03 23:35:19 +00007571 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7572 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7573 return false;
7574 return HandleSizeof(Info, ExprLoc, Ty, Result);
7575 };
7576
George Burgess IVe3763372016-12-22 02:50:20 +00007577 // We want to evaluate the size of the entire object. This is a valid fallback
7578 // for when Type=1 and the designator is invalid, because we're asked for an
7579 // upper-bound.
7580 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7581 // Type=3 wants a lower bound, so we can't fall back to this.
7582 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007583 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007584
7585 llvm::APInt APEndOffset;
7586 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7587 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7588 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7589
7590 if (LVal.InvalidBase)
7591 return false;
7592
7593 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007594 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007595 }
7596
George Burgess IVe3763372016-12-22 02:50:20 +00007597 // We want to evaluate the size of a subobject.
7598 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007599
7600 // The following is a moderately common idiom in C:
7601 //
7602 // struct Foo { int a; char c[1]; };
7603 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7604 // strcpy(&F->c[0], Bar);
7605 //
George Burgess IVe3763372016-12-22 02:50:20 +00007606 // In order to not break too much legacy code, we need to support it.
7607 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7608 // If we can resolve this to an alloc_size call, we can hand that back,
7609 // because we know for certain how many bytes there are to write to.
7610 llvm::APInt APEndOffset;
7611 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7612 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7613 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7614
7615 // If we cannot determine the size of the initial allocation, then we can't
7616 // given an accurate upper-bound. However, we are still able to give
7617 // conservative lower-bounds for Type=3.
7618 if (Type == 1)
7619 return false;
7620 }
7621
7622 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007623 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007624 return false;
7625
George Burgess IVe3763372016-12-22 02:50:20 +00007626 // According to the GCC documentation, we want the size of the subobject
7627 // denoted by the pointer. But that's not quite right -- what we actually
7628 // want is the size of the immediately-enclosing array, if there is one.
7629 int64_t ElemsRemaining;
7630 if (Designator.MostDerivedIsArrayElement &&
7631 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7632 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7633 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7634 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7635 } else {
7636 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7637 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007638
George Burgess IVe3763372016-12-22 02:50:20 +00007639 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7640 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007641}
7642
George Burgess IVe3763372016-12-22 02:50:20 +00007643/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7644/// returns true and stores the result in @p Size.
7645///
7646/// If @p WasError is non-null, this will report whether the failure to evaluate
7647/// is to be treated as an Error in IntExprEvaluator.
7648static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7649 EvalInfo &Info, uint64_t &Size) {
7650 // Determine the denoted object.
7651 LValue LVal;
7652 {
7653 // The operand of __builtin_object_size is never evaluated for side-effects.
7654 // If there are any, but we can determine the pointed-to object anyway, then
7655 // ignore the side-effects.
7656 SpeculativeEvaluationRAII SpeculativeEval(Info);
7657 FoldOffsetRAII Fold(Info);
7658
7659 if (E->isGLValue()) {
7660 // It's possible for us to be given GLValues if we're called via
7661 // Expr::tryEvaluateObjectSize.
7662 APValue RVal;
7663 if (!EvaluateAsRValue(Info, E, RVal))
7664 return false;
7665 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007666 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7667 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007668 return false;
7669 }
7670
7671 // If we point to before the start of the object, there are no accessible
7672 // bytes.
7673 if (LVal.getLValueOffset().isNegative()) {
7674 Size = 0;
7675 return true;
7676 }
7677
7678 CharUnits EndOffset;
7679 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7680 return false;
7681
7682 // If we've fallen outside of the end offset, just pretend there's nothing to
7683 // write to/read from.
7684 if (EndOffset <= LVal.getLValueOffset())
7685 Size = 0;
7686 else
7687 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7688 return true;
John McCall95007602010-05-10 23:27:23 +00007689}
7690
Peter Collingbournee9200682011-05-13 03:29:01 +00007691bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007692 if (unsigned BuiltinOp = E->getBuiltinCallee())
7693 return VisitBuiltinCallExpr(E, BuiltinOp);
7694
7695 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7696}
7697
7698bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7699 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007700 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007701 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007702 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007703
7704 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007705 // The type was checked when we built the expression.
7706 unsigned Type =
7707 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7708 assert(Type <= 3 && "unexpected type");
7709
George Burgess IVe3763372016-12-22 02:50:20 +00007710 uint64_t Size;
7711 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7712 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007713
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007714 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007715 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007716
Richard Smith01ade172012-05-23 04:13:20 +00007717 // Expression had no side effects, but we couldn't statically determine the
7718 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007719 switch (Info.EvalMode) {
7720 case EvalInfo::EM_ConstantExpression:
7721 case EvalInfo::EM_PotentialConstantExpression:
7722 case EvalInfo::EM_ConstantFold:
7723 case EvalInfo::EM_EvaluateForOverflow:
7724 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007725 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007726 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007727 return Error(E);
7728 case EvalInfo::EM_ConstantExpressionUnevaluated:
7729 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007730 // Reduce it to a constant now.
7731 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007732 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007733
7734 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007735 }
7736
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007737 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007738 case Builtin::BI__builtin_bswap32:
7739 case Builtin::BI__builtin_bswap64: {
7740 APSInt Val;
7741 if (!EvaluateInteger(E->getArg(0), Val, Info))
7742 return false;
7743
7744 return Success(Val.byteSwap(), E);
7745 }
7746
Richard Smith8889a3d2013-06-13 06:26:32 +00007747 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007748 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007749
7750 // FIXME: BI__builtin_clrsb
7751 // FIXME: BI__builtin_clrsbl
7752 // FIXME: BI__builtin_clrsbll
7753
Richard Smith80b3c8e2013-06-13 05:04:16 +00007754 case Builtin::BI__builtin_clz:
7755 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007756 case Builtin::BI__builtin_clzll:
7757 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007758 APSInt Val;
7759 if (!EvaluateInteger(E->getArg(0), Val, Info))
7760 return false;
7761 if (!Val)
7762 return Error(E);
7763
7764 return Success(Val.countLeadingZeros(), E);
7765 }
7766
Richard Smith8889a3d2013-06-13 06:26:32 +00007767 case Builtin::BI__builtin_constant_p:
7768 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7769
Richard Smith80b3c8e2013-06-13 05:04:16 +00007770 case Builtin::BI__builtin_ctz:
7771 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007772 case Builtin::BI__builtin_ctzll:
7773 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007774 APSInt Val;
7775 if (!EvaluateInteger(E->getArg(0), Val, Info))
7776 return false;
7777 if (!Val)
7778 return Error(E);
7779
7780 return Success(Val.countTrailingZeros(), E);
7781 }
7782
Richard Smith8889a3d2013-06-13 06:26:32 +00007783 case Builtin::BI__builtin_eh_return_data_regno: {
7784 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7785 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7786 return Success(Operand, E);
7787 }
7788
7789 case Builtin::BI__builtin_expect:
7790 return Visit(E->getArg(0));
7791
7792 case Builtin::BI__builtin_ffs:
7793 case Builtin::BI__builtin_ffsl:
7794 case Builtin::BI__builtin_ffsll: {
7795 APSInt Val;
7796 if (!EvaluateInteger(E->getArg(0), Val, Info))
7797 return false;
7798
7799 unsigned N = Val.countTrailingZeros();
7800 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7801 }
7802
7803 case Builtin::BI__builtin_fpclassify: {
7804 APFloat Val(0.0);
7805 if (!EvaluateFloat(E->getArg(5), Val, Info))
7806 return false;
7807 unsigned Arg;
7808 switch (Val.getCategory()) {
7809 case APFloat::fcNaN: Arg = 0; break;
7810 case APFloat::fcInfinity: Arg = 1; break;
7811 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7812 case APFloat::fcZero: Arg = 4; break;
7813 }
7814 return Visit(E->getArg(Arg));
7815 }
7816
7817 case Builtin::BI__builtin_isinf_sign: {
7818 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007819 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007820 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7821 }
7822
Richard Smithea3019d2013-10-15 19:07:14 +00007823 case Builtin::BI__builtin_isinf: {
7824 APFloat Val(0.0);
7825 return EvaluateFloat(E->getArg(0), Val, Info) &&
7826 Success(Val.isInfinity() ? 1 : 0, E);
7827 }
7828
7829 case Builtin::BI__builtin_isfinite: {
7830 APFloat Val(0.0);
7831 return EvaluateFloat(E->getArg(0), Val, Info) &&
7832 Success(Val.isFinite() ? 1 : 0, E);
7833 }
7834
7835 case Builtin::BI__builtin_isnan: {
7836 APFloat Val(0.0);
7837 return EvaluateFloat(E->getArg(0), Val, Info) &&
7838 Success(Val.isNaN() ? 1 : 0, E);
7839 }
7840
7841 case Builtin::BI__builtin_isnormal: {
7842 APFloat Val(0.0);
7843 return EvaluateFloat(E->getArg(0), Val, Info) &&
7844 Success(Val.isNormal() ? 1 : 0, E);
7845 }
7846
Richard Smith8889a3d2013-06-13 06:26:32 +00007847 case Builtin::BI__builtin_parity:
7848 case Builtin::BI__builtin_parityl:
7849 case Builtin::BI__builtin_parityll: {
7850 APSInt Val;
7851 if (!EvaluateInteger(E->getArg(0), Val, Info))
7852 return false;
7853
7854 return Success(Val.countPopulation() % 2, E);
7855 }
7856
Richard Smith80b3c8e2013-06-13 05:04:16 +00007857 case Builtin::BI__builtin_popcount:
7858 case Builtin::BI__builtin_popcountl:
7859 case Builtin::BI__builtin_popcountll: {
7860 APSInt Val;
7861 if (!EvaluateInteger(E->getArg(0), Val, Info))
7862 return false;
7863
7864 return Success(Val.countPopulation(), E);
7865 }
7866
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007867 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007868 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007869 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007870 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007871 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007872 << /*isConstexpr*/0 << /*isConstructor*/0
7873 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007874 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007875 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007876 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007877 case Builtin::BI__builtin_strlen:
7878 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007879 // As an extension, we support __builtin_strlen() as a constant expression,
7880 // and support folding strlen() to a constant.
7881 LValue String;
7882 if (!EvaluatePointer(E->getArg(0), String, Info))
7883 return false;
7884
Richard Smith8110c9d2016-11-29 19:45:17 +00007885 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7886
Richard Smithe6c19f22013-11-15 02:10:04 +00007887 // Fast path: if it's a string literal, search the string value.
7888 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7889 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007890 // The string literal may have embedded null characters. Find the first
7891 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007892 StringRef Str = S->getBytes();
7893 int64_t Off = String.Offset.getQuantity();
7894 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007895 S->getCharByteWidth() == 1 &&
7896 // FIXME: Add fast-path for wchar_t too.
7897 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007898 Str = Str.substr(Off);
7899
7900 StringRef::size_type Pos = Str.find(0);
7901 if (Pos != StringRef::npos)
7902 Str = Str.substr(0, Pos);
7903
7904 return Success(Str.size(), E);
7905 }
7906
7907 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007908 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007909
7910 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007911 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7912 APValue Char;
7913 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7914 !Char.isInt())
7915 return false;
7916 if (!Char.getInt())
7917 return Success(Strlen, E);
7918 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7919 return false;
7920 }
7921 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007922
Richard Smithe151bab2016-11-11 23:43:35 +00007923 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007924 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007925 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007926 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007927 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007928 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007929 // A call to strlen is not a constant expression.
7930 if (Info.getLangOpts().CPlusPlus11)
7931 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7932 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007933 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007934 else
7935 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007936 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00007937 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007938 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007939 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007940 case Builtin::BI__builtin_wcsncmp:
7941 case Builtin::BI__builtin_memcmp:
7942 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007943 LValue String1, String2;
7944 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7945 !EvaluatePointer(E->getArg(1), String2, Info))
7946 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007947
7948 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7949
Richard Smithe151bab2016-11-11 23:43:35 +00007950 uint64_t MaxLength = uint64_t(-1);
7951 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007952 BuiltinOp != Builtin::BIwcscmp &&
7953 BuiltinOp != Builtin::BI__builtin_strcmp &&
7954 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007955 APSInt N;
7956 if (!EvaluateInteger(E->getArg(2), N, Info))
7957 return false;
7958 MaxLength = N.getExtValue();
7959 }
7960 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007961 BuiltinOp != Builtin::BIwmemcmp &&
7962 BuiltinOp != Builtin::BI__builtin_memcmp &&
7963 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007964 for (; MaxLength; --MaxLength) {
7965 APValue Char1, Char2;
7966 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7967 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7968 !Char1.isInt() || !Char2.isInt())
7969 return false;
7970 if (Char1.getInt() != Char2.getInt())
7971 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7972 if (StopAtNull && !Char1.getInt())
7973 return Success(0, E);
7974 assert(!(StopAtNull && !Char2.getInt()));
7975 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7976 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7977 return false;
7978 }
7979 // We hit the strncmp / memcmp limit.
7980 return Success(0, E);
7981 }
7982
Richard Smith01ba47d2012-04-13 00:45:38 +00007983 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007984 case Builtin::BI__atomic_is_lock_free:
7985 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007986 APSInt SizeVal;
7987 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7988 return false;
7989
7990 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7991 // of two less than the maximum inline atomic width, we know it is
7992 // lock-free. If the size isn't a power of two, or greater than the
7993 // maximum alignment where we promote atomics, we know it is not lock-free
7994 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7995 // the answer can only be determined at runtime; for example, 16-byte
7996 // atomics have lock-free implementations on some, but not all,
7997 // x86-64 processors.
7998
7999 // Check power-of-two.
8000 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00008001 if (Size.isPowerOfTwo()) {
8002 // Check against inlining width.
8003 unsigned InlineWidthBits =
8004 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8005 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8006 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8007 Size == CharUnits::One() ||
8008 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8009 Expr::NPC_NeverValueDependent))
8010 // OK, we will inline appropriately-aligned operations of this size,
8011 // and _Atomic(T) is appropriately-aligned.
8012 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008013
Richard Smith01ba47d2012-04-13 00:45:38 +00008014 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8015 castAs<PointerType>()->getPointeeType();
8016 if (!PointeeType->isIncompleteType() &&
8017 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8018 // OK, we will inline operations on this object.
8019 return Success(1, E);
8020 }
8021 }
8022 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008023
Richard Smith01ba47d2012-04-13 00:45:38 +00008024 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8025 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008026 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008027 case Builtin::BIomp_is_initial_device:
8028 // We can decide statically which value the runtime would return if called.
8029 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008030 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008031}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008032
Richard Smith8b3497e2011-10-31 01:37:14 +00008033static bool HasSameBase(const LValue &A, const LValue &B) {
8034 if (!A.getLValueBase())
8035 return !B.getLValueBase();
8036 if (!B.getLValueBase())
8037 return false;
8038
Richard Smithce40ad62011-11-12 22:28:03 +00008039 if (A.getLValueBase().getOpaqueValue() !=
8040 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008041 const Decl *ADecl = GetLValueBaseDecl(A);
8042 if (!ADecl)
8043 return false;
8044 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00008045 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00008046 return false;
8047 }
8048
8049 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00008050 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00008051}
8052
Richard Smithd20f1e62014-10-21 23:01:04 +00008053/// \brief Determine whether this is a pointer past the end of the complete
8054/// object referred to by the lvalue.
8055static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8056 const LValue &LV) {
8057 // A null pointer can be viewed as being "past the end" but we don't
8058 // choose to look at it that way here.
8059 if (!LV.getLValueBase())
8060 return false;
8061
8062 // If the designator is valid and refers to a subobject, we're not pointing
8063 // past the end.
8064 if (!LV.getLValueDesignator().Invalid &&
8065 !LV.getLValueDesignator().isOnePastTheEnd())
8066 return false;
8067
David Majnemerc378ca52015-08-29 08:32:55 +00008068 // A pointer to an incomplete type might be past-the-end if the type's size is
8069 // zero. We cannot tell because the type is incomplete.
8070 QualType Ty = getType(LV.getLValueBase());
8071 if (Ty->isIncompleteType())
8072 return true;
8073
Richard Smithd20f1e62014-10-21 23:01:04 +00008074 // We're a past-the-end pointer if we point to the byte after the object,
8075 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008076 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008077 return LV.getLValueOffset() == Size;
8078}
8079
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008080namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008081
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008082/// \brief Data recursive integer evaluator of certain binary operators.
8083///
8084/// We use a data recursive algorithm for binary operators so that we are able
8085/// to handle extreme cases of chained binary operators without causing stack
8086/// overflow.
8087class DataRecursiveIntBinOpEvaluator {
8088 struct EvalResult {
8089 APValue Val;
8090 bool Failed;
8091
8092 EvalResult() : Failed(false) { }
8093
8094 void swap(EvalResult &RHS) {
8095 Val.swap(RHS.Val);
8096 Failed = RHS.Failed;
8097 RHS.Failed = false;
8098 }
8099 };
8100
8101 struct Job {
8102 const Expr *E;
8103 EvalResult LHSResult; // meaningful only for binary operator expression.
8104 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008105
David Blaikie73726062015-08-12 23:09:24 +00008106 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008107 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008108
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008109 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008110 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008111 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008112
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008113 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008114 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008115 };
8116
8117 SmallVector<Job, 16> Queue;
8118
8119 IntExprEvaluator &IntEval;
8120 EvalInfo &Info;
8121 APValue &FinalResult;
8122
8123public:
8124 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8125 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8126
8127 /// \brief True if \param E is a binary operator that we are going to handle
8128 /// data recursively.
8129 /// We handle binary operators that are comma, logical, or that have operands
8130 /// with integral or enumeration type.
8131 static bool shouldEnqueue(const BinaryOperator *E) {
8132 return E->getOpcode() == BO_Comma ||
8133 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00008134 (E->isRValue() &&
8135 E->getType()->isIntegralOrEnumerationType() &&
8136 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008137 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008138 }
8139
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008140 bool Traverse(const BinaryOperator *E) {
8141 enqueue(E);
8142 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008143 while (!Queue.empty())
8144 process(PrevResult);
8145
8146 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008147
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008148 FinalResult.swap(PrevResult.Val);
8149 return true;
8150 }
8151
8152private:
8153 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8154 return IntEval.Success(Value, E, Result);
8155 }
8156 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8157 return IntEval.Success(Value, E, Result);
8158 }
8159 bool Error(const Expr *E) {
8160 return IntEval.Error(E);
8161 }
8162 bool Error(const Expr *E, diag::kind D) {
8163 return IntEval.Error(E, D);
8164 }
8165
8166 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8167 return Info.CCEDiag(E, D);
8168 }
8169
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008170 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8171 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008172 bool &SuppressRHSDiags);
8173
8174 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8175 const BinaryOperator *E, APValue &Result);
8176
8177 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8178 Result.Failed = !Evaluate(Result.Val, Info, E);
8179 if (Result.Failed)
8180 Result.Val = APValue();
8181 }
8182
Richard Trieuba4d0872012-03-21 23:30:30 +00008183 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008184
8185 void enqueue(const Expr *E) {
8186 E = E->IgnoreParens();
8187 Queue.resize(Queue.size()+1);
8188 Queue.back().E = E;
8189 Queue.back().Kind = Job::AnyExprKind;
8190 }
8191};
8192
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008193}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008194
8195bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008196 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008197 bool &SuppressRHSDiags) {
8198 if (E->getOpcode() == BO_Comma) {
8199 // Ignore LHS but note if we could not evaluate it.
8200 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008201 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008202 return true;
8203 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008204
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008205 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008206 bool LHSAsBool;
8207 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008208 // We were able to evaluate the LHS, see if we can get away with not
8209 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008210 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8211 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008212 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008213 }
8214 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008215 LHSResult.Failed = true;
8216
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008217 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008218 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008219 if (!Info.noteSideEffect())
8220 return false;
8221
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008222 // We can't evaluate the LHS; however, sometimes the result
8223 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8224 // Don't ignore RHS and suppress diagnostics from this arm.
8225 SuppressRHSDiags = true;
8226 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008227
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008228 return true;
8229 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008230
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008231 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8232 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008233
George Burgess IVa145e252016-05-25 22:38:36 +00008234 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008235 return false; // Ignore RHS;
8236
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008237 return true;
8238}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008239
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008240static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8241 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008242 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8243 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8244 // offsets.
8245 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8246 CharUnits &Offset = LVal.getLValueOffset();
8247 uint64_t Offset64 = Offset.getQuantity();
8248 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8249 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8250 : Offset64 + Index64);
8251}
8252
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008253bool DataRecursiveIntBinOpEvaluator::
8254 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8255 const BinaryOperator *E, APValue &Result) {
8256 if (E->getOpcode() == BO_Comma) {
8257 if (RHSResult.Failed)
8258 return false;
8259 Result = RHSResult.Val;
8260 return true;
8261 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008262
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008263 if (E->isLogicalOp()) {
8264 bool lhsResult, rhsResult;
8265 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8266 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008267
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008268 if (LHSIsOK) {
8269 if (RHSIsOK) {
8270 if (E->getOpcode() == BO_LOr)
8271 return Success(lhsResult || rhsResult, E, Result);
8272 else
8273 return Success(lhsResult && rhsResult, E, Result);
8274 }
8275 } else {
8276 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008277 // We can't evaluate the LHS; however, sometimes the result
8278 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8279 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008280 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008281 }
8282 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008283
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008284 return false;
8285 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008286
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008287 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8288 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008289
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008290 if (LHSResult.Failed || RHSResult.Failed)
8291 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008292
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008293 const APValue &LHSVal = LHSResult.Val;
8294 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008295
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008296 // Handle cases like (unsigned long)&a + 4.
8297 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8298 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008299 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008300 return true;
8301 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008302
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008303 // Handle cases like 4 + (unsigned long)&a
8304 if (E->getOpcode() == BO_Add &&
8305 RHSVal.isLValue() && LHSVal.isInt()) {
8306 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008307 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008308 return true;
8309 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008310
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008311 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8312 // Handle (intptr_t)&&A - (intptr_t)&&B.
8313 if (!LHSVal.getLValueOffset().isZero() ||
8314 !RHSVal.getLValueOffset().isZero())
8315 return false;
8316 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8317 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8318 if (!LHSExpr || !RHSExpr)
8319 return false;
8320 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8321 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8322 if (!LHSAddrExpr || !RHSAddrExpr)
8323 return false;
8324 // Make sure both labels come from the same function.
8325 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8326 RHSAddrExpr->getLabel()->getDeclContext())
8327 return false;
8328 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8329 return true;
8330 }
Richard Smith43e77732013-05-07 04:50:00 +00008331
8332 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008333 if (!LHSVal.isInt() || !RHSVal.isInt())
8334 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008335
8336 // Set up the width and signedness manually, in case it can't be deduced
8337 // from the operation we're performing.
8338 // FIXME: Don't do this in the cases where we can deduce it.
8339 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8340 E->getType()->isUnsignedIntegerOrEnumerationType());
8341 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8342 RHSVal.getInt(), Value))
8343 return false;
8344 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008345}
8346
Richard Trieuba4d0872012-03-21 23:30:30 +00008347void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008348 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008349
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008350 switch (job.Kind) {
8351 case Job::AnyExprKind: {
8352 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8353 if (shouldEnqueue(Bop)) {
8354 job.Kind = Job::BinOpKind;
8355 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008356 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008357 }
8358 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008359
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008360 EvaluateExpr(job.E, Result);
8361 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008362 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008363 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008364
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008365 case Job::BinOpKind: {
8366 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008367 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008368 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008369 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008370 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008371 }
8372 if (SuppressRHSDiags)
8373 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008374 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008375 job.Kind = Job::BinOpVisitedLHSKind;
8376 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008377 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008378 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008379
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008380 case Job::BinOpVisitedLHSKind: {
8381 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8382 EvalResult RHS;
8383 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008384 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008385 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008386 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008387 }
8388 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008389
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008390 llvm_unreachable("Invalid Job::Kind!");
8391}
8392
George Burgess IV8c892b52016-05-25 22:31:54 +00008393namespace {
8394/// Used when we determine that we should fail, but can keep evaluating prior to
8395/// noting that we had a failure.
8396class DelayedNoteFailureRAII {
8397 EvalInfo &Info;
8398 bool NoteFailure;
8399
8400public:
8401 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8402 : Info(Info), NoteFailure(NoteFailure) {}
8403 ~DelayedNoteFailureRAII() {
8404 if (NoteFailure) {
8405 bool ContinueAfterFailure = Info.noteFailure();
8406 (void)ContinueAfterFailure;
8407 assert(ContinueAfterFailure &&
8408 "Shouldn't have kept evaluating on failure.");
8409 }
8410 }
8411};
8412}
8413
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008414bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008415 // We don't call noteFailure immediately because the assignment happens after
8416 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008417 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008418 return Error(E);
8419
George Burgess IV8c892b52016-05-25 22:31:54 +00008420 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008421 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8422 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008423
Anders Carlssonacc79812008-11-16 07:17:21 +00008424 QualType LHSTy = E->getLHS()->getType();
8425 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008426
Chandler Carruthb29a7432014-10-11 11:03:30 +00008427 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008428 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008429 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008430 if (E->isAssignmentOp()) {
8431 LValue LV;
8432 EvaluateLValue(E->getLHS(), LV, Info);
8433 LHSOK = false;
8434 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008435 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8436 if (LHSOK) {
8437 LHS.makeComplexFloat();
8438 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8439 }
8440 } else {
8441 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8442 }
George Burgess IVa145e252016-05-25 22:38:36 +00008443 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008444 return false;
8445
Chandler Carruthb29a7432014-10-11 11:03:30 +00008446 if (E->getRHS()->getType()->isRealFloatingType()) {
8447 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8448 return false;
8449 RHS.makeComplexFloat();
8450 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8451 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008452 return false;
8453
8454 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008455 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008456 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008457 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008458 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8459
John McCalle3027922010-08-25 11:45:40 +00008460 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008461 return Success((CR_r == APFloat::cmpEqual &&
8462 CR_i == APFloat::cmpEqual), E);
8463 else {
John McCalle3027922010-08-25 11:45:40 +00008464 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008465 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008466 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008467 CR_r == APFloat::cmpLessThan ||
8468 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008469 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008470 CR_i == APFloat::cmpLessThan ||
8471 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008472 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008473 } else {
John McCalle3027922010-08-25 11:45:40 +00008474 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008475 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8476 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8477 else {
John McCalle3027922010-08-25 11:45:40 +00008478 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008479 "Invalid compex comparison.");
8480 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8481 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8482 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008483 }
8484 }
Mike Stump11289f42009-09-09 15:08:12 +00008485
Anders Carlssonacc79812008-11-16 07:17:21 +00008486 if (LHSTy->isRealFloatingType() &&
8487 RHSTy->isRealFloatingType()) {
8488 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008489
Richard Smith253c2a32012-01-27 01:14:48 +00008490 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008491 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008492 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008493
Richard Smith253c2a32012-01-27 01:14:48 +00008494 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008495 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008496
Anders Carlssonacc79812008-11-16 07:17:21 +00008497 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008498
Anders Carlssonacc79812008-11-16 07:17:21 +00008499 switch (E->getOpcode()) {
8500 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008501 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008502 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008503 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008504 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008505 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008506 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008507 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008508 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008509 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008510 E);
John McCalle3027922010-08-25 11:45:40 +00008511 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008512 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008513 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008514 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008515 || CR == APFloat::cmpLessThan
8516 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008517 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008518 }
Mike Stump11289f42009-09-09 15:08:12 +00008519
Eli Friedmana38da572009-04-28 19:17:36 +00008520 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008521 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008522 LValue LHSValue, RHSValue;
8523
8524 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008525 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008526 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008527
Richard Smith253c2a32012-01-27 01:14:48 +00008528 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008529 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008530
Richard Smith8b3497e2011-10-31 01:37:14 +00008531 // Reject differing bases from the normal codepath; we special-case
8532 // comparisons to null.
8533 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008534 if (E->getOpcode() == BO_Sub) {
8535 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008536 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008537 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008538 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008539 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008540 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008541 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008542 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8543 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8544 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008545 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008546 // Make sure both labels come from the same function.
8547 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8548 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008549 return Error(E);
8550 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008551 }
Richard Smith83c68212011-10-31 05:11:32 +00008552 // Inequalities and subtractions between unrelated pointers have
8553 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008554 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008555 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008556 // A constant address may compare equal to the address of a symbol.
8557 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008558 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008559 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8560 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008561 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008562 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008563 // distinct addresses. In clang, the result of such a comparison is
8564 // unspecified, so it is not a constant expression. However, we do know
8565 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008566 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8567 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008568 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008569 // We can't tell whether weak symbols will end up pointing to the same
8570 // object.
8571 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008572 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008573 // We can't compare the address of the start of one object with the
8574 // past-the-end address of another object, per C++ DR1652.
8575 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8576 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8577 (RHSValue.Base && RHSValue.Offset.isZero() &&
8578 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8579 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008580 // We can't tell whether an object is at the same address as another
8581 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008582 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8583 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008584 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008585 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008586 // (Note that clang defaults to -fmerge-all-constants, which can
8587 // lead to inconsistent results for comparisons involving the address
8588 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008589 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008590 }
Eli Friedman64004332009-03-23 04:38:34 +00008591
Richard Smith1b470412012-02-01 08:10:20 +00008592 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8593 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8594
Richard Smith84f6dcf2012-02-02 01:16:57 +00008595 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8596 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8597
John McCalle3027922010-08-25 11:45:40 +00008598 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008599 // C++11 [expr.add]p6:
8600 // Unless both pointers point to elements of the same array object, or
8601 // one past the last element of the array object, the behavior is
8602 // undefined.
8603 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8604 !AreElementsOfSameArray(getType(LHSValue.Base),
8605 LHSDesignator, RHSDesignator))
8606 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8607
Chris Lattner882bdf22010-04-20 17:13:14 +00008608 QualType Type = E->getLHS()->getType();
8609 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008610
Richard Smithd62306a2011-11-10 06:34:14 +00008611 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008612 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008613 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008614
Richard Smith84c6b3d2013-09-10 21:34:14 +00008615 // As an extension, a type may have zero size (empty struct or union in
8616 // C, array of zero length). Pointer subtraction in such cases has
8617 // undefined behavior, so is not constant.
8618 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008619 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008620 << ElementType;
8621 return false;
8622 }
8623
Richard Smith1b470412012-02-01 08:10:20 +00008624 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8625 // and produce incorrect results when it overflows. Such behavior
8626 // appears to be non-conforming, but is common, so perhaps we should
8627 // assume the standard intended for such cases to be undefined behavior
8628 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008629
Richard Smith1b470412012-02-01 08:10:20 +00008630 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8631 // overflow in the final conversion to ptrdiff_t.
8632 APSInt LHS(
8633 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8634 APSInt RHS(
8635 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8636 APSInt ElemSize(
8637 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8638 APSInt TrueResult = (LHS - RHS) / ElemSize;
8639 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8640
Richard Smith0c6124b2015-12-03 01:36:22 +00008641 if (Result.extend(65) != TrueResult &&
8642 !HandleOverflow(Info, E, TrueResult, E->getType()))
8643 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008644 return Success(Result, E);
8645 }
Richard Smithde21b242012-01-31 06:41:30 +00008646
8647 // C++11 [expr.rel]p3:
8648 // Pointers to void (after pointer conversions) can be compared, with a
8649 // result defined as follows: If both pointers represent the same
8650 // address or are both the null pointer value, the result is true if the
8651 // operator is <= or >= and false otherwise; otherwise the result is
8652 // unspecified.
8653 // We interpret this as applying to pointers to *cv* void.
8654 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008655 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008656 CCEDiag(E, diag::note_constexpr_void_comparison);
8657
Richard Smith84f6dcf2012-02-02 01:16:57 +00008658 // C++11 [expr.rel]p2:
8659 // - If two pointers point to non-static data members of the same object,
8660 // or to subobjects or array elements fo such members, recursively, the
8661 // pointer to the later declared member compares greater provided the
8662 // two members have the same access control and provided their class is
8663 // not a union.
8664 // [...]
8665 // - Otherwise pointer comparisons are unspecified.
8666 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8667 E->isRelationalOp()) {
8668 bool WasArrayIndex;
8669 unsigned Mismatch =
8670 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8671 RHSDesignator, WasArrayIndex);
8672 // At the point where the designators diverge, the comparison has a
8673 // specified value if:
8674 // - we are comparing array indices
8675 // - we are comparing fields of a union, or fields with the same access
8676 // Otherwise, the result is unspecified and thus the comparison is not a
8677 // constant expression.
8678 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8679 Mismatch < RHSDesignator.Entries.size()) {
8680 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8681 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8682 if (!LF && !RF)
8683 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8684 else if (!LF)
8685 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8686 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8687 << RF->getParent() << RF;
8688 else if (!RF)
8689 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8690 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8691 << LF->getParent() << LF;
8692 else if (!LF->getParent()->isUnion() &&
8693 LF->getAccess() != RF->getAccess())
8694 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8695 << LF << LF->getAccess() << RF << RF->getAccess()
8696 << LF->getParent();
8697 }
8698 }
8699
Eli Friedman6c31cb42012-04-16 04:30:08 +00008700 // The comparison here must be unsigned, and performed with the same
8701 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008702 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8703 uint64_t CompareLHS = LHSOffset.getQuantity();
8704 uint64_t CompareRHS = RHSOffset.getQuantity();
8705 assert(PtrSize <= 64 && "Unexpected pointer width");
8706 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8707 CompareLHS &= Mask;
8708 CompareRHS &= Mask;
8709
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008710 // If there is a base and this is a relational operator, we can only
8711 // compare pointers within the object in question; otherwise, the result
8712 // depends on where the object is located in memory.
8713 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8714 QualType BaseTy = getType(LHSValue.Base);
8715 if (BaseTy->isIncompleteType())
8716 return Error(E);
8717 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8718 uint64_t OffsetLimit = Size.getQuantity();
8719 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8720 return Error(E);
8721 }
8722
Richard Smith8b3497e2011-10-31 01:37:14 +00008723 switch (E->getOpcode()) {
8724 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008725 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8726 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8727 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8728 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8729 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8730 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008731 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008732 }
8733 }
Richard Smith7bb00672012-02-01 01:42:44 +00008734
8735 if (LHSTy->isMemberPointerType()) {
8736 assert(E->isEqualityOp() && "unexpected member pointer operation");
8737 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8738
8739 MemberPtr LHSValue, RHSValue;
8740
8741 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008742 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008743 return false;
8744
8745 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8746 return false;
8747
8748 // C++11 [expr.eq]p2:
8749 // If both operands are null, they compare equal. Otherwise if only one is
8750 // null, they compare unequal.
8751 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8752 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8753 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8754 }
8755
8756 // Otherwise if either is a pointer to a virtual member function, the
8757 // result is unspecified.
8758 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8759 if (MD->isVirtual())
8760 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8761 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8762 if (MD->isVirtual())
8763 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8764
8765 // Otherwise they compare equal if and only if they would refer to the
8766 // same member of the same most derived object or the same subobject if
8767 // they were dereferenced with a hypothetical object of the associated
8768 // class type.
8769 bool Equal = LHSValue == RHSValue;
8770 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8771 }
8772
Richard Smithab44d9b2012-02-14 22:35:28 +00008773 if (LHSTy->isNullPtrType()) {
8774 assert(E->isComparisonOp() && "unexpected nullptr operation");
8775 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8776 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8777 // are compared, the result is true of the operator is <=, >= or ==, and
8778 // false otherwise.
8779 BinaryOperator::Opcode Opcode = E->getOpcode();
8780 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8781 }
8782
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008783 assert((!LHSTy->isIntegralOrEnumerationType() ||
8784 !RHSTy->isIntegralOrEnumerationType()) &&
8785 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8786 // We can't continue from here for non-integral types.
8787 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008788}
8789
Peter Collingbournee190dee2011-03-11 19:24:49 +00008790/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8791/// a result as the expression's type.
8792bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8793 const UnaryExprOrTypeTraitExpr *E) {
8794 switch(E->getKind()) {
8795 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008796 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008797 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008798 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008799 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008800 }
Eli Friedman64004332009-03-23 04:38:34 +00008801
Peter Collingbournee190dee2011-03-11 19:24:49 +00008802 case UETT_VecStep: {
8803 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008804
Peter Collingbournee190dee2011-03-11 19:24:49 +00008805 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008806 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008807
Peter Collingbournee190dee2011-03-11 19:24:49 +00008808 // The vec_step built-in functions that take a 3-component
8809 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8810 if (n == 3)
8811 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008812
Peter Collingbournee190dee2011-03-11 19:24:49 +00008813 return Success(n, E);
8814 } else
8815 return Success(1, E);
8816 }
8817
8818 case UETT_SizeOf: {
8819 QualType SrcTy = E->getTypeOfArgument();
8820 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8821 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008822 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8823 SrcTy = Ref->getPointeeType();
8824
Richard Smithd62306a2011-11-10 06:34:14 +00008825 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008826 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008827 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008828 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008829 }
Alexey Bataev00396512015-07-02 03:40:19 +00008830 case UETT_OpenMPRequiredSimdAlign:
8831 assert(E->isArgumentType());
8832 return Success(
8833 Info.Ctx.toCharUnitsFromBits(
8834 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8835 .getQuantity(),
8836 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008837 }
8838
8839 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008840}
8841
Peter Collingbournee9200682011-05-13 03:29:01 +00008842bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008843 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008844 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008845 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008846 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008847 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008848 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008849 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008850 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008851 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008852 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008853 APSInt IdxResult;
8854 if (!EvaluateInteger(Idx, IdxResult, Info))
8855 return false;
8856 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8857 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008858 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008859 CurrentType = AT->getElementType();
8860 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8861 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008862 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008863 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008864
James Y Knight7281c352015-12-29 22:31:18 +00008865 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008866 FieldDecl *MemberDecl = ON.getField();
8867 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008868 if (!RT)
8869 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008870 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008871 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008872 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008873 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008874 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008875 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008876 CurrentType = MemberDecl->getType().getNonReferenceType();
8877 break;
8878 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008879
James Y Knight7281c352015-12-29 22:31:18 +00008880 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008881 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008882
James Y Knight7281c352015-12-29 22:31:18 +00008883 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008884 CXXBaseSpecifier *BaseSpec = ON.getBase();
8885 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008886 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008887
8888 // Find the layout of the class whose base we are looking into.
8889 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008890 if (!RT)
8891 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008892 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008893 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008894 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8895
8896 // Find the base class itself.
8897 CurrentType = BaseSpec->getType();
8898 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8899 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008900 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00008901
Douglas Gregord1702062010-04-29 00:18:15 +00008902 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008903 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008904 break;
8905 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008906 }
8907 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008908 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008909}
8910
Chris Lattnere13042c2008-07-11 19:10:17 +00008911bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008912 switch (E->getOpcode()) {
8913 default:
8914 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8915 // See C99 6.6p3.
8916 return Error(E);
8917 case UO_Extension:
8918 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8919 // If so, we could clear the diagnostic ID.
8920 return Visit(E->getSubExpr());
8921 case UO_Plus:
8922 // The result is just the value.
8923 return Visit(E->getSubExpr());
8924 case UO_Minus: {
8925 if (!Visit(E->getSubExpr()))
Aaron Ballmana5038552018-01-09 13:07:03 +00008926 return false;
8927 if (!Result.isInt()) return Error(E);
8928 const APSInt &Value = Result.getInt();
8929 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
8930 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8931 E->getType()))
8932 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008933 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008934 }
8935 case UO_Not: {
8936 if (!Visit(E->getSubExpr()))
8937 return false;
8938 if (!Result.isInt()) return Error(E);
8939 return Success(~Result.getInt(), E);
8940 }
8941 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008942 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008943 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008944 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008945 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008946 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008947 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008948}
Mike Stump11289f42009-09-09 15:08:12 +00008949
Chris Lattner477c4be2008-07-12 01:15:53 +00008950/// HandleCast - This is used to evaluate implicit or explicit casts where the
8951/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008952bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8953 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008954 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008955 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008956
Eli Friedmanc757de22011-03-25 00:43:55 +00008957 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008958 case CK_BaseToDerived:
8959 case CK_DerivedToBase:
8960 case CK_UncheckedDerivedToBase:
8961 case CK_Dynamic:
8962 case CK_ToUnion:
8963 case CK_ArrayToPointerDecay:
8964 case CK_FunctionToPointerDecay:
8965 case CK_NullToPointer:
8966 case CK_NullToMemberPointer:
8967 case CK_BaseToDerivedMemberPointer:
8968 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008969 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008970 case CK_ConstructorConversion:
8971 case CK_IntegralToPointer:
8972 case CK_ToVoid:
8973 case CK_VectorSplat:
8974 case CK_IntegralToFloating:
8975 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008976 case CK_CPointerToObjCPointerCast:
8977 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008978 case CK_AnyPointerToBlockPointerCast:
8979 case CK_ObjCObjectLValueCast:
8980 case CK_FloatingRealToComplex:
8981 case CK_FloatingComplexToReal:
8982 case CK_FloatingComplexCast:
8983 case CK_FloatingComplexToIntegralComplex:
8984 case CK_IntegralRealToComplex:
8985 case CK_IntegralComplexCast:
8986 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008987 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008988 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008989 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008990 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008991 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008992 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008993 llvm_unreachable("invalid cast kind for integral value");
8994
Eli Friedman9faf2f92011-03-25 19:07:11 +00008995 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008996 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008997 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008998 case CK_ARCProduceObject:
8999 case CK_ARCConsumeObject:
9000 case CK_ARCReclaimReturnedObject:
9001 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009002 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009003 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009004
Richard Smith4ef685b2012-01-17 21:17:26 +00009005 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00009006 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009007 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009008 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009009 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009010
9011 case CK_MemberPointerToBoolean:
9012 case CK_PointerToBoolean:
9013 case CK_IntegralToBoolean:
9014 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009015 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009016 case CK_FloatingComplexToBoolean:
9017 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009018 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009019 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009020 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009021 uint64_t IntResult = BoolResult;
9022 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9023 IntResult = (uint64_t)-1;
9024 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009025 }
9026
Eli Friedmanc757de22011-03-25 00:43:55 +00009027 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009028 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009029 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009030
Eli Friedman742421e2009-02-20 01:15:07 +00009031 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009032 // Allow casts of address-of-label differences if they are no-ops
9033 // or narrowing. (The narrowing case isn't actually guaranteed to
9034 // be constant-evaluatable except in some narrow cases which are hard
9035 // to detect here. We let it through on the assumption the user knows
9036 // what they are doing.)
9037 if (Result.isAddrLabelDiff())
9038 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009039 // Only allow casts of lvalues if they are lossless.
9040 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9041 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009042
Richard Smith911e1422012-01-30 22:27:01 +00009043 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9044 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009045 }
Mike Stump11289f42009-09-09 15:08:12 +00009046
Eli Friedmanc757de22011-03-25 00:43:55 +00009047 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009048 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9049
John McCall45d55e42010-05-07 21:00:08 +00009050 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009051 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009052 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009053
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009054 if (LV.getLValueBase()) {
9055 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009056 // FIXME: Allow a larger integer size than the pointer size, and allow
9057 // narrowing back down to pointer width in subsequent integral casts.
9058 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009059 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009060 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009061
Richard Smithcf74da72011-11-16 07:18:12 +00009062 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009063 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009064 return true;
9065 }
9066
Yaxun Liu402804b2016-12-15 08:09:08 +00009067 uint64_t V;
9068 if (LV.isNullPointer())
9069 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9070 else
9071 V = LV.getLValueOffset().getQuantity();
9072
9073 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009074 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009075 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009076
Eli Friedmanc757de22011-03-25 00:43:55 +00009077 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009078 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009079 if (!EvaluateComplex(SubExpr, C, Info))
9080 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009081 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009082 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009083
Eli Friedmanc757de22011-03-25 00:43:55 +00009084 case CK_FloatingToIntegral: {
9085 APFloat F(0.0);
9086 if (!EvaluateFloat(SubExpr, F, Info))
9087 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009088
Richard Smith357362d2011-12-13 06:39:58 +00009089 APSInt Value;
9090 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9091 return false;
9092 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009093 }
9094 }
Mike Stump11289f42009-09-09 15:08:12 +00009095
Eli Friedmanc757de22011-03-25 00:43:55 +00009096 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009097}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009098
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009099bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9100 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009101 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009102 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9103 return false;
9104 if (!LV.isComplexInt())
9105 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009106 return Success(LV.getComplexIntReal(), E);
9107 }
9108
9109 return Visit(E->getSubExpr());
9110}
9111
Eli Friedman4e7a2412009-02-27 04:45:43 +00009112bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009113 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009114 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009115 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9116 return false;
9117 if (!LV.isComplexInt())
9118 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009119 return Success(LV.getComplexIntImag(), E);
9120 }
9121
Richard Smith4a678122011-10-24 18:44:57 +00009122 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009123 return Success(0, E);
9124}
9125
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009126bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9127 return Success(E->getPackLength(), E);
9128}
9129
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009130bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9131 return Success(E->getValue(), E);
9132}
9133
Chris Lattner05706e882008-07-11 18:11:29 +00009134//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009135// Float Evaluation
9136//===----------------------------------------------------------------------===//
9137
9138namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009139class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009140 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009141 APFloat &Result;
9142public:
9143 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009144 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009145
Richard Smith2e312c82012-03-03 22:46:17 +00009146 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009147 Result = V.getFloat();
9148 return true;
9149 }
Eli Friedman24c01542008-08-22 00:06:13 +00009150
Richard Smithfddd3842011-12-30 21:15:51 +00009151 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009152 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9153 return true;
9154 }
9155
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009156 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009157
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009158 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009159 bool VisitBinaryOperator(const BinaryOperator *E);
9160 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009161 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009162
John McCallb1fb0d32010-05-07 22:08:54 +00009163 bool VisitUnaryReal(const UnaryOperator *E);
9164 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009165
Richard Smithfddd3842011-12-30 21:15:51 +00009166 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009167};
9168} // end anonymous namespace
9169
9170static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009171 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009172 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009173}
9174
Jay Foad39c79802011-01-12 09:06:06 +00009175static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009176 QualType ResultTy,
9177 const Expr *Arg,
9178 bool SNaN,
9179 llvm::APFloat &Result) {
9180 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9181 if (!S) return false;
9182
9183 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9184
9185 llvm::APInt fill;
9186
9187 // Treat empty strings as if they were zero.
9188 if (S->getString().empty())
9189 fill = llvm::APInt(32, 0);
9190 else if (S->getString().getAsInteger(0, fill))
9191 return false;
9192
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009193 if (Context.getTargetInfo().isNan2008()) {
9194 if (SNaN)
9195 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9196 else
9197 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9198 } else {
9199 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9200 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9201 // a different encoding to what became a standard in 2008, and for pre-
9202 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9203 // sNaN. This is now known as "legacy NaN" encoding.
9204 if (SNaN)
9205 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9206 else
9207 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9208 }
9209
John McCall16291492010-02-28 13:00:19 +00009210 return true;
9211}
9212
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009213bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009214 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009215 default:
9216 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9217
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009218 case Builtin::BI__builtin_huge_val:
9219 case Builtin::BI__builtin_huge_valf:
9220 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009221 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009222 case Builtin::BI__builtin_inf:
9223 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009224 case Builtin::BI__builtin_infl:
9225 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009226 const llvm::fltSemantics &Sem =
9227 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009228 Result = llvm::APFloat::getInf(Sem);
9229 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009230 }
Mike Stump11289f42009-09-09 15:08:12 +00009231
John McCall16291492010-02-28 13:00:19 +00009232 case Builtin::BI__builtin_nans:
9233 case Builtin::BI__builtin_nansf:
9234 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009235 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009236 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9237 true, Result))
9238 return Error(E);
9239 return true;
John McCall16291492010-02-28 13:00:19 +00009240
Chris Lattner0b7282e2008-10-06 06:31:58 +00009241 case Builtin::BI__builtin_nan:
9242 case Builtin::BI__builtin_nanf:
9243 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009244 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +00009245 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009246 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009247 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9248 false, Result))
9249 return Error(E);
9250 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009251
9252 case Builtin::BI__builtin_fabs:
9253 case Builtin::BI__builtin_fabsf:
9254 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009255 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009256 if (!EvaluateFloat(E->getArg(0), Result, Info))
9257 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009258
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009259 if (Result.isNegative())
9260 Result.changeSign();
9261 return true;
9262
Richard Smith8889a3d2013-06-13 06:26:32 +00009263 // FIXME: Builtin::BI__builtin_powi
9264 // FIXME: Builtin::BI__builtin_powif
9265 // FIXME: Builtin::BI__builtin_powil
9266
Mike Stump11289f42009-09-09 15:08:12 +00009267 case Builtin::BI__builtin_copysign:
9268 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009269 case Builtin::BI__builtin_copysignl:
9270 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009271 APFloat RHS(0.);
9272 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9273 !EvaluateFloat(E->getArg(1), RHS, Info))
9274 return false;
9275 Result.copySign(RHS);
9276 return true;
9277 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009278 }
9279}
9280
John McCallb1fb0d32010-05-07 22:08:54 +00009281bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009282 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9283 ComplexValue CV;
9284 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9285 return false;
9286 Result = CV.FloatReal;
9287 return true;
9288 }
9289
9290 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009291}
9292
9293bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009294 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9295 ComplexValue CV;
9296 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9297 return false;
9298 Result = CV.FloatImag;
9299 return true;
9300 }
9301
Richard Smith4a678122011-10-24 18:44:57 +00009302 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009303 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9304 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009305 return true;
9306}
9307
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009308bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009309 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009310 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009311 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009312 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009313 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009314 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9315 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009316 Result.changeSign();
9317 return true;
9318 }
9319}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009320
Eli Friedman24c01542008-08-22 00:06:13 +00009321bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009322 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9323 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009324
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009325 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009326 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009327 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009328 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009329 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9330 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009331}
9332
9333bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9334 Result = E->getValue();
9335 return true;
9336}
9337
Peter Collingbournee9200682011-05-13 03:29:01 +00009338bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9339 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009340
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009341 switch (E->getCastKind()) {
9342 default:
Richard Smith11562c52011-10-28 17:51:58 +00009343 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009344
9345 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009346 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009347 return EvaluateInteger(SubExpr, IntResult, Info) &&
9348 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9349 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009350 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009351
9352 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009353 if (!Visit(SubExpr))
9354 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009355 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9356 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009357 }
John McCalld7646252010-11-14 08:17:51 +00009358
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009359 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009360 ComplexValue V;
9361 if (!EvaluateComplex(SubExpr, V, Info))
9362 return false;
9363 Result = V.getComplexFloatReal();
9364 return true;
9365 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009366 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009367}
9368
Eli Friedman24c01542008-08-22 00:06:13 +00009369//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009370// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009371//===----------------------------------------------------------------------===//
9372
9373namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009374class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009375 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009376 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009377
Anders Carlsson537969c2008-11-16 20:27:53 +00009378public:
John McCall93d91dc2010-05-07 17:22:02 +00009379 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009380 : ExprEvaluatorBaseTy(info), Result(Result) {}
9381
Richard Smith2e312c82012-03-03 22:46:17 +00009382 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009383 Result.setFrom(V);
9384 return true;
9385 }
Mike Stump11289f42009-09-09 15:08:12 +00009386
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009387 bool ZeroInitialization(const Expr *E);
9388
Anders Carlsson537969c2008-11-16 20:27:53 +00009389 //===--------------------------------------------------------------------===//
9390 // Visitor Methods
9391 //===--------------------------------------------------------------------===//
9392
Peter Collingbournee9200682011-05-13 03:29:01 +00009393 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009394 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009395 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009396 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009397 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009398};
9399} // end anonymous namespace
9400
John McCall93d91dc2010-05-07 17:22:02 +00009401static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9402 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009403 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009404 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009405}
9406
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009407bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009408 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009409 if (ElemTy->isRealFloatingType()) {
9410 Result.makeComplexFloat();
9411 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9412 Result.FloatReal = Zero;
9413 Result.FloatImag = Zero;
9414 } else {
9415 Result.makeComplexInt();
9416 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9417 Result.IntReal = Zero;
9418 Result.IntImag = Zero;
9419 }
9420 return true;
9421}
9422
Peter Collingbournee9200682011-05-13 03:29:01 +00009423bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9424 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009425
9426 if (SubExpr->getType()->isRealFloatingType()) {
9427 Result.makeComplexFloat();
9428 APFloat &Imag = Result.FloatImag;
9429 if (!EvaluateFloat(SubExpr, Imag, Info))
9430 return false;
9431
9432 Result.FloatReal = APFloat(Imag.getSemantics());
9433 return true;
9434 } else {
9435 assert(SubExpr->getType()->isIntegerType() &&
9436 "Unexpected imaginary literal.");
9437
9438 Result.makeComplexInt();
9439 APSInt &Imag = Result.IntImag;
9440 if (!EvaluateInteger(SubExpr, Imag, Info))
9441 return false;
9442
9443 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9444 return true;
9445 }
9446}
9447
Peter Collingbournee9200682011-05-13 03:29:01 +00009448bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009449
John McCallfcef3cf2010-12-14 17:51:41 +00009450 switch (E->getCastKind()) {
9451 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009452 case CK_BaseToDerived:
9453 case CK_DerivedToBase:
9454 case CK_UncheckedDerivedToBase:
9455 case CK_Dynamic:
9456 case CK_ToUnion:
9457 case CK_ArrayToPointerDecay:
9458 case CK_FunctionToPointerDecay:
9459 case CK_NullToPointer:
9460 case CK_NullToMemberPointer:
9461 case CK_BaseToDerivedMemberPointer:
9462 case CK_DerivedToBaseMemberPointer:
9463 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009464 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009465 case CK_ConstructorConversion:
9466 case CK_IntegralToPointer:
9467 case CK_PointerToIntegral:
9468 case CK_PointerToBoolean:
9469 case CK_ToVoid:
9470 case CK_VectorSplat:
9471 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009472 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009473 case CK_IntegralToBoolean:
9474 case CK_IntegralToFloating:
9475 case CK_FloatingToIntegral:
9476 case CK_FloatingToBoolean:
9477 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009478 case CK_CPointerToObjCPointerCast:
9479 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009480 case CK_AnyPointerToBlockPointerCast:
9481 case CK_ObjCObjectLValueCast:
9482 case CK_FloatingComplexToReal:
9483 case CK_FloatingComplexToBoolean:
9484 case CK_IntegralComplexToReal:
9485 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009486 case CK_ARCProduceObject:
9487 case CK_ARCConsumeObject:
9488 case CK_ARCReclaimReturnedObject:
9489 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009490 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009491 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009492 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009493 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009494 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009495 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009496 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009497 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009498
John McCallfcef3cf2010-12-14 17:51:41 +00009499 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009500 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009501 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009502 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009503
9504 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009505 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009506 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009507 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009508
9509 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009510 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009511 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009512 return false;
9513
John McCallfcef3cf2010-12-14 17:51:41 +00009514 Result.makeComplexFloat();
9515 Result.FloatImag = APFloat(Real.getSemantics());
9516 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009517 }
9518
John McCallfcef3cf2010-12-14 17:51:41 +00009519 case CK_FloatingComplexCast: {
9520 if (!Visit(E->getSubExpr()))
9521 return false;
9522
9523 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9524 QualType From
9525 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9526
Richard Smith357362d2011-12-13 06:39:58 +00009527 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9528 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009529 }
9530
9531 case CK_FloatingComplexToIntegralComplex: {
9532 if (!Visit(E->getSubExpr()))
9533 return false;
9534
9535 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9536 QualType From
9537 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9538 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009539 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9540 To, Result.IntReal) &&
9541 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9542 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009543 }
9544
9545 case CK_IntegralRealToComplex: {
9546 APSInt &Real = Result.IntReal;
9547 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9548 return false;
9549
9550 Result.makeComplexInt();
9551 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9552 return true;
9553 }
9554
9555 case CK_IntegralComplexCast: {
9556 if (!Visit(E->getSubExpr()))
9557 return false;
9558
9559 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9560 QualType From
9561 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9562
Richard Smith911e1422012-01-30 22:27:01 +00009563 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9564 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009565 return true;
9566 }
9567
9568 case CK_IntegralComplexToFloatingComplex: {
9569 if (!Visit(E->getSubExpr()))
9570 return false;
9571
Ted Kremenek28831752012-08-23 20:46:57 +00009572 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009573 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009574 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009575 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009576 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9577 To, Result.FloatReal) &&
9578 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9579 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009580 }
9581 }
9582
9583 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009584}
9585
John McCall93d91dc2010-05-07 17:22:02 +00009586bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009587 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009588 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9589
Chandler Carrutha216cad2014-10-11 00:57:18 +00009590 // Track whether the LHS or RHS is real at the type system level. When this is
9591 // the case we can simplify our evaluation strategy.
9592 bool LHSReal = false, RHSReal = false;
9593
9594 bool LHSOK;
9595 if (E->getLHS()->getType()->isRealFloatingType()) {
9596 LHSReal = true;
9597 APFloat &Real = Result.FloatReal;
9598 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9599 if (LHSOK) {
9600 Result.makeComplexFloat();
9601 Result.FloatImag = APFloat(Real.getSemantics());
9602 }
9603 } else {
9604 LHSOK = Visit(E->getLHS());
9605 }
George Burgess IVa145e252016-05-25 22:38:36 +00009606 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009607 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009608
John McCall93d91dc2010-05-07 17:22:02 +00009609 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009610 if (E->getRHS()->getType()->isRealFloatingType()) {
9611 RHSReal = true;
9612 APFloat &Real = RHS.FloatReal;
9613 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9614 return false;
9615 RHS.makeComplexFloat();
9616 RHS.FloatImag = APFloat(Real.getSemantics());
9617 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009618 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009619
Chandler Carrutha216cad2014-10-11 00:57:18 +00009620 assert(!(LHSReal && RHSReal) &&
9621 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009622 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009623 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009624 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009625 if (Result.isComplexFloat()) {
9626 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9627 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009628 if (LHSReal)
9629 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9630 else if (!RHSReal)
9631 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9632 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009633 } else {
9634 Result.getComplexIntReal() += RHS.getComplexIntReal();
9635 Result.getComplexIntImag() += RHS.getComplexIntImag();
9636 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009637 break;
John McCalle3027922010-08-25 11:45:40 +00009638 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009639 if (Result.isComplexFloat()) {
9640 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9641 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009642 if (LHSReal) {
9643 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9644 Result.getComplexFloatImag().changeSign();
9645 } else if (!RHSReal) {
9646 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9647 APFloat::rmNearestTiesToEven);
9648 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009649 } else {
9650 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9651 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9652 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009653 break;
John McCalle3027922010-08-25 11:45:40 +00009654 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009655 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009656 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009657 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009658 // following naming scheme:
9659 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009660 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009661 APFloat &A = LHS.getComplexFloatReal();
9662 APFloat &B = LHS.getComplexFloatImag();
9663 APFloat &C = RHS.getComplexFloatReal();
9664 APFloat &D = RHS.getComplexFloatImag();
9665 APFloat &ResR = Result.getComplexFloatReal();
9666 APFloat &ResI = Result.getComplexFloatImag();
9667 if (LHSReal) {
9668 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9669 ResR = A * C;
9670 ResI = A * D;
9671 } else if (RHSReal) {
9672 ResR = C * A;
9673 ResI = C * B;
9674 } else {
9675 // In the fully general case, we need to handle NaNs and infinities
9676 // robustly.
9677 APFloat AC = A * C;
9678 APFloat BD = B * D;
9679 APFloat AD = A * D;
9680 APFloat BC = B * C;
9681 ResR = AC - BD;
9682 ResI = AD + BC;
9683 if (ResR.isNaN() && ResI.isNaN()) {
9684 bool Recalc = false;
9685 if (A.isInfinity() || B.isInfinity()) {
9686 A = APFloat::copySign(
9687 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9688 B = APFloat::copySign(
9689 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9690 if (C.isNaN())
9691 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9692 if (D.isNaN())
9693 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9694 Recalc = true;
9695 }
9696 if (C.isInfinity() || D.isInfinity()) {
9697 C = APFloat::copySign(
9698 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9699 D = APFloat::copySign(
9700 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9701 if (A.isNaN())
9702 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9703 if (B.isNaN())
9704 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9705 Recalc = true;
9706 }
9707 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9708 AD.isInfinity() || BC.isInfinity())) {
9709 if (A.isNaN())
9710 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9711 if (B.isNaN())
9712 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9713 if (C.isNaN())
9714 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9715 if (D.isNaN())
9716 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9717 Recalc = true;
9718 }
9719 if (Recalc) {
9720 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9721 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9722 }
9723 }
9724 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009725 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009726 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009727 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009728 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9729 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009730 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009731 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9732 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9733 }
9734 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009735 case BO_Div:
9736 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009737 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009738 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009739 // following naming scheme:
9740 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009741 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009742 APFloat &A = LHS.getComplexFloatReal();
9743 APFloat &B = LHS.getComplexFloatImag();
9744 APFloat &C = RHS.getComplexFloatReal();
9745 APFloat &D = RHS.getComplexFloatImag();
9746 APFloat &ResR = Result.getComplexFloatReal();
9747 APFloat &ResI = Result.getComplexFloatImag();
9748 if (RHSReal) {
9749 ResR = A / C;
9750 ResI = B / C;
9751 } else {
9752 if (LHSReal) {
9753 // No real optimizations we can do here, stub out with zero.
9754 B = APFloat::getZero(A.getSemantics());
9755 }
9756 int DenomLogB = 0;
9757 APFloat MaxCD = maxnum(abs(C), abs(D));
9758 if (MaxCD.isFinite()) {
9759 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009760 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9761 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009762 }
9763 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009764 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9765 APFloat::rmNearestTiesToEven);
9766 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9767 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009768 if (ResR.isNaN() && ResI.isNaN()) {
9769 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9770 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9771 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9772 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9773 D.isFinite()) {
9774 A = APFloat::copySign(
9775 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9776 B = APFloat::copySign(
9777 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9778 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9779 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9780 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9781 C = APFloat::copySign(
9782 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9783 D = APFloat::copySign(
9784 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9785 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9786 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9787 }
9788 }
9789 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009790 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009791 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9792 return Error(E, diag::note_expr_divide_by_zero);
9793
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009794 ComplexValue LHS = Result;
9795 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9796 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9797 Result.getComplexIntReal() =
9798 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9799 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9800 Result.getComplexIntImag() =
9801 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9802 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9803 }
9804 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009805 }
9806
John McCall93d91dc2010-05-07 17:22:02 +00009807 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009808}
9809
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009810bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9811 // Get the operand value into 'Result'.
9812 if (!Visit(E->getSubExpr()))
9813 return false;
9814
9815 switch (E->getOpcode()) {
9816 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009817 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009818 case UO_Extension:
9819 return true;
9820 case UO_Plus:
9821 // The result is always just the subexpr.
9822 return true;
9823 case UO_Minus:
9824 if (Result.isComplexFloat()) {
9825 Result.getComplexFloatReal().changeSign();
9826 Result.getComplexFloatImag().changeSign();
9827 }
9828 else {
9829 Result.getComplexIntReal() = -Result.getComplexIntReal();
9830 Result.getComplexIntImag() = -Result.getComplexIntImag();
9831 }
9832 return true;
9833 case UO_Not:
9834 if (Result.isComplexFloat())
9835 Result.getComplexFloatImag().changeSign();
9836 else
9837 Result.getComplexIntImag() = -Result.getComplexIntImag();
9838 return true;
9839 }
9840}
9841
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009842bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9843 if (E->getNumInits() == 2) {
9844 if (E->getType()->isComplexType()) {
9845 Result.makeComplexFloat();
9846 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9847 return false;
9848 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9849 return false;
9850 } else {
9851 Result.makeComplexInt();
9852 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9853 return false;
9854 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9855 return false;
9856 }
9857 return true;
9858 }
9859 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9860}
9861
Anders Carlsson537969c2008-11-16 20:27:53 +00009862//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009863// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9864// implicit conversion.
9865//===----------------------------------------------------------------------===//
9866
9867namespace {
9868class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009869 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009870 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009871 APValue &Result;
9872public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009873 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9874 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009875
9876 bool Success(const APValue &V, const Expr *E) {
9877 Result = V;
9878 return true;
9879 }
9880
9881 bool ZeroInitialization(const Expr *E) {
9882 ImplicitValueInitExpr VIE(
9883 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009884 // For atomic-qualified class (and array) types in C++, initialize the
9885 // _Atomic-wrapped subobject directly, in-place.
9886 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9887 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009888 }
9889
9890 bool VisitCastExpr(const CastExpr *E) {
9891 switch (E->getCastKind()) {
9892 default:
9893 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9894 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009895 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9896 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009897 }
9898 }
9899};
9900} // end anonymous namespace
9901
Richard Smith64cb9ca2017-02-22 22:09:50 +00009902static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9903 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009904 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009905 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009906}
9907
9908//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009909// Void expression evaluation, primarily for a cast to void on the LHS of a
9910// comma operator
9911//===----------------------------------------------------------------------===//
9912
9913namespace {
9914class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009915 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009916public:
9917 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9918
Richard Smith2e312c82012-03-03 22:46:17 +00009919 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009920
Richard Smith7cd577b2017-08-17 19:35:50 +00009921 bool ZeroInitialization(const Expr *E) { return true; }
9922
Richard Smith42d3af92011-12-07 00:43:50 +00009923 bool VisitCastExpr(const CastExpr *E) {
9924 switch (E->getCastKind()) {
9925 default:
9926 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9927 case CK_ToVoid:
9928 VisitIgnoredValue(E->getSubExpr());
9929 return true;
9930 }
9931 }
Hal Finkela8443c32014-07-17 14:49:58 +00009932
9933 bool VisitCallExpr(const CallExpr *E) {
9934 switch (E->getBuiltinCallee()) {
9935 default:
9936 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9937 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009938 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009939 // The argument is not evaluated!
9940 return true;
9941 }
9942 }
Richard Smith42d3af92011-12-07 00:43:50 +00009943};
9944} // end anonymous namespace
9945
9946static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9947 assert(E->isRValue() && E->getType()->isVoidType());
9948 return VoidExprEvaluator(Info).Visit(E);
9949}
9950
9951//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009952// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009953//===----------------------------------------------------------------------===//
9954
Richard Smith2e312c82012-03-03 22:46:17 +00009955static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009956 // In C, function designators are not lvalues, but we evaluate them as if they
9957 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009958 QualType T = E->getType();
9959 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009960 LValue LV;
9961 if (!EvaluateLValue(E, LV, Info))
9962 return false;
9963 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009964 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009965 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009966 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009967 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009968 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009969 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009970 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009971 LValue LV;
9972 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009973 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009974 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009975 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009976 llvm::APFloat F(0.0);
9977 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009978 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009979 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009980 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009981 ComplexValue C;
9982 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009983 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009984 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009985 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009986 MemberPtr P;
9987 if (!EvaluateMemberPointer(E, P, Info))
9988 return false;
9989 P.moveInto(Result);
9990 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009991 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009992 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009993 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009994 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9995 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009996 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009997 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009998 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009999 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010000 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010001 APValue &Value = Info.CurrentCall->createTemporary(E, false);
10002 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000010003 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010004 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010005 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010006 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010007 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000010008 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000010009 if (!EvaluateVoid(E, Info))
10010 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010011 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010012 QualType Unqual = T.getAtomicUnqualifiedType();
10013 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10014 LValue LV;
10015 LV.set(E, Info.CurrentCall->Index);
10016 APValue &Value = Info.CurrentCall->createTemporary(E, false);
10017 if (!EvaluateAtomic(E, &LV, Value, Info))
10018 return false;
10019 } else {
10020 if (!EvaluateAtomic(E, nullptr, Result, Info))
10021 return false;
10022 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010023 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010024 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010025 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010026 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010027 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010028 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010029 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010030
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010031 return true;
10032}
10033
Richard Smithb228a862012-02-15 02:18:13 +000010034/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10035/// cases, the in-place evaluation is essential, since later initializers for
10036/// an object can indirectly refer to subobjects which were initialized earlier.
10037static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010038 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010039 assert(!E->isValueDependent());
10040
Richard Smith7525ff62013-05-09 07:14:00 +000010041 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010042 return false;
10043
10044 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010045 // Evaluate arrays and record types in-place, so that later initializers can
10046 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010047 QualType T = E->getType();
10048 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010049 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010050 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010051 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010052 else if (T->isAtomicType()) {
10053 QualType Unqual = T.getAtomicUnqualifiedType();
10054 if (Unqual->isArrayType() || Unqual->isRecordType())
10055 return EvaluateAtomic(E, &This, Result, Info);
10056 }
Richard Smithed5165f2011-11-04 05:33:44 +000010057 }
10058
10059 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010060 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010061}
10062
Richard Smithf57d8cb2011-12-09 22:58:01 +000010063/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10064/// lvalue-to-rvalue cast if it is an lvalue.
10065static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010066 if (E->getType().isNull())
10067 return false;
10068
Nick Lewyckyc190f962017-05-02 01:06:16 +000010069 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010070 return false;
10071
Richard Smith2e312c82012-03-03 22:46:17 +000010072 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010073 return false;
10074
10075 if (E->isGLValue()) {
10076 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010077 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010078 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010079 return false;
10080 }
10081
Richard Smith2e312c82012-03-03 22:46:17 +000010082 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010083 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010084}
Richard Smith11562c52011-10-28 17:51:58 +000010085
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010086static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010087 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010088 // Fast-path evaluations of integer literals, since we sometimes see files
10089 // containing vast quantities of these.
10090 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10091 Result.Val = APValue(APSInt(L->getValue(),
10092 L->getType()->isUnsignedIntegerType()));
10093 IsConst = true;
10094 return true;
10095 }
James Dennett0492ef02014-03-14 17:44:10 +000010096
10097 // This case should be rare, but we need to check it before we check on
10098 // the type below.
10099 if (Exp->getType().isNull()) {
10100 IsConst = false;
10101 return true;
10102 }
Daniel Jasperffdee092017-05-02 19:21:42 +000010103
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010104 // FIXME: Evaluating values of large array and record types can cause
10105 // performance problems. Only do so in C++11 for now.
10106 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10107 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010108 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010109 IsConst = false;
10110 return true;
10111 }
10112 return false;
10113}
10114
10115
Richard Smith7b553f12011-10-29 00:50:52 +000010116/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010117/// any crazy technique (that has nothing to do with language standards) that
10118/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010119/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10120/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010121bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010122 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010123 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010124 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +000010125
Richard Smith6d4c6582013-11-05 22:18:15 +000010126 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010127 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010128}
10129
Jay Foad39c79802011-01-12 09:06:06 +000010130bool Expr::EvaluateAsBooleanCondition(bool &Result,
10131 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010132 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010133 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010134 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010135}
10136
Richard Smithce8eca52015-12-08 03:21:47 +000010137static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10138 Expr::SideEffectsKind SEK) {
10139 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10140 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10141}
10142
Richard Smith5fab0c92011-12-28 19:48:30 +000010143bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10144 SideEffectsKind AllowSideEffects) const {
10145 if (!getType()->isIntegralOrEnumerationType())
10146 return false;
10147
Richard Smith11562c52011-10-28 17:51:58 +000010148 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010149 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010150 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010151 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010152
Richard Smith11562c52011-10-28 17:51:58 +000010153 Result = ExprResult.Val.getInt();
10154 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010155}
10156
Richard Trieube234c32016-04-21 21:04:55 +000010157bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10158 SideEffectsKind AllowSideEffects) const {
10159 if (!getType()->isRealFloatingType())
10160 return false;
10161
10162 EvalResult ExprResult;
10163 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10164 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10165 return false;
10166
10167 Result = ExprResult.Val.getFloat();
10168 return true;
10169}
10170
Jay Foad39c79802011-01-12 09:06:06 +000010171bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010172 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010173
John McCall45d55e42010-05-07 21:00:08 +000010174 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010175 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10176 !CheckLValueConstantExpression(Info, getExprLoc(),
10177 Ctx.getLValueReferenceType(getType()), LV))
10178 return false;
10179
Richard Smith2e312c82012-03-03 22:46:17 +000010180 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010181 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010182}
10183
Richard Smithd0b4dd62011-12-19 06:19:21 +000010184bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10185 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010186 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010187 // FIXME: Evaluating initializers for large array and record types can cause
10188 // performance problems. Only do so in C++11 for now.
10189 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010190 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010191 return false;
10192
Richard Smithd0b4dd62011-12-19 06:19:21 +000010193 Expr::EvalStatus EStatus;
10194 EStatus.Diag = &Notes;
10195
Richard Smith0c6124b2015-12-03 01:36:22 +000010196 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10197 ? EvalInfo::EM_ConstantExpression
10198 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010199 InitInfo.setEvaluatingDecl(VD, Value);
10200
10201 LValue LVal;
10202 LVal.set(VD);
10203
Richard Smithfddd3842011-12-30 21:15:51 +000010204 // C++11 [basic.start.init]p2:
10205 // Variables with static storage duration or thread storage duration shall be
10206 // zero-initialized before any other initialization takes place.
10207 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010208 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010209 !VD->getType()->isReferenceType()) {
10210 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010211 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010212 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010213 return false;
10214 }
10215
Richard Smith7525ff62013-05-09 07:14:00 +000010216 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10217 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010218 EStatus.HasSideEffects)
10219 return false;
10220
10221 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10222 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010223}
10224
Richard Smith7b553f12011-10-29 00:50:52 +000010225/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10226/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010227bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010228 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010229 return EvaluateAsRValue(Result, Ctx) &&
10230 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010231}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010232
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010233APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010234 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010235 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010236 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010237 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010238 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010239 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010240 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010241
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010242 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010243}
John McCall864e3962010-05-07 05:32:02 +000010244
Richard Smithe9ff7702013-11-05 22:23:30 +000010245void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010246 bool IsConst;
10247 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010248 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010249 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010250 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10251 }
10252}
10253
Richard Smithe6c01442013-06-05 00:46:14 +000010254bool Expr::EvalResult::isGlobalLValue() const {
10255 assert(Val.isLValue());
10256 return IsGlobalLValue(Val.getLValueBase());
10257}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010258
10259
John McCall864e3962010-05-07 05:32:02 +000010260/// isIntegerConstantExpr - this recursive routine will test if an expression is
10261/// an integer constant expression.
10262
10263/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10264/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010265
10266// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010267// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10268// and a (possibly null) SourceLocation indicating the location of the problem.
10269//
John McCall864e3962010-05-07 05:32:02 +000010270// Note that to reduce code duplication, this helper does no evaluation
10271// itself; the caller checks whether the expression is evaluatable, and
10272// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010273// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010274
Dan Gohman28ade552010-07-26 21:25:24 +000010275namespace {
10276
Richard Smith9e575da2012-12-28 13:25:52 +000010277enum ICEKind {
10278 /// This expression is an ICE.
10279 IK_ICE,
10280 /// This expression is not an ICE, but if it isn't evaluated, it's
10281 /// a legal subexpression for an ICE. This return value is used to handle
10282 /// the comma operator in C99 mode, and non-constant subexpressions.
10283 IK_ICEIfUnevaluated,
10284 /// This expression is not an ICE, and is not a legal subexpression for one.
10285 IK_NotICE
10286};
10287
John McCall864e3962010-05-07 05:32:02 +000010288struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010289 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010290 SourceLocation Loc;
10291
Richard Smith9e575da2012-12-28 13:25:52 +000010292 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010293};
10294
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010295}
Dan Gohman28ade552010-07-26 21:25:24 +000010296
Richard Smith9e575da2012-12-28 13:25:52 +000010297static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10298
10299static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010300
Craig Toppera31a8822013-08-22 07:09:37 +000010301static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010302 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010303 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010304 !EVResult.Val.isInt())
10305 return ICEDiag(IK_NotICE, E->getLocStart());
10306
John McCall864e3962010-05-07 05:32:02 +000010307 return NoDiag();
10308}
10309
Craig Toppera31a8822013-08-22 07:09:37 +000010310static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010311 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010312 if (!E->getType()->isIntegralOrEnumerationType())
10313 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010314
10315 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010316#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010317#define STMT(Node, Base) case Expr::Node##Class:
10318#define EXPR(Node, Base)
10319#include "clang/AST/StmtNodes.inc"
10320 case Expr::PredefinedExprClass:
10321 case Expr::FloatingLiteralClass:
10322 case Expr::ImaginaryLiteralClass:
10323 case Expr::StringLiteralClass:
10324 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010325 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010326 case Expr::MemberExprClass:
10327 case Expr::CompoundAssignOperatorClass:
10328 case Expr::CompoundLiteralExprClass:
10329 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010330 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010331 case Expr::ArrayInitLoopExprClass:
10332 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010333 case Expr::NoInitExprClass:
10334 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010335 case Expr::ImplicitValueInitExprClass:
10336 case Expr::ParenListExprClass:
10337 case Expr::VAArgExprClass:
10338 case Expr::AddrLabelExprClass:
10339 case Expr::StmtExprClass:
10340 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010341 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010342 case Expr::CXXDynamicCastExprClass:
10343 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010344 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010345 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010346 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010347 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010348 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010349 case Expr::CXXThisExprClass:
10350 case Expr::CXXThrowExprClass:
10351 case Expr::CXXNewExprClass:
10352 case Expr::CXXDeleteExprClass:
10353 case Expr::CXXPseudoDestructorExprClass:
10354 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010355 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010356 case Expr::DependentScopeDeclRefExprClass:
10357 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010358 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010359 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010360 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010361 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010362 case Expr::CXXTemporaryObjectExprClass:
10363 case Expr::CXXUnresolvedConstructExprClass:
10364 case Expr::CXXDependentScopeMemberExprClass:
10365 case Expr::UnresolvedMemberExprClass:
10366 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010367 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010368 case Expr::ObjCArrayLiteralClass:
10369 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010370 case Expr::ObjCEncodeExprClass:
10371 case Expr::ObjCMessageExprClass:
10372 case Expr::ObjCSelectorExprClass:
10373 case Expr::ObjCProtocolExprClass:
10374 case Expr::ObjCIvarRefExprClass:
10375 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010376 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010377 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010378 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010379 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010380 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010381 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010382 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010383 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010384 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010385 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010386 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010387 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010388 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010389 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010390 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010391 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010392 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010393 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010394 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010395 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010396 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010397 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010398
Richard Smithf137f932014-01-25 20:50:08 +000010399 case Expr::InitListExprClass: {
10400 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10401 // form "T x = { a };" is equivalent to "T x = a;".
10402 // Unless we're initializing a reference, T is a scalar as it is known to be
10403 // of integral or enumeration type.
10404 if (E->isRValue())
10405 if (cast<InitListExpr>(E)->getNumInits() == 1)
10406 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10407 return ICEDiag(IK_NotICE, E->getLocStart());
10408 }
10409
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010410 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010411 case Expr::GNUNullExprClass:
10412 // GCC considers the GNU __null value to be an integral constant expression.
10413 return NoDiag();
10414
John McCall7c454bb2011-07-15 05:09:51 +000010415 case Expr::SubstNonTypeTemplateParmExprClass:
10416 return
10417 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10418
John McCall864e3962010-05-07 05:32:02 +000010419 case Expr::ParenExprClass:
10420 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010421 case Expr::GenericSelectionExprClass:
10422 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010423 case Expr::IntegerLiteralClass:
10424 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010425 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010426 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010427 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010428 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010429 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010430 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010431 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010432 return NoDiag();
10433 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010434 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010435 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10436 // constant expressions, but they can never be ICEs because an ICE cannot
10437 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010438 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010439 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010440 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010441 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010442 }
Richard Smith6365c912012-02-24 22:12:32 +000010443 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010444 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10445 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000010446 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010447 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010448 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010449 // Parameter variables are never constants. Without this check,
10450 // getAnyInitializer() can find a default argument, which leads
10451 // to chaos.
10452 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010453 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010454
10455 // C++ 7.1.5.1p2
10456 // A variable of non-volatile const-qualified integral or enumeration
10457 // type initialized by an ICE can be used in ICEs.
10458 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010459 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010460 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010461
Richard Smithd0b4dd62011-12-19 06:19:21 +000010462 const VarDecl *VD;
10463 // Look for a declaration of this variable that has an initializer, and
10464 // check whether it is an ICE.
10465 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10466 return NoDiag();
10467 else
Richard Smith9e575da2012-12-28 13:25:52 +000010468 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010469 }
10470 }
Richard Smith9e575da2012-12-28 13:25:52 +000010471 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010472 }
John McCall864e3962010-05-07 05:32:02 +000010473 case Expr::UnaryOperatorClass: {
10474 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10475 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010476 case UO_PostInc:
10477 case UO_PostDec:
10478 case UO_PreInc:
10479 case UO_PreDec:
10480 case UO_AddrOf:
10481 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010482 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010483 // C99 6.6/3 allows increment and decrement within unevaluated
10484 // subexpressions of constant expressions, but they can never be ICEs
10485 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010486 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010487 case UO_Extension:
10488 case UO_LNot:
10489 case UO_Plus:
10490 case UO_Minus:
10491 case UO_Not:
10492 case UO_Real:
10493 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010494 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010495 }
Richard Smith9e575da2012-12-28 13:25:52 +000010496
John McCall864e3962010-05-07 05:32:02 +000010497 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010498 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010499 }
10500 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010501 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10502 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10503 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10504 // compliance: we should warn earlier for offsetof expressions with
10505 // array subscripts that aren't ICEs, and if the array subscripts
10506 // are ICEs, the value of the offsetof must be an integer constant.
10507 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010508 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010509 case Expr::UnaryExprOrTypeTraitExprClass: {
10510 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10511 if ((Exp->getKind() == UETT_SizeOf) &&
10512 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010513 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010514 return NoDiag();
10515 }
10516 case Expr::BinaryOperatorClass: {
10517 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10518 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010519 case BO_PtrMemD:
10520 case BO_PtrMemI:
10521 case BO_Assign:
10522 case BO_MulAssign:
10523 case BO_DivAssign:
10524 case BO_RemAssign:
10525 case BO_AddAssign:
10526 case BO_SubAssign:
10527 case BO_ShlAssign:
10528 case BO_ShrAssign:
10529 case BO_AndAssign:
10530 case BO_XorAssign:
10531 case BO_OrAssign:
Richard Smithc70f1d62017-12-14 15:16:18 +000010532 case BO_Cmp: // FIXME: Re-enable once we can evaluate this.
Richard Smith62f65952011-10-24 22:35:48 +000010533 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10534 // constant expressions, but they can never be ICEs because an ICE cannot
10535 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010536 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010537
John McCalle3027922010-08-25 11:45:40 +000010538 case BO_Mul:
10539 case BO_Div:
10540 case BO_Rem:
10541 case BO_Add:
10542 case BO_Sub:
10543 case BO_Shl:
10544 case BO_Shr:
10545 case BO_LT:
10546 case BO_GT:
10547 case BO_LE:
10548 case BO_GE:
10549 case BO_EQ:
10550 case BO_NE:
10551 case BO_And:
10552 case BO_Xor:
10553 case BO_Or:
10554 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010555 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10556 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010557 if (Exp->getOpcode() == BO_Div ||
10558 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010559 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010560 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010561 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010562 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010563 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010564 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010565 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010566 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010567 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010568 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010569 }
10570 }
10571 }
John McCalle3027922010-08-25 11:45:40 +000010572 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010573 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010574 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10575 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010576 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10577 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010578 } else {
10579 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010580 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010581 }
10582 }
Richard Smith9e575da2012-12-28 13:25:52 +000010583 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010584 }
John McCalle3027922010-08-25 11:45:40 +000010585 case BO_LAnd:
10586 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010587 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10588 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010589 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010590 // Rare case where the RHS has a comma "side-effect"; we need
10591 // to actually check the condition to see whether the side
10592 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010593 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010594 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010595 return RHSResult;
10596 return NoDiag();
10597 }
10598
Richard Smith9e575da2012-12-28 13:25:52 +000010599 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010600 }
10601 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010602 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010603 }
10604 case Expr::ImplicitCastExprClass:
10605 case Expr::CStyleCastExprClass:
10606 case Expr::CXXFunctionalCastExprClass:
10607 case Expr::CXXStaticCastExprClass:
10608 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010609 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010610 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010611 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010612 if (isa<ExplicitCastExpr>(E)) {
10613 if (const FloatingLiteral *FL
10614 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10615 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10616 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10617 APSInt IgnoredVal(DestWidth, !DestSigned);
10618 bool Ignored;
10619 // If the value does not fit in the destination type, the behavior is
10620 // undefined, so we are not required to treat it as a constant
10621 // expression.
10622 if (FL->getValue().convertToInteger(IgnoredVal,
10623 llvm::APFloat::rmTowardZero,
10624 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010625 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010626 return NoDiag();
10627 }
10628 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010629 switch (cast<CastExpr>(E)->getCastKind()) {
10630 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010631 case CK_AtomicToNonAtomic:
10632 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010633 case CK_NoOp:
10634 case CK_IntegralToBoolean:
10635 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010636 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010637 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010638 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010639 }
John McCall864e3962010-05-07 05:32:02 +000010640 }
John McCallc07a0c72011-02-17 10:25:35 +000010641 case Expr::BinaryConditionalOperatorClass: {
10642 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10643 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010644 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010645 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010646 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10647 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10648 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010649 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010650 return FalseResult;
10651 }
John McCall864e3962010-05-07 05:32:02 +000010652 case Expr::ConditionalOperatorClass: {
10653 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10654 // If the condition (ignoring parens) is a __builtin_constant_p call,
10655 // then only the true side is actually considered in an integer constant
10656 // expression, and it is fully evaluated. This is an important GNU
10657 // extension. See GCC PR38377 for discussion.
10658 if (const CallExpr *CallCE
10659 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010660 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010661 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010662 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010663 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010664 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010665
Richard Smithf57d8cb2011-12-09 22:58:01 +000010666 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10667 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010668
Richard Smith9e575da2012-12-28 13:25:52 +000010669 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010670 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010671 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010672 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010673 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010674 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010675 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010676 return NoDiag();
10677 // Rare case where the diagnostics depend on which side is evaluated
10678 // Note that if we get here, CondResult is 0, and at least one of
10679 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010680 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010681 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010682 return TrueResult;
10683 }
10684 case Expr::CXXDefaultArgExprClass:
10685 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010686 case Expr::CXXDefaultInitExprClass:
10687 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010688 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010689 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010690 }
10691 }
10692
David Blaikiee4d798f2012-01-20 21:50:17 +000010693 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010694}
10695
Richard Smithf57d8cb2011-12-09 22:58:01 +000010696/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010697static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010698 const Expr *E,
10699 llvm::APSInt *Value,
10700 SourceLocation *Loc) {
10701 if (!E->getType()->isIntegralOrEnumerationType()) {
10702 if (Loc) *Loc = E->getExprLoc();
10703 return false;
10704 }
10705
Richard Smith66e05fe2012-01-18 05:21:49 +000010706 APValue Result;
10707 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010708 return false;
10709
Richard Smith98710fc2014-11-13 23:03:19 +000010710 if (!Result.isInt()) {
10711 if (Loc) *Loc = E->getExprLoc();
10712 return false;
10713 }
10714
Richard Smith66e05fe2012-01-18 05:21:49 +000010715 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010716 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010717}
10718
Craig Toppera31a8822013-08-22 07:09:37 +000010719bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10720 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010721 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010722 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010723
Richard Smith9e575da2012-12-28 13:25:52 +000010724 ICEDiag D = CheckICE(this, Ctx);
10725 if (D.Kind != IK_ICE) {
10726 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010727 return false;
10728 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010729 return true;
10730}
10731
Craig Toppera31a8822013-08-22 07:09:37 +000010732bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010733 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010734 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010735 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10736
10737 if (!isIntegerConstantExpr(Ctx, Loc))
10738 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010739 // The only possible side-effects here are due to UB discovered in the
10740 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10741 // required to treat the expression as an ICE, so we produce the folded
10742 // value.
10743 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010744 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010745 return true;
10746}
Richard Smith66e05fe2012-01-18 05:21:49 +000010747
Craig Toppera31a8822013-08-22 07:09:37 +000010748bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010749 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010750}
10751
Craig Toppera31a8822013-08-22 07:09:37 +000010752bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010753 SourceLocation *Loc) const {
10754 // We support this checking in C++98 mode in order to diagnose compatibility
10755 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010756 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010757
Richard Smith98a0a492012-02-14 21:38:30 +000010758 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010759 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010760 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010761 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010762 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010763
10764 APValue Scratch;
10765 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10766
10767 if (!Diags.empty()) {
10768 IsConstExpr = false;
10769 if (Loc) *Loc = Diags[0].first;
10770 } else if (!IsConstExpr) {
10771 // FIXME: This shouldn't happen.
10772 if (Loc) *Loc = getExprLoc();
10773 }
10774
10775 return IsConstExpr;
10776}
Richard Smith253c2a32012-01-27 01:14:48 +000010777
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010778bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10779 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010780 ArrayRef<const Expr*> Args,
10781 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010782 Expr::EvalStatus Status;
10783 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10784
George Burgess IV177399e2017-01-09 04:12:14 +000010785 LValue ThisVal;
10786 const LValue *ThisPtr = nullptr;
10787 if (This) {
10788#ifndef NDEBUG
10789 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10790 assert(MD && "Don't provide `this` for non-methods.");
10791 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10792#endif
10793 if (EvaluateObjectArgument(Info, This, ThisVal))
10794 ThisPtr = &ThisVal;
10795 if (Info.EvalStatus.HasSideEffects)
10796 return false;
10797 }
10798
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010799 ArgVector ArgValues(Args.size());
10800 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10801 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010802 if ((*I)->isValueDependent() ||
10803 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010804 // If evaluation fails, throw away the argument entirely.
10805 ArgValues[I - Args.begin()] = APValue();
10806 if (Info.EvalStatus.HasSideEffects)
10807 return false;
10808 }
10809
10810 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010811 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010812 ArgValues.data());
10813 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10814}
10815
Richard Smith253c2a32012-01-27 01:14:48 +000010816bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010817 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010818 PartialDiagnosticAt> &Diags) {
10819 // FIXME: It would be useful to check constexpr function templates, but at the
10820 // moment the constant expression evaluator cannot cope with the non-rigorous
10821 // ASTs which we build for dependent expressions.
10822 if (FD->isDependentContext())
10823 return true;
10824
10825 Expr::EvalStatus Status;
10826 Status.Diag = &Diags;
10827
Richard Smith6d4c6582013-11-05 22:18:15 +000010828 EvalInfo Info(FD->getASTContext(), Status,
10829 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010830
10831 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010832 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010833
Richard Smith7525ff62013-05-09 07:14:00 +000010834 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010835 // is a temporary being used as the 'this' pointer.
10836 LValue This;
10837 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010838 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010839
Richard Smith253c2a32012-01-27 01:14:48 +000010840 ArrayRef<const Expr*> Args;
10841
Richard Smith2e312c82012-03-03 22:46:17 +000010842 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010843 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10844 // Evaluate the call as a constant initializer, to allow the construction
10845 // of objects of non-literal types.
10846 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010847 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10848 } else {
10849 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010850 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010851 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010852 }
Richard Smith253c2a32012-01-27 01:14:48 +000010853
10854 return Diags.empty();
10855}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010856
10857bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10858 const FunctionDecl *FD,
10859 SmallVectorImpl<
10860 PartialDiagnosticAt> &Diags) {
10861 Expr::EvalStatus Status;
10862 Status.Diag = &Diags;
10863
10864 EvalInfo Info(FD->getASTContext(), Status,
10865 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10866
10867 // Fabricate a call stack frame to give the arguments a plausible cover story.
10868 ArrayRef<const Expr*> Args;
10869 ArgVector ArgValues(0);
10870 bool Success = EvaluateArgs(Args, ArgValues, Info);
10871 (void)Success;
10872 assert(Success &&
10873 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010874 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010875
10876 APValue ResultScratch;
10877 Evaluate(ResultScratch, Info, E);
10878 return Diags.empty();
10879}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010880
10881bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10882 unsigned Type) const {
10883 if (!getType()->isPointerType())
10884 return false;
10885
10886 Expr::EvalStatus Status;
10887 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010888 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010889}