blob: c540dfbbf070445b86848fa97cd6c15044f2099c [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.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000455 typedef std::pair<const void *, unsigned> MapKeyTy;
456 typedef std::map<MapKeyTy, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000457 /// 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
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000466 /// The stack of integers for tracking version numbers for temporaries.
467 SmallVector<unsigned, 2> TempVersionStack = {1};
468 unsigned CurTempVersion = TempVersionStack.back();
469
470 unsigned getTempVersion() const { return TempVersionStack.back(); }
471
472 void pushTempVersion() {
473 TempVersionStack.push_back(++CurTempVersion);
474 }
475
476 void popTempVersion() {
477 TempVersionStack.pop_back();
478 }
479
Faisal Vali051e3a22017-02-16 04:12:21 +0000480 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
481 // on the overall stack usage of deeply-recursing constexpr evaluataions.
482 // (We should cache this map rather than recomputing it repeatedly.)
483 // But let's try this and see how it goes; we can look into caching the map
484 // as a later change.
485
486 /// LambdaCaptureFields - Mapping from captured variables/this to
487 /// corresponding data members in the closure class.
488 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
489 FieldDecl *LambdaThisCaptureField;
490
Richard Smithf6f003a2011-12-16 19:06:07 +0000491 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
492 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000493 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000494 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000495
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000496 // Return the temporary for Key whose version number is Version.
497 APValue *getTemporary(const void *Key, unsigned Version) {
498 MapKeyTy KV(Key, Version);
499 auto LB = Temporaries.lower_bound(KV);
500 if (LB != Temporaries.end() && LB->first == KV)
501 return &LB->second;
502 // Pair (Key,Version) wasn't found in the map. Check that no elements
503 // in the map have 'Key' as their key.
504 assert((LB == Temporaries.end() || LB->first.first != Key) &&
505 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
506 "Element with key 'Key' found in map");
507 return nullptr;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000508 }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000509
510 // Return the current temporary for Key in the map.
511 APValue *getCurrentTemporary(const void *Key) {
512 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
513 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
514 return &std::prev(UB)->second;
515 return nullptr;
516 }
517
518 // Return the version number of the current temporary for Key.
519 unsigned getCurrentTemporaryVersion(const void *Key) const {
520 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
521 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
522 return std::prev(UB)->first.second;
523 return 0;
524 }
525
Richard Smith08d6a2c2013-07-24 07:11:57 +0000526 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000527 };
528
Richard Smith852c9db2013-04-20 22:23:05 +0000529 /// Temporarily override 'this'.
530 class ThisOverrideRAII {
531 public:
532 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
533 : Frame(Frame), OldThis(Frame.This) {
534 if (Enable)
535 Frame.This = NewThis;
536 }
537 ~ThisOverrideRAII() {
538 Frame.This = OldThis;
539 }
540 private:
541 CallStackFrame &Frame;
542 const LValue *OldThis;
543 };
544
Richard Smith92b1ce02011-12-12 09:28:41 +0000545 /// A partial diagnostic which we might know in advance that we are not going
546 /// to emit.
547 class OptionalDiagnostic {
548 PartialDiagnostic *Diag;
549
550 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000551 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
552 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000553
554 template<typename T>
555 OptionalDiagnostic &operator<<(const T &v) {
556 if (Diag)
557 *Diag << v;
558 return *this;
559 }
Richard Smithfe800032012-01-31 04:08:20 +0000560
561 OptionalDiagnostic &operator<<(const APSInt &I) {
562 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000563 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000564 I.toString(Buffer);
565 *Diag << StringRef(Buffer.data(), Buffer.size());
566 }
567 return *this;
568 }
569
570 OptionalDiagnostic &operator<<(const APFloat &F) {
571 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000572 // FIXME: Force the precision of the source value down so we don't
573 // print digits which are usually useless (we don't really care here if
574 // we truncate a digit by accident in edge cases). Ideally,
Daniel Jasperffdee092017-05-02 19:21:42 +0000575 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000576 // representation which rounds to the correct value, but it's a bit
577 // tricky to implement.
578 unsigned precision =
579 llvm::APFloat::semanticsPrecision(F.getSemantics());
580 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000581 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000582 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000583 *Diag << StringRef(Buffer.data(), Buffer.size());
584 }
585 return *this;
586 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000587 };
588
Richard Smith08d6a2c2013-07-24 07:11:57 +0000589 /// A cleanup, and a flag indicating whether it is lifetime-extended.
590 class Cleanup {
591 llvm::PointerIntPair<APValue*, 1, bool> Value;
592
593 public:
594 Cleanup(APValue *Val, bool IsLifetimeExtended)
595 : Value(Val, IsLifetimeExtended) {}
596
597 bool isLifetimeExtended() const { return Value.getInt(); }
598 void endLifetime() {
599 *Value.getPointer() = APValue();
600 }
601 };
602
Richard Smithb228a862012-02-15 02:18:13 +0000603 /// EvalInfo - This is a private struct used by the evaluator to capture
604 /// information about a subexpression as it is folded. It retains information
605 /// about the AST context, but also maintains information about the folded
606 /// expression.
607 ///
608 /// If an expression could be evaluated, it is still possible it is not a C
609 /// "integer constant expression" or constant expression. If not, this struct
610 /// captures information about how and why not.
611 ///
612 /// One bit of information passed *into* the request for constant folding
613 /// indicates whether the subexpression is "evaluated" or not according to C
614 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
615 /// evaluate the expression regardless of what the RHS is, but C only allows
616 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000617 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000618 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000619
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000620 /// EvalStatus - Contains information about the evaluation.
621 Expr::EvalStatus &EvalStatus;
622
623 /// CurrentCall - The top of the constexpr call stack.
624 CallStackFrame *CurrentCall;
625
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000626 /// CallStackDepth - The number of calls in the call stack right now.
627 unsigned CallStackDepth;
628
Richard Smithb228a862012-02-15 02:18:13 +0000629 /// NextCallIndex - The next call index to assign.
630 unsigned NextCallIndex;
631
Richard Smitha3d3bd22013-05-08 02:12:03 +0000632 /// StepsLeft - The remaining number of evaluation steps we're permitted
633 /// to perform. This is essentially a limit for the number of statements
634 /// we will evaluate.
635 unsigned StepsLeft;
636
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000637 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000638 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000639 CallStackFrame BottomFrame;
640
Richard Smith08d6a2c2013-07-24 07:11:57 +0000641 /// A stack of values whose lifetimes end at the end of some surrounding
642 /// evaluation frame.
643 llvm::SmallVector<Cleanup, 16> CleanupStack;
644
Richard Smithd62306a2011-11-10 06:34:14 +0000645 /// EvaluatingDecl - This is the declaration whose initializer is being
646 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000647 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000648
649 /// EvaluatingDeclValue - This is the value being constructed for the
650 /// declaration whose initializer is being evaluated, if any.
651 APValue *EvaluatingDeclValue;
652
Erik Pilkington42925492017-10-04 00:18:55 +0000653 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
654 /// the call index that that lvalue was allocated in.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000655 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
656 EvaluatingObject;
Erik Pilkington42925492017-10-04 00:18:55 +0000657
658 /// EvaluatingConstructors - Set of objects that are currently being
659 /// constructed.
660 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
661
662 struct EvaluatingConstructorRAII {
663 EvalInfo &EI;
664 EvaluatingObject Object;
665 bool DidInsert;
666 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
667 : EI(EI), Object(Object) {
668 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
669 }
670 ~EvaluatingConstructorRAII() {
671 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
672 }
673 };
674
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000675 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
676 unsigned Version) {
677 return EvaluatingConstructors.count(
678 EvaluatingObject(Decl, {CallIndex, Version}));
Erik Pilkington42925492017-10-04 00:18:55 +0000679 }
680
Richard Smith410306b2016-12-12 02:53:20 +0000681 /// The current array initialization index, if we're performing array
682 /// initialization.
683 uint64_t ArrayInitIndex = -1;
684
Richard Smith357362d2011-12-13 06:39:58 +0000685 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
686 /// notes attached to it will also be stored, otherwise they will not be.
687 bool HasActiveDiagnostic;
688
Richard Smith0c6124b2015-12-03 01:36:22 +0000689 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
690 /// fold (not just why it's not strictly a constant expression)?
691 bool HasFoldFailureDiagnostic;
692
George Burgess IV8c892b52016-05-25 22:31:54 +0000693 /// \brief Whether or not we're currently speculatively evaluating.
694 bool IsSpeculativelyEvaluating;
695
Richard Smith6d4c6582013-11-05 22:18:15 +0000696 enum EvaluationMode {
697 /// Evaluate as a constant expression. Stop if we find that the expression
698 /// is not a constant expression.
699 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000700
Richard Smith6d4c6582013-11-05 22:18:15 +0000701 /// Evaluate as a potential constant expression. Keep going if we hit a
702 /// construct that we can't evaluate yet (because we don't yet know the
703 /// value of something) but stop if we hit something that could never be
704 /// a constant expression.
705 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000706
Richard Smith6d4c6582013-11-05 22:18:15 +0000707 /// Fold the expression to a constant. Stop if we hit a side-effect that
708 /// we can't model.
709 EM_ConstantFold,
710
711 /// Evaluate the expression looking for integer overflow and similar
712 /// issues. Don't worry about side-effects, and try to visit all
713 /// subexpressions.
714 EM_EvaluateForOverflow,
715
716 /// Evaluate in any way we know how. Don't worry about side-effects that
717 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000718 EM_IgnoreSideEffects,
719
720 /// Evaluate as a constant expression. Stop if we find that the expression
721 /// is not a constant expression. Some expressions can be retried in the
722 /// optimizer if we don't constant fold them here, but in an unevaluated
723 /// context we try to fold them immediately since the optimizer never
724 /// gets a chance to look at it.
725 EM_ConstantExpressionUnevaluated,
726
727 /// Evaluate as a potential constant expression. Keep going if we hit a
728 /// construct that we can't evaluate yet (because we don't yet know the
729 /// value of something) but stop if we hit something that could never be
730 /// a constant expression. Some expressions can be retried in the
731 /// optimizer if we don't constant fold them here, but in an unevaluated
732 /// context we try to fold them immediately since the optimizer never
733 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000734 EM_PotentialConstantExpressionUnevaluated,
735
George Burgess IVf9013bf2017-02-10 22:52:29 +0000736 /// Evaluate as a constant expression. In certain scenarios, if:
737 /// - we find a MemberExpr with a base that can't be evaluated, or
738 /// - we find a variable initialized with a call to a function that has
739 /// the alloc_size attribute on it
740 /// then we may consider evaluation to have succeeded.
741 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000742 /// In either case, the LValue returned shall have an invalid base; in the
743 /// former, the base will be the invalid MemberExpr, in the latter, the
744 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
745 /// said CallExpr.
746 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000747 } EvalMode;
748
749 /// Are we checking whether the expression is a potential constant
750 /// expression?
751 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000752 return EvalMode == EM_PotentialConstantExpression ||
753 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000754 }
755
756 /// Are we checking an expression for overflow?
757 // FIXME: We should check for any kind of undefined or suspicious behavior
758 // in such constructs, not just overflow.
759 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
760
761 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000762 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000763 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000764 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000765 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
766 EvaluatingDecl((const ValueDecl *)nullptr),
767 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000768 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
769 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000770
Richard Smith7525ff62013-05-09 07:14:00 +0000771 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
772 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000773 EvaluatingDeclValue = &Value;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +0000774 EvaluatingConstructors.insert({Base, {0, 0}});
Richard Smithd62306a2011-11-10 06:34:14 +0000775 }
776
David Blaikiebbafb8a2012-03-11 07:00:24 +0000777 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000778
Richard Smith357362d2011-12-13 06:39:58 +0000779 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000780 // Don't perform any constexpr calls (other than the call we're checking)
781 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000782 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000783 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000784 if (NextCallIndex == 0) {
785 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000786 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000787 return false;
788 }
Richard Smith357362d2011-12-13 06:39:58 +0000789 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
790 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000791 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000792 << getLangOpts().ConstexprCallDepth;
793 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000794 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000795
Richard Smithb228a862012-02-15 02:18:13 +0000796 CallStackFrame *getCallFrame(unsigned CallIndex) {
797 assert(CallIndex && "no call index in getCallFrame");
798 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
799 // be null in this loop.
800 CallStackFrame *Frame = CurrentCall;
801 while (Frame->Index > CallIndex)
802 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000803 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000804 }
805
Richard Smitha3d3bd22013-05-08 02:12:03 +0000806 bool nextStep(const Stmt *S) {
807 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000808 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000809 return false;
810 }
811 --StepsLeft;
812 return true;
813 }
814
Richard Smith357362d2011-12-13 06:39:58 +0000815 private:
816 /// Add a diagnostic to the diagnostics list.
817 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
818 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
819 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
820 return EvalStatus.Diag->back().second;
821 }
822
Richard Smithf6f003a2011-12-16 19:06:07 +0000823 /// Add notes containing a call stack to the current point of evaluation.
824 void addCallStack(unsigned Limit);
825
Faisal Valie690b7a2016-07-02 22:34:24 +0000826 private:
827 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
828 unsigned ExtraNotes, bool IsCCEDiag) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000829
Richard Smith92b1ce02011-12-12 09:28:41 +0000830 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000831 // If we have a prior diagnostic, it will be noting that the expression
832 // isn't a constant expression. This diagnostic is more important,
833 // unless we require this evaluation to produce a constant expression.
834 //
835 // FIXME: We might want to show both diagnostics to the user in
836 // EM_ConstantFold mode.
837 if (!EvalStatus.Diag->empty()) {
838 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000839 case EM_ConstantFold:
840 case EM_IgnoreSideEffects:
841 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000842 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000843 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000844 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000845 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000846 case EM_ConstantExpression:
847 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000848 case EM_ConstantExpressionUnevaluated:
849 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000850 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000851 HasActiveDiagnostic = false;
852 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000853 }
854 }
855
Richard Smithf6f003a2011-12-16 19:06:07 +0000856 unsigned CallStackNotes = CallStackDepth - 1;
857 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
858 if (Limit)
859 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000860 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000861 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000862
Richard Smith357362d2011-12-13 06:39:58 +0000863 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000864 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000865 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000866 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
867 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000868 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000869 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000870 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000871 }
Richard Smith357362d2011-12-13 06:39:58 +0000872 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000873 return OptionalDiagnostic();
874 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000875 public:
876 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
877 OptionalDiagnostic
878 FFDiag(SourceLocation Loc,
879 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
880 unsigned ExtraNotes = 0) {
881 return Diag(Loc, DiagId, ExtraNotes, false);
882 }
Daniel Jasperffdee092017-05-02 19:21:42 +0000883
Faisal Valie690b7a2016-07-02 22:34:24 +0000884 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000885 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000886 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000887 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000888 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000889 HasActiveDiagnostic = false;
890 return OptionalDiagnostic();
891 }
892
Richard Smith92b1ce02011-12-12 09:28:41 +0000893 /// Diagnose that the evaluation does not produce a C++11 core constant
894 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000895 ///
896 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
897 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000898 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000899 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000900 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000901 // Don't override a previous diagnostic. Don't bother collecting
902 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000903 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000904 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000905 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000906 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000907 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000908 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000909 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
910 = diag::note_invalid_subexpr_in_const_expr,
911 unsigned ExtraNotes = 0) {
912 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
913 }
Richard Smith357362d2011-12-13 06:39:58 +0000914 /// Add a note to a prior diagnostic.
915 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
916 if (!HasActiveDiagnostic)
917 return OptionalDiagnostic();
918 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000919 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000920
921 /// Add a stack of notes to a prior diagnostic.
922 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
923 if (HasActiveDiagnostic) {
924 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
925 Diags.begin(), Diags.end());
926 }
927 }
Richard Smith253c2a32012-01-27 01:14:48 +0000928
Richard Smith6d4c6582013-11-05 22:18:15 +0000929 /// Should we continue evaluation after encountering a side-effect that we
930 /// couldn't model?
931 bool keepEvaluatingAfterSideEffect() {
932 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000933 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000934 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000935 case EM_EvaluateForOverflow:
936 case EM_IgnoreSideEffects:
937 return true;
938
Richard Smith6d4c6582013-11-05 22:18:15 +0000939 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000940 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000941 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000942 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000943 return false;
944 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000945 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000946 }
947
948 /// Note that we have had a side-effect, and determine whether we should
949 /// keep evaluating.
950 bool noteSideEffect() {
951 EvalStatus.HasSideEffects = true;
952 return keepEvaluatingAfterSideEffect();
953 }
954
Richard Smithce8eca52015-12-08 03:21:47 +0000955 /// Should we continue evaluation after encountering undefined behavior?
956 bool keepEvaluatingAfterUndefinedBehavior() {
957 switch (EvalMode) {
958 case EM_EvaluateForOverflow:
959 case EM_IgnoreSideEffects:
960 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000961 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000962 return true;
963
964 case EM_PotentialConstantExpression:
965 case EM_PotentialConstantExpressionUnevaluated:
966 case EM_ConstantExpression:
967 case EM_ConstantExpressionUnevaluated:
968 return false;
969 }
970 llvm_unreachable("Missed EvalMode case");
971 }
972
973 /// Note that we hit something that was technically undefined behavior, but
974 /// that we can evaluate past it (such as signed overflow or floating-point
975 /// division by zero.)
976 bool noteUndefinedBehavior() {
977 EvalStatus.HasUndefinedBehavior = true;
978 return keepEvaluatingAfterUndefinedBehavior();
979 }
980
Richard Smith253c2a32012-01-27 01:14:48 +0000981 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000982 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000983 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000984 if (!StepsLeft)
985 return false;
986
987 switch (EvalMode) {
988 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000989 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000990 case EM_EvaluateForOverflow:
991 return true;
992
993 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000994 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000995 case EM_ConstantFold:
996 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000997 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000998 return false;
999 }
Aaron Ballmanf682f532013-11-06 18:15:02 +00001000 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +00001001 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00001002
George Burgess IV8c892b52016-05-25 22:31:54 +00001003 /// Notes that we failed to evaluate an expression that other expressions
1004 /// directly depend on, and determine if we should keep evaluating. This
1005 /// should only be called if we actually intend to keep evaluating.
1006 ///
1007 /// Call noteSideEffect() instead if we may be able to ignore the value that
1008 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1009 ///
1010 /// (Foo(), 1) // use noteSideEffect
1011 /// (Foo() || true) // use noteSideEffect
1012 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +00001013 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001014 // Failure when evaluating some expression often means there is some
1015 // subexpression whose evaluation was skipped. Therefore, (because we
1016 // don't track whether we skipped an expression when unwinding after an
1017 // evaluation failure) every evaluation failure that bubbles up from a
1018 // subexpression implies that a side-effect has potentially happened. We
1019 // skip setting the HasSideEffects flag to true until we decide to
1020 // continue evaluating after that point, which happens here.
1021 bool KeepGoing = keepEvaluatingAfterFailure();
1022 EvalStatus.HasSideEffects |= KeepGoing;
1023 return KeepGoing;
1024 }
1025
Richard Smith410306b2016-12-12 02:53:20 +00001026 class ArrayInitLoopIndex {
1027 EvalInfo &Info;
1028 uint64_t OuterIndex;
1029
1030 public:
1031 ArrayInitLoopIndex(EvalInfo &Info)
1032 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1033 Info.ArrayInitIndex = 0;
1034 }
1035 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1036
1037 operator uint64_t&() { return Info.ArrayInitIndex; }
1038 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001039 };
Richard Smith84f6dcf2012-02-02 01:16:57 +00001040
1041 /// Object used to treat all foldable expressions as constant expressions.
1042 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +00001043 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001044 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +00001045 bool HadNoPriorDiags;
1046 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001047
Richard Smith6d4c6582013-11-05 22:18:15 +00001048 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1049 : Info(Info),
1050 Enabled(Enabled),
1051 HadNoPriorDiags(Info.EvalStatus.Diag &&
1052 Info.EvalStatus.Diag->empty() &&
1053 !Info.EvalStatus.HasSideEffects),
1054 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001055 if (Enabled &&
1056 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1057 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001058 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001059 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001060 void keepDiagnostics() { Enabled = false; }
1061 ~FoldConstant() {
1062 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001063 !Info.EvalStatus.HasSideEffects)
1064 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001065 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001066 }
1067 };
Richard Smith17100ba2012-02-16 02:46:34 +00001068
George Burgess IV3a03fab2015-09-04 21:28:13 +00001069 /// RAII object used to treat the current evaluation as the correct pointer
1070 /// offset fold for the current EvalMode
1071 struct FoldOffsetRAII {
1072 EvalInfo &Info;
1073 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +00001074 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001075 : Info(Info), OldMode(Info.EvalMode) {
1076 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +00001077 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001078 }
1079
1080 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1081 };
1082
George Burgess IV8c892b52016-05-25 22:31:54 +00001083 /// RAII object used to optionally suppress diagnostics and side-effects from
1084 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001085 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001086 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001087 Expr::EvalStatus OldStatus;
1088 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001089
George Burgess IV8c892b52016-05-25 22:31:54 +00001090 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001091 Info = Other.Info;
1092 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001093 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001094 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001095 }
1096
1097 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001098 if (!Info)
1099 return;
1100
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001101 Info->EvalStatus = OldStatus;
1102 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001103 }
1104
Richard Smith17100ba2012-02-16 02:46:34 +00001105 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001106 SpeculativeEvaluationRAII() = default;
1107
1108 SpeculativeEvaluationRAII(
1109 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001110 : Info(&Info), OldStatus(Info.EvalStatus),
1111 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001112 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001113 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001114 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001115
1116 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1117 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1118 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001119 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001120
1121 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1122 maybeRestoreState();
1123 moveFromAndCancel(std::move(Other));
1124 return *this;
1125 }
1126
1127 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001128 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001129
1130 /// RAII object wrapping a full-expression or block scope, and handling
1131 /// the ending of the lifetime of temporaries created within it.
1132 template<bool IsFullExpression>
1133 class ScopeRAII {
1134 EvalInfo &Info;
1135 unsigned OldStackSize;
1136 public:
1137 ScopeRAII(EvalInfo &Info)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001138 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1139 // Push a new temporary version. This is needed to distinguish between
1140 // temporaries created in different iterations of a loop.
1141 Info.CurrentCall->pushTempVersion();
1142 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00001143 ~ScopeRAII() {
1144 // Body moved to a static method to encourage the compiler to inline away
1145 // instances of this class.
1146 cleanup(Info, OldStackSize);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001147 Info.CurrentCall->popTempVersion();
Richard Smith08d6a2c2013-07-24 07:11:57 +00001148 }
1149 private:
1150 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1151 unsigned NewEnd = OldStackSize;
1152 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1153 I != N; ++I) {
1154 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1155 // Full-expression cleanup of a lifetime-extended temporary: nothing
1156 // to do, just move this cleanup to the right place in the stack.
1157 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1158 ++NewEnd;
1159 } else {
1160 // End the lifetime of the object.
1161 Info.CleanupStack[I].endLifetime();
1162 }
1163 }
1164 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1165 Info.CleanupStack.end());
1166 }
1167 };
1168 typedef ScopeRAII<false> BlockScopeRAII;
1169 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001170}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001171
Richard Smitha8105bc2012-01-06 16:39:00 +00001172bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1173 CheckSubobjectKind CSK) {
1174 if (Invalid)
1175 return false;
1176 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001177 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001178 << CSK;
1179 setInvalid();
1180 return false;
1181 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001182 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1183 // must actually be at least one array element; even a VLA cannot have a
1184 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001185 return true;
1186}
1187
Richard Smith6f4f0f12017-10-20 22:56:25 +00001188void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1189 const Expr *E) {
1190 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1191 // Do not set the designator as invalid: we can represent this situation,
1192 // and correct handling of __builtin_object_size requires us to do so.
1193}
1194
Richard Smitha8105bc2012-01-06 16:39:00 +00001195void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001196 const Expr *E,
1197 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001198 // If we're complaining, we must be able to statically determine the size of
1199 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001200 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001201 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001202 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001203 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001204 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001205 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001206 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001207 setInvalid();
1208}
1209
Richard Smithf6f003a2011-12-16 19:06:07 +00001210CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1211 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001212 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001213 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1214 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001215 Info.CurrentCall = this;
1216 ++Info.CallStackDepth;
1217}
1218
1219CallStackFrame::~CallStackFrame() {
1220 assert(Info.CurrentCall == this && "calls retired out of order");
1221 --Info.CallStackDepth;
1222 Info.CurrentCall = Caller;
1223}
1224
Richard Smith08d6a2c2013-07-24 07:11:57 +00001225APValue &CallStackFrame::createTemporary(const void *Key,
1226 bool IsLifetimeExtended) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001227 unsigned Version = Info.CurrentCall->getTempVersion();
1228 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
Richard Smith08d6a2c2013-07-24 07:11:57 +00001229 assert(Result.isUninit() && "temporary created multiple times");
1230 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1231 return Result;
1232}
1233
Richard Smith84401042013-06-03 05:03:02 +00001234static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001235
1236void EvalInfo::addCallStack(unsigned Limit) {
1237 // Determine which calls to skip, if any.
1238 unsigned ActiveCalls = CallStackDepth - 1;
1239 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1240 if (Limit && Limit < ActiveCalls) {
1241 SkipStart = Limit / 2 + Limit % 2;
1242 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001243 }
1244
Richard Smithf6f003a2011-12-16 19:06:07 +00001245 // Walk the call stack and add the diagnostics.
1246 unsigned CallIdx = 0;
1247 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1248 Frame = Frame->Caller, ++CallIdx) {
1249 // Skip this call?
1250 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1251 if (CallIdx == SkipStart) {
1252 // Note that we're skipping calls.
1253 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1254 << unsigned(ActiveCalls - Limit);
1255 }
1256 continue;
1257 }
1258
Richard Smith5179eb72016-06-28 19:03:57 +00001259 // Use a different note for an inheriting constructor, because from the
1260 // user's perspective it's not really a function at all.
1261 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1262 if (CD->isInheritingConstructor()) {
1263 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1264 << CD->getParent();
1265 continue;
1266 }
1267 }
1268
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001269 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001270 llvm::raw_svector_ostream Out(Buffer);
1271 describeCall(Frame, Out);
1272 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1273 }
1274}
1275
1276namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001277 struct ComplexValue {
1278 private:
1279 bool IsInt;
1280
1281 public:
1282 APSInt IntReal, IntImag;
1283 APFloat FloatReal, FloatImag;
1284
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001285 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001286
1287 void makeComplexFloat() { IsInt = false; }
1288 bool isComplexFloat() const { return !IsInt; }
1289 APFloat &getComplexFloatReal() { return FloatReal; }
1290 APFloat &getComplexFloatImag() { return FloatImag; }
1291
1292 void makeComplexInt() { IsInt = true; }
1293 bool isComplexInt() const { return IsInt; }
1294 APSInt &getComplexIntReal() { return IntReal; }
1295 APSInt &getComplexIntImag() { return IntImag; }
1296
Richard Smith2e312c82012-03-03 22:46:17 +00001297 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001298 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001299 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001300 else
Richard Smith2e312c82012-03-03 22:46:17 +00001301 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001302 }
Richard Smith2e312c82012-03-03 22:46:17 +00001303 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001304 assert(v.isComplexFloat() || v.isComplexInt());
1305 if (v.isComplexFloat()) {
1306 makeComplexFloat();
1307 FloatReal = v.getComplexFloatReal();
1308 FloatImag = v.getComplexFloatImag();
1309 } else {
1310 makeComplexInt();
1311 IntReal = v.getComplexIntReal();
1312 IntImag = v.getComplexIntImag();
1313 }
1314 }
John McCall93d91dc2010-05-07 17:22:02 +00001315 };
John McCall45d55e42010-05-07 21:00:08 +00001316
1317 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001318 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001319 CharUnits Offset;
Richard Smith96e0c102011-11-04 02:25:55 +00001320 SubobjectDesignator Designator;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001321 bool IsNullPtr : 1;
1322 bool InvalidBase : 1;
John McCall45d55e42010-05-07 21:00:08 +00001323
Richard Smithce40ad62011-11-12 22:28:03 +00001324 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001325 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001326 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith96e0c102011-11-04 02:25:55 +00001327 SubobjectDesignator &getLValueDesignator() { return Designator; }
1328 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001329 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001330
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001331 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1332 unsigned getLValueVersion() const { return Base.getVersion(); }
1333
Richard Smith2e312c82012-03-03 22:46:17 +00001334 void moveInto(APValue &V) const {
1335 if (Designator.Invalid)
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001336 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001337 else {
1338 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001339 V = APValue(Base, Offset, Designator.Entries,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001340 Designator.IsOnePastTheEnd, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001341 }
John McCall45d55e42010-05-07 21:00:08 +00001342 }
Richard Smith2e312c82012-03-03 22:46:17 +00001343 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001344 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001345 Base = V.getLValueBase();
1346 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001347 InvalidBase = false;
Richard Smith2e312c82012-03-03 22:46:17 +00001348 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001349 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001350 }
1351
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001352 void set(APValue::LValueBase B, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001353#ifndef NDEBUG
1354 // We only allow a few types of invalid bases. Enforce that here.
1355 if (BInvalid) {
1356 const auto *E = B.get<const Expr *>();
1357 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1358 "Unexpected type of invalid base");
1359 }
1360#endif
1361
Richard Smithce40ad62011-11-12 22:28:03 +00001362 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001363 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001364 InvalidBase = BInvalid;
Richard Smitha8105bc2012-01-06 16:39:00 +00001365 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001366 IsNullPtr = false;
1367 }
1368
1369 void setNull(QualType PointerTy, uint64_t TargetVal) {
1370 Base = (Expr *)nullptr;
1371 Offset = CharUnits::fromQuantity(TargetVal);
1372 InvalidBase = false;
Tim Northover01503332017-05-26 02:16:00 +00001373 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1374 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001375 }
1376
George Burgess IV3a03fab2015-09-04 21:28:13 +00001377 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001378 set(B, true);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001379 }
1380
Richard Smitha8105bc2012-01-06 16:39:00 +00001381 // Check that this LValue is not based on a null pointer. If it is, produce
1382 // a diagnostic and mark the designator as invalid.
1383 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1384 CheckSubobjectKind CSK) {
1385 if (Designator.Invalid)
1386 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001387 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001388 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001389 << CSK;
1390 Designator.setInvalid();
1391 return false;
1392 }
1393 return true;
1394 }
1395
1396 // Check this LValue refers to an object. If not, set the designator to be
1397 // invalid and emit a diagnostic.
1398 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001399 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001400 Designator.checkSubobject(Info, E, CSK);
1401 }
1402
1403 void addDecl(EvalInfo &Info, const Expr *E,
1404 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001405 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1406 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001407 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001408 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1409 if (!Designator.Entries.empty()) {
1410 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1411 Designator.setInvalid();
1412 return;
1413 }
Richard Smithefdb5032017-11-15 03:03:56 +00001414 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1415 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1416 Designator.FirstEntryIsAnUnsizedArray = true;
1417 Designator.addUnsizedArrayUnchecked(ElemTy);
1418 }
George Burgess IVe3763372016-12-22 02:50:20 +00001419 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001420 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001421 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1422 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001423 }
Richard Smith66c96992012-02-18 22:04:06 +00001424 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001425 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1426 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001427 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001428 void clearIsNullPointer() {
1429 IsNullPtr = false;
1430 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001431 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1432 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001433 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1434 // but we're not required to diagnose it and it's valid in C++.)
1435 if (!Index)
1436 return;
1437
1438 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1439 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1440 // offsets.
1441 uint64_t Offset64 = Offset.getQuantity();
1442 uint64_t ElemSize64 = ElementSize.getQuantity();
1443 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1444 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1445
1446 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001447 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001448 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001449 }
1450 void adjustOffset(CharUnits N) {
1451 Offset += N;
1452 if (N.getQuantity())
1453 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001454 }
John McCall45d55e42010-05-07 21:00:08 +00001455 };
Richard Smith027bf112011-11-17 22:56:20 +00001456
1457 struct MemberPtr {
1458 MemberPtr() {}
1459 explicit MemberPtr(const ValueDecl *Decl) :
1460 DeclAndIsDerivedMember(Decl, false), Path() {}
1461
1462 /// The member or (direct or indirect) field referred to by this member
1463 /// pointer, or 0 if this is a null member pointer.
1464 const ValueDecl *getDecl() const {
1465 return DeclAndIsDerivedMember.getPointer();
1466 }
1467 /// Is this actually a member of some type derived from the relevant class?
1468 bool isDerivedMember() const {
1469 return DeclAndIsDerivedMember.getInt();
1470 }
1471 /// Get the class which the declaration actually lives in.
1472 const CXXRecordDecl *getContainingRecord() const {
1473 return cast<CXXRecordDecl>(
1474 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1475 }
1476
Richard Smith2e312c82012-03-03 22:46:17 +00001477 void moveInto(APValue &V) const {
1478 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001479 }
Richard Smith2e312c82012-03-03 22:46:17 +00001480 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001481 assert(V.isMemberPointer());
1482 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1483 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1484 Path.clear();
1485 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1486 Path.insert(Path.end(), P.begin(), P.end());
1487 }
1488
1489 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1490 /// whether the member is a member of some class derived from the class type
1491 /// of the member pointer.
1492 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1493 /// Path - The path of base/derived classes from the member declaration's
1494 /// class (exclusive) to the class type of the member pointer (inclusive).
1495 SmallVector<const CXXRecordDecl*, 4> Path;
1496
1497 /// Perform a cast towards the class of the Decl (either up or down the
1498 /// hierarchy).
1499 bool castBack(const CXXRecordDecl *Class) {
1500 assert(!Path.empty());
1501 const CXXRecordDecl *Expected;
1502 if (Path.size() >= 2)
1503 Expected = Path[Path.size() - 2];
1504 else
1505 Expected = getContainingRecord();
1506 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1507 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1508 // if B does not contain the original member and is not a base or
1509 // derived class of the class containing the original member, the result
1510 // of the cast is undefined.
1511 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1512 // (D::*). We consider that to be a language defect.
1513 return false;
1514 }
1515 Path.pop_back();
1516 return true;
1517 }
1518 /// Perform a base-to-derived member pointer cast.
1519 bool castToDerived(const CXXRecordDecl *Derived) {
1520 if (!getDecl())
1521 return true;
1522 if (!isDerivedMember()) {
1523 Path.push_back(Derived);
1524 return true;
1525 }
1526 if (!castBack(Derived))
1527 return false;
1528 if (Path.empty())
1529 DeclAndIsDerivedMember.setInt(false);
1530 return true;
1531 }
1532 /// Perform a derived-to-base member pointer cast.
1533 bool castToBase(const CXXRecordDecl *Base) {
1534 if (!getDecl())
1535 return true;
1536 if (Path.empty())
1537 DeclAndIsDerivedMember.setInt(true);
1538 if (isDerivedMember()) {
1539 Path.push_back(Base);
1540 return true;
1541 }
1542 return castBack(Base);
1543 }
1544 };
Richard Smith357362d2011-12-13 06:39:58 +00001545
Richard Smith7bb00672012-02-01 01:42:44 +00001546 /// Compare two member pointers, which are assumed to be of the same type.
1547 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1548 if (!LHS.getDecl() || !RHS.getDecl())
1549 return !LHS.getDecl() && !RHS.getDecl();
1550 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1551 return false;
1552 return LHS.Path == RHS.Path;
1553 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001554}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001555
Richard Smith2e312c82012-03-03 22:46:17 +00001556static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001557static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1558 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001559 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001560static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1561 bool InvalidBaseOK = false);
1562static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1563 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001564static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1565 EvalInfo &Info);
1566static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001567static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001568static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001569 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001570static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001571static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001572static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1573 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001574static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001575
1576//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001577// Misc utilities
1578//===----------------------------------------------------------------------===//
1579
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001580/// A helper function to create a temporary and set an LValue.
1581template <class KeyTy>
1582static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1583 LValue &LV, CallStackFrame &Frame) {
1584 LV.set({Key, Frame.Info.CurrentCall->Index,
1585 Frame.Info.CurrentCall->getTempVersion()});
1586 return Frame.createTemporary(Key, IsLifetimeExtended);
1587}
1588
Richard Smithd6cc1982017-01-31 02:23:02 +00001589/// Negate an APSInt in place, converting it to a signed form if necessary, and
1590/// preserving its value (by extending by up to one bit as needed).
1591static void negateAsSigned(APSInt &Int) {
1592 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1593 Int = Int.extend(Int.getBitWidth() + 1);
1594 Int.setIsSigned(true);
1595 }
1596 Int = -Int;
1597}
1598
Richard Smith84401042013-06-03 05:03:02 +00001599/// Produce a string describing the given constexpr call.
1600static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1601 unsigned ArgIndex = 0;
1602 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1603 !isa<CXXConstructorDecl>(Frame->Callee) &&
1604 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1605
1606 if (!IsMemberCall)
1607 Out << *Frame->Callee << '(';
1608
1609 if (Frame->This && IsMemberCall) {
1610 APValue Val;
1611 Frame->This->moveInto(Val);
1612 Val.printPretty(Out, Frame->Info.Ctx,
1613 Frame->This->Designator.MostDerivedType);
1614 // FIXME: Add parens around Val if needed.
1615 Out << "->" << *Frame->Callee << '(';
1616 IsMemberCall = false;
1617 }
1618
1619 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1620 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1621 if (ArgIndex > (unsigned)IsMemberCall)
1622 Out << ", ";
1623
1624 const ParmVarDecl *Param = *I;
1625 const APValue &Arg = Frame->Arguments[ArgIndex];
1626 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1627
1628 if (ArgIndex == 0 && IsMemberCall)
1629 Out << "->" << *Frame->Callee << '(';
1630 }
1631
1632 Out << ')';
1633}
1634
Richard Smithd9f663b2013-04-22 15:31:51 +00001635/// Evaluate an expression to see if it had side-effects, and discard its
1636/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001637/// \return \c true if the caller should keep evaluating.
1638static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001639 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001640 if (!Evaluate(Scratch, Info, E))
1641 // We don't need the value, but we might have skipped a side effect here.
1642 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001643 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001644}
1645
Richard Smithd62306a2011-11-10 06:34:14 +00001646/// Should this call expression be treated as a string literal?
1647static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001648 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001649 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1650 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1651}
1652
Richard Smithce40ad62011-11-12 22:28:03 +00001653static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001654 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1655 // constant expression of pointer type that evaluates to...
1656
1657 // ... a null pointer value, or a prvalue core constant expression of type
1658 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001659 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001660
Richard Smithce40ad62011-11-12 22:28:03 +00001661 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1662 // ... the address of an object with static storage duration,
1663 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1664 return VD->hasGlobalStorage();
1665 // ... the address of a function,
1666 return isa<FunctionDecl>(D);
1667 }
1668
1669 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001670 switch (E->getStmtClass()) {
1671 default:
1672 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001673 case Expr::CompoundLiteralExprClass: {
1674 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1675 return CLE->isFileScope() && CLE->isLValue();
1676 }
Richard Smithe6c01442013-06-05 00:46:14 +00001677 case Expr::MaterializeTemporaryExprClass:
1678 // A materialized temporary might have been lifetime-extended to static
1679 // storage duration.
1680 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001681 // A string literal has static storage duration.
1682 case Expr::StringLiteralClass:
1683 case Expr::PredefinedExprClass:
1684 case Expr::ObjCStringLiteralClass:
1685 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001686 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001687 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001688 return true;
1689 case Expr::CallExprClass:
1690 return IsStringLiteralCall(cast<CallExpr>(E));
1691 // For GCC compatibility, &&label has static storage duration.
1692 case Expr::AddrLabelExprClass:
1693 return true;
1694 // A Block literal expression may be used as the initialization value for
1695 // Block variables at global or local static scope.
1696 case Expr::BlockExprClass:
1697 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001698 case Expr::ImplicitValueInitExprClass:
1699 // FIXME:
1700 // We can never form an lvalue with an implicit value initialization as its
1701 // base through expression evaluation, so these only appear in one case: the
1702 // implicit variable declaration we invent when checking whether a constexpr
1703 // constructor can produce a constant expression. We must assume that such
1704 // an expression might be a global lvalue.
1705 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001706 }
John McCall95007602010-05-10 23:27:23 +00001707}
1708
Richard Smithb228a862012-02-15 02:18:13 +00001709static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1710 assert(Base && "no location for a null lvalue");
1711 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1712 if (VD)
1713 Info.Note(VD->getLocation(), diag::note_declared_at);
1714 else
Ted Kremenek28831752012-08-23 20:46:57 +00001715 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001716 diag::note_constexpr_temporary_here);
1717}
1718
Richard Smith80815602011-11-07 05:07:52 +00001719/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001720/// value for an address or reference constant expression. Return true if we
1721/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001722static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1723 QualType Type, const LValue &LVal) {
1724 bool IsReferenceType = Type->isReferenceType();
1725
Richard Smith357362d2011-12-13 06:39:58 +00001726 APValue::LValueBase Base = LVal.getLValueBase();
1727 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1728
Richard Smith0dea49e2012-02-18 04:58:18 +00001729 // Check that the object is a global. Note that the fake 'this' object we
1730 // manufacture when checking potential constant expressions is conservatively
1731 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001732 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001733 if (Info.getLangOpts().CPlusPlus11) {
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_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001736 << IsReferenceType << !Designator.Entries.empty()
1737 << !!VD << VD;
1738 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001739 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001740 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001741 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001742 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001743 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001744 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001745 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001746 LVal.getLValueCallIndex() == 0) &&
1747 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001748
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001749 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1750 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001751 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001752 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001753 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001754
Hans Wennborg82dd8772014-06-25 22:19:48 +00001755 // A dllimport variable never acts like a constant.
1756 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001757 return false;
1758 }
1759 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1760 // __declspec(dllimport) must be handled very carefully:
1761 // We must never initialize an expression with the thunk in C++.
1762 // Doing otherwise would allow the same id-expression to yield
1763 // different addresses for the same function in different translation
1764 // units. However, this means that we must dynamically initialize the
1765 // expression with the contents of the import address table at runtime.
1766 //
1767 // The C language has no notion of ODR; furthermore, it has no notion of
1768 // dynamic initialization. This means that we are permitted to
1769 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001770 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001771 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001772 }
1773 }
1774
Richard Smitha8105bc2012-01-06 16:39:00 +00001775 // Allow address constant expressions to be past-the-end pointers. This is
1776 // an extension: the standard requires them to point to an object.
1777 if (!IsReferenceType)
1778 return true;
1779
1780 // A reference constant expression must refer to an object.
1781 if (!Base) {
1782 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001783 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001784 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001785 }
1786
Richard Smith357362d2011-12-13 06:39:58 +00001787 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001788 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001789 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001790 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001791 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001792 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001793 }
1794
Richard Smith80815602011-11-07 05:07:52 +00001795 return true;
1796}
1797
Reid Klecknercd016d82017-07-07 22:04:29 +00001798/// Member pointers are constant expressions unless they point to a
1799/// non-virtual dllimport member function.
1800static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1801 SourceLocation Loc,
1802 QualType Type,
1803 const APValue &Value) {
1804 const ValueDecl *Member = Value.getMemberPointerDecl();
1805 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1806 if (!FD)
1807 return true;
1808 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1809}
1810
Richard Smithfddd3842011-12-30 21:15:51 +00001811/// Check that this core constant expression is of literal type, and if not,
1812/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001813static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001814 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001815 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001816 return true;
1817
Richard Smith7525ff62013-05-09 07:14:00 +00001818 // C++1y: A constant initializer for an object o [...] may also invoke
1819 // constexpr constructors for o and its subobjects even if those objects
1820 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001821 //
1822 // C++11 missed this detail for aggregates, so classes like this:
1823 // struct foo_t { union { int i; volatile int j; } u; };
1824 // are not (obviously) initializable like so:
1825 // __attribute__((__require_constant_initialization__))
1826 // static const foo_t x = {{0}};
1827 // because "i" is a subobject with non-literal initialization (due to the
1828 // volatile member of the union). See:
1829 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1830 // Therefore, we use the C++1y behavior.
1831 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001832 return true;
1833
Richard Smithfddd3842011-12-30 21:15:51 +00001834 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001835 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001836 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001837 << E->getType();
1838 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001839 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001840 return false;
1841}
1842
Richard Smith0b0a0b62011-10-29 20:57:55 +00001843/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001844/// constant expression. If not, report an appropriate diagnostic. Does not
1845/// check that the expression is of literal type.
1846static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1847 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001848 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001849 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001850 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001851 return false;
1852 }
1853
Richard Smith77be48a2014-07-31 06:31:19 +00001854 // We allow _Atomic(T) to be initialized from anything that T can be
1855 // initialized from.
1856 if (const AtomicType *AT = Type->getAs<AtomicType>())
1857 Type = AT->getValueType();
1858
Richard Smithb228a862012-02-15 02:18:13 +00001859 // Core issue 1454: For a literal constant expression of array or class type,
1860 // each subobject of its value shall have been initialized by a constant
1861 // expression.
1862 if (Value.isArray()) {
1863 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1864 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1865 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1866 Value.getArrayInitializedElt(I)))
1867 return false;
1868 }
1869 if (!Value.hasArrayFiller())
1870 return true;
1871 return CheckConstantExpression(Info, DiagLoc, EltTy,
1872 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001873 }
Richard Smithb228a862012-02-15 02:18:13 +00001874 if (Value.isUnion() && Value.getUnionField()) {
1875 return CheckConstantExpression(Info, DiagLoc,
1876 Value.getUnionField()->getType(),
1877 Value.getUnionValue());
1878 }
1879 if (Value.isStruct()) {
1880 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1881 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1882 unsigned BaseIndex = 0;
1883 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1884 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1885 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1886 Value.getStructBase(BaseIndex)))
1887 return false;
1888 }
1889 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001890 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001891 if (I->isUnnamedBitfield())
1892 continue;
1893
David Blaikie2d7c57e2012-04-30 02:36:29 +00001894 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1895 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001896 return false;
1897 }
1898 }
1899
1900 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001901 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001902 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001903 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1904 }
1905
Reid Klecknercd016d82017-07-07 22:04:29 +00001906 if (Value.isMemberPointer())
1907 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1908
Richard Smithb228a862012-02-15 02:18:13 +00001909 // Everything else is fine.
1910 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001911}
1912
Benjamin Kramer8407df72015-03-09 16:47:52 +00001913static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001914 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001915}
1916
1917static bool IsLiteralLValue(const LValue &Value) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00001918 if (Value.getLValueCallIndex())
Richard Smithe6c01442013-06-05 00:46:14 +00001919 return false;
1920 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1921 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001922}
1923
Richard Smithcecf1842011-11-01 21:06:14 +00001924static bool IsWeakLValue(const LValue &Value) {
1925 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001926 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001927}
1928
David Majnemerb5116032014-12-09 23:32:34 +00001929static bool isZeroSized(const LValue &Value) {
1930 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001931 if (Decl && isa<VarDecl>(Decl)) {
1932 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001933 if (Ty->isArrayType())
1934 return Ty->isIncompleteType() ||
1935 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001936 }
1937 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001938}
1939
Richard Smith2e312c82012-03-03 22:46:17 +00001940static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001941 // A null base expression indicates a null pointer. These are always
1942 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001943 if (!Value.getLValueBase()) {
1944 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001945 return true;
1946 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001947
Richard Smith027bf112011-11-17 22:56:20 +00001948 // We have a non-null base. These are generally known to be true, but if it's
1949 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001950 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001951 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001952 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001953}
1954
Richard Smith2e312c82012-03-03 22:46:17 +00001955static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001956 switch (Val.getKind()) {
1957 case APValue::Uninitialized:
1958 return false;
1959 case APValue::Int:
1960 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001961 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001962 case APValue::Float:
1963 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001964 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001965 case APValue::ComplexInt:
1966 Result = Val.getComplexIntReal().getBoolValue() ||
1967 Val.getComplexIntImag().getBoolValue();
1968 return true;
1969 case APValue::ComplexFloat:
1970 Result = !Val.getComplexFloatReal().isZero() ||
1971 !Val.getComplexFloatImag().isZero();
1972 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001973 case APValue::LValue:
1974 return EvalPointerValueAsBool(Val, Result);
1975 case APValue::MemberPointer:
1976 Result = Val.getMemberPointerDecl();
1977 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001978 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001979 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001980 case APValue::Struct:
1981 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001982 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001983 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001984 }
1985
Richard Smith11562c52011-10-28 17:51:58 +00001986 llvm_unreachable("unknown APValue kind");
1987}
1988
1989static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1990 EvalInfo &Info) {
1991 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001992 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001993 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001994 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001995 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001996}
1997
Richard Smith357362d2011-12-13 06:39:58 +00001998template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001999static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00002000 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00002001 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00002002 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00002003 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00002004}
2005
2006static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2007 QualType SrcType, const APFloat &Value,
2008 QualType DestType, APSInt &Result) {
2009 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002010 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002011 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00002012
Richard Smith357362d2011-12-13 06:39:58 +00002013 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002014 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002015 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2016 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00002017 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002018 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002019}
2020
Richard Smith357362d2011-12-13 06:39:58 +00002021static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2022 QualType SrcType, QualType DestType,
2023 APFloat &Result) {
2024 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002025 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00002026 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2027 APFloat::rmNearestTiesToEven, &ignored)
2028 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002029 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002030 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002031}
2032
Richard Smith911e1422012-01-30 22:27:01 +00002033static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2034 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00002035 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00002036 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002037 APSInt Result = Value;
2038 // Figure out if this is a truncate, extend or noop cast.
2039 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00002040 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002041 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002042 return Result;
2043}
2044
Richard Smith357362d2011-12-13 06:39:58 +00002045static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2046 QualType SrcType, const APSInt &Value,
2047 QualType DestType, APFloat &Result) {
2048 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2049 if (Result.convertFromAPInt(Value, Value.isSigned(),
2050 APFloat::rmNearestTiesToEven)
2051 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00002052 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00002053 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002054}
2055
Richard Smith49ca8aa2013-08-06 07:09:20 +00002056static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2057 APValue &Value, const FieldDecl *FD) {
2058 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2059
2060 if (!Value.isInt()) {
2061 // Trying to store a pointer-cast-to-integer into a bitfield.
2062 // FIXME: In this case, we should provide the diagnostic for casting
2063 // a pointer to an integer.
2064 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00002065 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00002066 return false;
2067 }
2068
2069 APSInt &Int = Value.getInt();
2070 unsigned OldBitWidth = Int.getBitWidth();
2071 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2072 if (NewBitWidth < OldBitWidth)
2073 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2074 return true;
2075}
2076
Eli Friedman803acb32011-12-22 03:51:45 +00002077static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2078 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002079 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002080 if (!Evaluate(SVal, Info, E))
2081 return false;
2082 if (SVal.isInt()) {
2083 Res = SVal.getInt();
2084 return true;
2085 }
2086 if (SVal.isFloat()) {
2087 Res = SVal.getFloat().bitcastToAPInt();
2088 return true;
2089 }
2090 if (SVal.isVector()) {
2091 QualType VecTy = E->getType();
2092 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2093 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2094 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2095 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2096 Res = llvm::APInt::getNullValue(VecSize);
2097 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2098 APValue &Elt = SVal.getVectorElt(i);
2099 llvm::APInt EltAsInt;
2100 if (Elt.isInt()) {
2101 EltAsInt = Elt.getInt();
2102 } else if (Elt.isFloat()) {
2103 EltAsInt = Elt.getFloat().bitcastToAPInt();
2104 } else {
2105 // Don't try to handle vectors of anything other than int or float
2106 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002107 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002108 return false;
2109 }
2110 unsigned BaseEltSize = EltAsInt.getBitWidth();
2111 if (BigEndian)
2112 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2113 else
2114 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2115 }
2116 return true;
2117 }
2118 // Give up if the input isn't an int, float, or vector. For example, we
2119 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002120 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002121 return false;
2122}
2123
Richard Smith43e77732013-05-07 04:50:00 +00002124/// Perform the given integer operation, which is known to need at most BitWidth
2125/// bits, and check for overflow in the original type (if that type was not an
2126/// unsigned type).
2127template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002128static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2129 const APSInt &LHS, const APSInt &RHS,
2130 unsigned BitWidth, Operation Op,
2131 APSInt &Result) {
2132 if (LHS.isUnsigned()) {
2133 Result = Op(LHS, RHS);
2134 return true;
2135 }
Richard Smith43e77732013-05-07 04:50:00 +00002136
2137 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002138 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002139 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002140 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002141 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002142 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002143 << Result.toString(10) << E->getType();
2144 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002145 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002146 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002147 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002148}
2149
2150/// Perform the given binary integer operation.
2151static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2152 BinaryOperatorKind Opcode, APSInt RHS,
2153 APSInt &Result) {
2154 switch (Opcode) {
2155 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002156 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002157 return false;
2158 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002159 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2160 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002161 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002162 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2163 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002164 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002165 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2166 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002167 case BO_And: Result = LHS & RHS; return true;
2168 case BO_Xor: Result = LHS ^ RHS; return true;
2169 case BO_Or: Result = LHS | RHS; return true;
2170 case BO_Div:
2171 case BO_Rem:
2172 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002173 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002174 return false;
2175 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002176 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2177 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2178 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002179 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2180 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002181 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2182 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002183 return true;
2184 case BO_Shl: {
2185 if (Info.getLangOpts().OpenCL)
2186 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2187 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2188 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2189 RHS.isUnsigned());
2190 else if (RHS.isSigned() && RHS.isNegative()) {
2191 // During constant-folding, a negative shift is an opposite shift. Such
2192 // a shift is not a constant expression.
2193 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2194 RHS = -RHS;
2195 goto shift_right;
2196 }
2197 shift_left:
2198 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2199 // the shifted type.
2200 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2201 if (SA != RHS) {
2202 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2203 << RHS << E->getType() << LHS.getBitWidth();
2204 } else if (LHS.isSigned()) {
2205 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2206 // operand, and must not overflow the corresponding unsigned type.
2207 if (LHS.isNegative())
2208 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2209 else if (LHS.countLeadingZeros() < SA)
2210 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2211 }
2212 Result = LHS << SA;
2213 return true;
2214 }
2215 case BO_Shr: {
2216 if (Info.getLangOpts().OpenCL)
2217 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2218 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2219 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2220 RHS.isUnsigned());
2221 else if (RHS.isSigned() && RHS.isNegative()) {
2222 // During constant-folding, a negative shift is an opposite shift. Such a
2223 // shift is not a constant expression.
2224 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2225 RHS = -RHS;
2226 goto shift_left;
2227 }
2228 shift_right:
2229 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2230 // shifted type.
2231 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2232 if (SA != RHS)
2233 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2234 << RHS << E->getType() << LHS.getBitWidth();
2235 Result = LHS >> SA;
2236 return true;
2237 }
2238
2239 case BO_LT: Result = LHS < RHS; return true;
2240 case BO_GT: Result = LHS > RHS; return true;
2241 case BO_LE: Result = LHS <= RHS; return true;
2242 case BO_GE: Result = LHS >= RHS; return true;
2243 case BO_EQ: Result = LHS == RHS; return true;
2244 case BO_NE: Result = LHS != RHS; return true;
2245 }
2246}
2247
Richard Smith861b5b52013-05-07 23:34:45 +00002248/// Perform the given binary floating-point operation, in-place, on LHS.
2249static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2250 APFloat &LHS, BinaryOperatorKind Opcode,
2251 const APFloat &RHS) {
2252 switch (Opcode) {
2253 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002254 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002255 return false;
2256 case BO_Mul:
2257 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2258 break;
2259 case BO_Add:
2260 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2261 break;
2262 case BO_Sub:
2263 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2264 break;
2265 case BO_Div:
2266 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2267 break;
2268 }
2269
Richard Smith0c6124b2015-12-03 01:36:22 +00002270 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002271 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002272 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002273 }
Richard Smith861b5b52013-05-07 23:34:45 +00002274 return true;
2275}
2276
Richard Smitha8105bc2012-01-06 16:39:00 +00002277/// Cast an lvalue referring to a base subobject to a derived class, by
2278/// truncating the lvalue's path to the given length.
2279static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2280 const RecordDecl *TruncatedType,
2281 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002282 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002283
2284 // Check we actually point to a derived class object.
2285 if (TruncatedElements == D.Entries.size())
2286 return true;
2287 assert(TruncatedElements >= D.MostDerivedPathLength &&
2288 "not casting to a derived class");
2289 if (!Result.checkSubobject(Info, E, CSK_Derived))
2290 return false;
2291
2292 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002293 const RecordDecl *RD = TruncatedType;
2294 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002295 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002296 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2297 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002298 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002299 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002300 else
Richard Smithd62306a2011-11-10 06:34:14 +00002301 Result.Offset -= Layout.getBaseClassOffset(Base);
2302 RD = Base;
2303 }
Richard Smith027bf112011-11-17 22:56:20 +00002304 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002305 return true;
2306}
2307
John McCalld7bca762012-05-01 00:38:49 +00002308static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002309 const CXXRecordDecl *Derived,
2310 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002311 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002312 if (!RL) {
2313 if (Derived->isInvalidDecl()) return false;
2314 RL = &Info.Ctx.getASTRecordLayout(Derived);
2315 }
2316
Richard Smithd62306a2011-11-10 06:34:14 +00002317 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002318 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002319 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002320}
2321
Richard Smitha8105bc2012-01-06 16:39:00 +00002322static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002323 const CXXRecordDecl *DerivedDecl,
2324 const CXXBaseSpecifier *Base) {
2325 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2326
John McCalld7bca762012-05-01 00:38:49 +00002327 if (!Base->isVirtual())
2328 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002329
Richard Smitha8105bc2012-01-06 16:39:00 +00002330 SubobjectDesignator &D = Obj.Designator;
2331 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002332 return false;
2333
Richard Smitha8105bc2012-01-06 16:39:00 +00002334 // Extract most-derived object and corresponding type.
2335 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2336 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2337 return false;
2338
2339 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002340 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002341 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2342 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002343 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002344 return true;
2345}
2346
Richard Smith84401042013-06-03 05:03:02 +00002347static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2348 QualType Type, LValue &Result) {
2349 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2350 PathE = E->path_end();
2351 PathI != PathE; ++PathI) {
2352 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2353 *PathI))
2354 return false;
2355 Type = (*PathI)->getType();
2356 }
2357 return true;
2358}
2359
Richard Smithd62306a2011-11-10 06:34:14 +00002360/// Update LVal to refer to the given field, which must be a member of the type
2361/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002362static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002363 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002364 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002365 if (!RL) {
2366 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002367 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002368 }
Richard Smithd62306a2011-11-10 06:34:14 +00002369
2370 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002371 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002372 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002373 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002374}
2375
Richard Smith1b78b3d2012-01-25 22:15:11 +00002376/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002377static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002378 LValue &LVal,
2379 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002380 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002381 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002382 return false;
2383 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002384}
2385
Richard Smithd62306a2011-11-10 06:34:14 +00002386/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002387static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2388 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002389 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2390 // extension.
2391 if (Type->isVoidType() || Type->isFunctionType()) {
2392 Size = CharUnits::One();
2393 return true;
2394 }
2395
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002396 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002397 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002398 return false;
2399 }
2400
Richard Smithd62306a2011-11-10 06:34:14 +00002401 if (!Type->isConstantSizeType()) {
2402 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002403 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002404 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002405 return false;
2406 }
2407
2408 Size = Info.Ctx.getTypeSizeInChars(Type);
2409 return true;
2410}
2411
2412/// Update a pointer value to model pointer arithmetic.
2413/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002414/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002415/// \param LVal - The pointer value to be updated.
2416/// \param EltTy - The pointee type represented by LVal.
2417/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002418static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2419 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002420 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002421 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002422 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002423 return false;
2424
Yaxun Liu402804b2016-12-15 08:09:08 +00002425 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002426 return true;
2427}
2428
Richard Smithd6cc1982017-01-31 02:23:02 +00002429static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2430 LValue &LVal, QualType EltTy,
2431 int64_t Adjustment) {
2432 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2433 APSInt::get(Adjustment));
2434}
2435
Richard Smith66c96992012-02-18 22:04:06 +00002436/// Update an lvalue to refer to a component of a complex number.
2437/// \param Info - Information about the ongoing evaluation.
2438/// \param LVal - The lvalue to be updated.
2439/// \param EltTy - The complex number's component type.
2440/// \param Imag - False for the real component, true for the imaginary.
2441static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2442 LValue &LVal, QualType EltTy,
2443 bool Imag) {
2444 if (Imag) {
2445 CharUnits SizeOfComponent;
2446 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2447 return false;
2448 LVal.Offset += SizeOfComponent;
2449 }
2450 LVal.addComplex(Info, E, EltTy, Imag);
2451 return true;
2452}
2453
Faisal Vali051e3a22017-02-16 04:12:21 +00002454static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2455 QualType Type, const LValue &LVal,
2456 APValue &RVal);
2457
Richard Smith27908702011-10-24 17:54:18 +00002458/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002459///
2460/// \param Info Information about the ongoing evaluation.
2461/// \param E An expression to be used when printing diagnostics.
2462/// \param VD The variable whose initializer should be obtained.
2463/// \param Frame The frame in which the variable was created. Must be null
2464/// if this variable is not local to the evaluation.
2465/// \param Result Filled in with a pointer to the value of the variable.
2466static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2467 const VarDecl *VD, CallStackFrame *Frame,
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002468 APValue *&Result, const LValue *LVal) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002469
Richard Smith254a73d2011-10-28 22:34:42 +00002470 // If this is a parameter to an active constexpr function call, perform
2471 // argument substitution.
2472 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002473 // Assume arguments of a potential constant expression are unknown
2474 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002475 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002476 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002477 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002478 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002479 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002480 }
Richard Smith3229b742013-05-05 21:17:10 +00002481 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002482 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002483 }
Richard Smith27908702011-10-24 17:54:18 +00002484
Richard Smithd9f663b2013-04-22 15:31:51 +00002485 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002486 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00002487 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2488 : Frame->getCurrentTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002489 if (!Result) {
2490 // Assume variables referenced within a lambda's call operator that were
2491 // not declared within the call operator are captures and during checking
2492 // of a potential constant expression, assume they are unknown constant
2493 // expressions.
2494 assert(isLambdaCallOperator(Frame->Callee) &&
2495 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2496 "missing value for local variable");
2497 if (Info.checkingPotentialConstantExpression())
2498 return false;
2499 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002500 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002501 diag::note_unimplemented_constexpr_lambda_feature_ast)
2502 << "captures not currently allowed";
2503 return false;
2504 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002505 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002506 }
2507
Richard Smithd0b4dd62011-12-19 06:19:21 +00002508 // Dig out the initializer, and use the declaration which it's attached to.
2509 const Expr *Init = VD->getAnyInitializer(VD);
2510 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002511 // If we're checking a potential constant expression, the variable could be
2512 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002513 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002514 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002515 return false;
2516 }
2517
Richard Smithd62306a2011-11-10 06:34:14 +00002518 // If we're currently evaluating the initializer of this declaration, use that
2519 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002520 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002521 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002522 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002523 }
2524
Richard Smithcecf1842011-11-01 21:06:14 +00002525 // Never evaluate the initializer of a weak variable. We can't be sure that
2526 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002527 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002528 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002529 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002530 }
Richard Smithcecf1842011-11-01 21:06:14 +00002531
Richard Smithd0b4dd62011-12-19 06:19:21 +00002532 // Check that we can fold the initializer. In C++, we will have already done
2533 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002534 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002535 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002536 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002537 Notes.size() + 1) << VD;
2538 Info.Note(VD->getLocation(), diag::note_declared_at);
2539 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002540 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002541 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002542 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002543 Notes.size() + 1) << VD;
2544 Info.Note(VD->getLocation(), diag::note_declared_at);
2545 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002546 }
Richard Smith27908702011-10-24 17:54:18 +00002547
Richard Smith3229b742013-05-05 21:17:10 +00002548 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002549 return true;
Richard Smith27908702011-10-24 17:54:18 +00002550}
2551
Richard Smith11562c52011-10-28 17:51:58 +00002552static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002553 Qualifiers Quals = T.getQualifiers();
2554 return Quals.hasConst() && !Quals.hasVolatile();
2555}
2556
Richard Smithe97cbd72011-11-11 04:05:33 +00002557/// Get the base index of the given base class within an APValue representing
2558/// the given derived class.
2559static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2560 const CXXRecordDecl *Base) {
2561 Base = Base->getCanonicalDecl();
2562 unsigned Index = 0;
2563 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2564 E = Derived->bases_end(); I != E; ++I, ++Index) {
2565 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2566 return Index;
2567 }
2568
2569 llvm_unreachable("base class missing from derived class's bases list");
2570}
2571
Richard Smith3da88fa2013-04-26 14:36:30 +00002572/// Extract the value of a character from a string literal.
2573static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2574 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002575 // FIXME: Support MakeStringConstant
2576 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2577 std::string Str;
2578 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2579 assert(Index <= Str.size() && "Index too large");
2580 return APSInt::getUnsigned(Str.c_str()[Index]);
2581 }
2582
Alexey Bataevec474782014-10-09 08:45:04 +00002583 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2584 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002585 const StringLiteral *S = cast<StringLiteral>(Lit);
2586 const ConstantArrayType *CAT =
2587 Info.Ctx.getAsConstantArrayType(S->getType());
2588 assert(CAT && "string literal isn't an array");
2589 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002590 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002591
2592 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002593 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002594 if (Index < S->getLength())
2595 Value = S->getCodeUnit(Index);
2596 return Value;
2597}
2598
Richard Smith3da88fa2013-04-26 14:36:30 +00002599// Expand a string literal into an array of characters.
2600static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2601 APValue &Result) {
2602 const StringLiteral *S = cast<StringLiteral>(Lit);
2603 const ConstantArrayType *CAT =
2604 Info.Ctx.getAsConstantArrayType(S->getType());
2605 assert(CAT && "string literal isn't an array");
2606 QualType CharType = CAT->getElementType();
2607 assert(CharType->isIntegerType() && "unexpected character type");
2608
2609 unsigned Elts = CAT->getSize().getZExtValue();
2610 Result = APValue(APValue::UninitArray(),
2611 std::min(S->getLength(), Elts), Elts);
2612 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2613 CharType->isUnsignedIntegerType());
2614 if (Result.hasArrayFiller())
2615 Result.getArrayFiller() = APValue(Value);
2616 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2617 Value = S->getCodeUnit(I);
2618 Result.getArrayInitializedElt(I) = APValue(Value);
2619 }
2620}
2621
2622// Expand an array so that it has more than Index filled elements.
2623static void expandArray(APValue &Array, unsigned Index) {
2624 unsigned Size = Array.getArraySize();
2625 assert(Index < Size);
2626
2627 // Always at least double the number of elements for which we store a value.
2628 unsigned OldElts = Array.getArrayInitializedElts();
2629 unsigned NewElts = std::max(Index+1, OldElts * 2);
2630 NewElts = std::min(Size, std::max(NewElts, 8u));
2631
2632 // Copy the data across.
2633 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2634 for (unsigned I = 0; I != OldElts; ++I)
2635 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2636 for (unsigned I = OldElts; I != NewElts; ++I)
2637 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2638 if (NewValue.hasArrayFiller())
2639 NewValue.getArrayFiller() = Array.getArrayFiller();
2640 Array.swap(NewValue);
2641}
2642
Richard Smithb01fe402014-09-16 01:24:02 +00002643/// Determine whether a type would actually be read by an lvalue-to-rvalue
2644/// conversion. If it's of class type, we may assume that the copy operation
2645/// is trivial. Note that this is never true for a union type with fields
2646/// (because the copy always "reads" the active member) and always true for
2647/// a non-class type.
2648static bool isReadByLvalueToRvalueConversion(QualType T) {
2649 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2650 if (!RD || (RD->isUnion() && !RD->field_empty()))
2651 return true;
2652 if (RD->isEmpty())
2653 return false;
2654
2655 for (auto *Field : RD->fields())
2656 if (isReadByLvalueToRvalueConversion(Field->getType()))
2657 return true;
2658
2659 for (auto &BaseSpec : RD->bases())
2660 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2661 return true;
2662
2663 return false;
2664}
2665
2666/// Diagnose an attempt to read from any unreadable field within the specified
2667/// type, which might be a class type.
2668static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2669 QualType T) {
2670 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2671 if (!RD)
2672 return false;
2673
2674 if (!RD->hasMutableFields())
2675 return false;
2676
2677 for (auto *Field : RD->fields()) {
2678 // If we're actually going to read this field in some way, then it can't
2679 // be mutable. If we're in a union, then assigning to a mutable field
2680 // (even an empty one) can change the active member, so that's not OK.
2681 // FIXME: Add core issue number for the union case.
2682 if (Field->isMutable() &&
2683 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002684 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002685 Info.Note(Field->getLocation(), diag::note_declared_at);
2686 return true;
2687 }
2688
2689 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2690 return true;
2691 }
2692
2693 for (auto &BaseSpec : RD->bases())
2694 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2695 return true;
2696
2697 // All mutable fields were empty, and thus not actually read.
2698 return false;
2699}
2700
Richard Smith861b5b52013-05-07 23:34:45 +00002701/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002702enum AccessKinds {
2703 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002704 AK_Assign,
2705 AK_Increment,
2706 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002707};
2708
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002709namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002710/// A handle to a complete object (an object that is not a subobject of
2711/// another object).
2712struct CompleteObject {
2713 /// The value of the complete object.
2714 APValue *Value;
2715 /// The type of the complete object.
2716 QualType Type;
Richard Smith9defb7d2018-02-21 03:38:30 +00002717 bool LifetimeStartedInEvaluation;
Richard Smith3229b742013-05-05 21:17:10 +00002718
Craig Topper36250ad2014-05-12 05:36:57 +00002719 CompleteObject() : Value(nullptr) {}
Richard Smith9defb7d2018-02-21 03:38:30 +00002720 CompleteObject(APValue *Value, QualType Type,
2721 bool LifetimeStartedInEvaluation)
2722 : Value(Value), Type(Type),
2723 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
Richard Smith3229b742013-05-05 21:17:10 +00002724 assert(Value && "missing value for complete object");
2725 }
2726
Aaron Ballman67347662015-02-15 22:00:28 +00002727 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002728};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002729} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002730
Richard Smith3da88fa2013-04-26 14:36:30 +00002731/// Find the designated sub-object of an rvalue.
2732template<typename SubobjectHandler>
2733typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002734findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002735 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002736 if (Sub.Invalid)
2737 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002738 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002739 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002740 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002741 Info.FFDiag(E, Sub.isOnePastTheEnd()
2742 ? diag::note_constexpr_access_past_end
2743 : diag::note_constexpr_access_unsized_array)
2744 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002745 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002746 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002747 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002748 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002749
Richard Smith3229b742013-05-05 21:17:10 +00002750 APValue *O = Obj.Value;
2751 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002752 const FieldDecl *LastField = nullptr;
Richard Smith9defb7d2018-02-21 03:38:30 +00002753 const bool MayReadMutableMembers =
2754 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002755
Richard Smithd62306a2011-11-10 06:34:14 +00002756 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002757 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2758 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002759 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002760 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002761 return handler.failed();
2762 }
2763
Richard Smith49ca8aa2013-08-06 07:09:20 +00002764 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002765 // If we are reading an object of class type, there may still be more
2766 // things we need to check: if there are any mutable subobjects, we
2767 // cannot perform this read. (This only happens when performing a trivial
2768 // copy or assignment.)
2769 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
Richard Smith9defb7d2018-02-21 03:38:30 +00002770 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
Richard Smithb01fe402014-09-16 01:24:02 +00002771 return handler.failed();
2772
Richard Smith49ca8aa2013-08-06 07:09:20 +00002773 if (!handler.found(*O, ObjType))
2774 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002775
Richard Smith49ca8aa2013-08-06 07:09:20 +00002776 // If we modified a bit-field, truncate it to the right width.
2777 if (handler.AccessKind != AK_Read &&
2778 LastField && LastField->isBitField() &&
2779 !truncateBitfieldValue(Info, E, *O, LastField))
2780 return false;
2781
2782 return true;
2783 }
2784
Craig Topper36250ad2014-05-12 05:36:57 +00002785 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002786 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002787 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002788 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002789 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002790 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002791 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002792 // Note, it should not be possible to form a pointer with a valid
2793 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002794 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002795 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002796 << handler.AccessKind;
2797 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002798 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002799 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002800 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002801
2802 ObjType = CAT->getElementType();
2803
Richard Smith14a94132012-02-17 03:35:37 +00002804 // An array object is represented as either an Array APValue or as an
2805 // LValue which refers to a string literal.
2806 if (O->isLValue()) {
2807 assert(I == N - 1 && "extracting subobject of character?");
2808 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002809 if (handler.AccessKind != AK_Read)
2810 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2811 *O);
2812 else
2813 return handler.foundString(*O, ObjType, Index);
2814 }
2815
2816 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002817 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002818 else if (handler.AccessKind != AK_Read) {
2819 expandArray(*O, Index);
2820 O = &O->getArrayInitializedElt(Index);
2821 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002822 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002823 } else if (ObjType->isAnyComplexType()) {
2824 // Next subobject is a complex number.
2825 uint64_t Index = Sub.Entries[I].ArrayIndex;
2826 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002827 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002828 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002829 << handler.AccessKind;
2830 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002831 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002832 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002833 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002834
2835 bool WasConstQualified = ObjType.isConstQualified();
2836 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2837 if (WasConstQualified)
2838 ObjType.addConst();
2839
Richard Smith66c96992012-02-18 22:04:06 +00002840 assert(I == N - 1 && "extracting subobject of scalar?");
2841 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002842 return handler.found(Index ? O->getComplexIntImag()
2843 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002844 } else {
2845 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002846 return handler.found(Index ? O->getComplexFloatImag()
2847 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002848 }
Richard Smithd62306a2011-11-10 06:34:14 +00002849 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith9defb7d2018-02-21 03:38:30 +00002850 // In C++14 onwards, it is permitted to read a mutable member whose
2851 // lifetime began within the evaluation.
2852 // FIXME: Should we also allow this in C++11?
2853 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2854 !MayReadMutableMembers) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002855 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002856 << Field;
2857 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002858 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002859 }
2860
Richard Smithd62306a2011-11-10 06:34:14 +00002861 // Next subobject is a class, struct or union field.
2862 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2863 if (RD->isUnion()) {
2864 const FieldDecl *UnionField = O->getUnionField();
2865 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002866 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002867 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002868 << handler.AccessKind << Field << !UnionField << UnionField;
2869 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002870 }
Richard Smithd62306a2011-11-10 06:34:14 +00002871 O = &O->getUnionValue();
2872 } else
2873 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002874
2875 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002876 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002877 if (WasConstQualified && !Field->isMutable())
2878 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002879
2880 if (ObjType.isVolatileQualified()) {
2881 if (Info.getLangOpts().CPlusPlus) {
2882 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002883 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002884 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002885 Info.Note(Field->getLocation(), diag::note_declared_at);
2886 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002887 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002888 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002889 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002890 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002891
2892 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002893 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002894 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002895 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2896 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2897 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002898
2899 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002900 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002901 if (WasConstQualified)
2902 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002903 }
2904 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002905}
2906
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002907namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002908struct ExtractSubobjectHandler {
2909 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002910 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002911
2912 static const AccessKinds AccessKind = AK_Read;
2913
2914 typedef bool result_type;
2915 bool failed() { return false; }
2916 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002917 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002918 return true;
2919 }
2920 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002921 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002922 return true;
2923 }
2924 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002925 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002926 return true;
2927 }
2928 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002929 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002930 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2931 return true;
2932 }
2933};
Richard Smith3229b742013-05-05 21:17:10 +00002934} // end anonymous namespace
2935
Richard Smith3da88fa2013-04-26 14:36:30 +00002936const AccessKinds ExtractSubobjectHandler::AccessKind;
2937
2938/// Extract the designated sub-object of an rvalue.
2939static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002940 const CompleteObject &Obj,
2941 const SubobjectDesignator &Sub,
2942 APValue &Result) {
2943 ExtractSubobjectHandler Handler = { Info, Result };
2944 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002945}
2946
Richard Smith3229b742013-05-05 21:17:10 +00002947namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002948struct ModifySubobjectHandler {
2949 EvalInfo &Info;
2950 APValue &NewVal;
2951 const Expr *E;
2952
2953 typedef bool result_type;
2954 static const AccessKinds AccessKind = AK_Assign;
2955
2956 bool checkConst(QualType QT) {
2957 // Assigning to a const object has undefined behavior.
2958 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002959 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002960 return false;
2961 }
2962 return true;
2963 }
2964
2965 bool failed() { return false; }
2966 bool found(APValue &Subobj, QualType SubobjType) {
2967 if (!checkConst(SubobjType))
2968 return false;
2969 // We've been given ownership of NewVal, so just swap it in.
2970 Subobj.swap(NewVal);
2971 return true;
2972 }
2973 bool found(APSInt &Value, QualType SubobjType) {
2974 if (!checkConst(SubobjType))
2975 return false;
2976 if (!NewVal.isInt()) {
2977 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002978 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002979 return false;
2980 }
2981 Value = NewVal.getInt();
2982 return true;
2983 }
2984 bool found(APFloat &Value, QualType SubobjType) {
2985 if (!checkConst(SubobjType))
2986 return false;
2987 Value = NewVal.getFloat();
2988 return true;
2989 }
2990 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2991 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2992 }
2993};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002994} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002995
Richard Smith3229b742013-05-05 21:17:10 +00002996const AccessKinds ModifySubobjectHandler::AccessKind;
2997
Richard Smith3da88fa2013-04-26 14:36:30 +00002998/// Update the designated sub-object of an rvalue to the given value.
2999static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00003000 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00003001 const SubobjectDesignator &Sub,
3002 APValue &NewVal) {
3003 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00003004 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00003005}
3006
Richard Smith84f6dcf2012-02-02 01:16:57 +00003007/// Find the position where two subobject designators diverge, or equivalently
3008/// the length of the common initial subsequence.
3009static unsigned FindDesignatorMismatch(QualType ObjType,
3010 const SubobjectDesignator &A,
3011 const SubobjectDesignator &B,
3012 bool &WasArrayIndex) {
3013 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3014 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00003015 if (!ObjType.isNull() &&
3016 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00003017 // Next subobject is an array element.
3018 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3019 WasArrayIndex = true;
3020 return I;
3021 }
Richard Smith66c96992012-02-18 22:04:06 +00003022 if (ObjType->isAnyComplexType())
3023 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3024 else
3025 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00003026 } else {
3027 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3028 WasArrayIndex = false;
3029 return I;
3030 }
3031 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3032 // Next subobject is a field.
3033 ObjType = FD->getType();
3034 else
3035 // Next subobject is a base class.
3036 ObjType = QualType();
3037 }
3038 }
3039 WasArrayIndex = false;
3040 return I;
3041}
3042
3043/// Determine whether the given subobject designators refer to elements of the
3044/// same array object.
3045static bool AreElementsOfSameArray(QualType ObjType,
3046 const SubobjectDesignator &A,
3047 const SubobjectDesignator &B) {
3048 if (A.Entries.size() != B.Entries.size())
3049 return false;
3050
George Burgess IVa51c4072015-10-16 01:49:01 +00003051 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00003052 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3053 // A is a subobject of the array element.
3054 return false;
3055
3056 // If A (and B) designates an array element, the last entry will be the array
3057 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3058 // of length 1' case, and the entire path must match.
3059 bool WasArrayIndex;
3060 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3061 return CommonLength >= A.Entries.size() - IsArray;
3062}
3063
Richard Smith3229b742013-05-05 21:17:10 +00003064/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00003065static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3066 AccessKinds AK, const LValue &LVal,
3067 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00003068 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003069 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00003070 return CompleteObject();
3071 }
3072
Craig Topper36250ad2014-05-12 05:36:57 +00003073 CallStackFrame *Frame = nullptr;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003074 if (LVal.getLValueCallIndex()) {
3075 Frame = Info.getCallFrame(LVal.getLValueCallIndex());
Richard Smith3229b742013-05-05 21:17:10 +00003076 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003077 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003078 << AK << LVal.Base.is<const ValueDecl*>();
3079 NoteLValueLocation(Info, LVal.Base);
3080 return CompleteObject();
3081 }
Richard Smith3229b742013-05-05 21:17:10 +00003082 }
3083
3084 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3085 // is not a constant expression (even if the object is non-volatile). We also
3086 // apply this rule to C++98, in order to conform to the expected 'volatile'
3087 // semantics.
3088 if (LValType.isVolatileQualified()) {
3089 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003090 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003091 << AK << LValType;
3092 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003093 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003094 return CompleteObject();
3095 }
3096
3097 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003098 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003099 QualType BaseType = getType(LVal.Base);
Richard Smith9defb7d2018-02-21 03:38:30 +00003100 bool LifetimeStartedInEvaluation = Frame;
Richard Smith3229b742013-05-05 21:17:10 +00003101
3102 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3103 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3104 // In C++11, constexpr, non-volatile variables initialized with constant
3105 // expressions are constant expressions too. Inside constexpr functions,
3106 // parameters are constant expressions even if they're non-const.
3107 // In C++1y, objects local to a constant expression (those with a Frame) are
3108 // both readable and writable inside constant expressions.
3109 // In C, such things can also be folded, although they are not ICEs.
3110 const VarDecl *VD = dyn_cast<VarDecl>(D);
3111 if (VD) {
3112 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3113 VD = VDef;
3114 }
3115 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003116 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003117 return CompleteObject();
3118 }
3119
3120 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003121 if (BaseType.isVolatileQualified()) {
3122 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003123 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003124 << AK << 1 << VD;
3125 Info.Note(VD->getLocation(), diag::note_declared_at);
3126 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003127 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003128 }
3129 return CompleteObject();
3130 }
3131
3132 // Unless we're looking at a local variable or argument in a constexpr call,
3133 // the variable we're reading must be const.
3134 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003135 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003136 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3137 // OK, we can read and modify an object if we're in the process of
3138 // evaluating its initializer, because its lifetime began in this
3139 // evaluation.
3140 } else if (AK != AK_Read) {
3141 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003142 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003143 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003144 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003145 // OK, we can read this variable.
3146 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003147 // In OpenCL if a variable is in constant address space it is a const value.
3148 if (!(BaseType.isConstQualified() ||
3149 (Info.getLangOpts().OpenCL &&
3150 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003151 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003152 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003153 Info.Note(VD->getLocation(), diag::note_declared_at);
3154 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003155 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003156 }
3157 return CompleteObject();
3158 }
3159 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3160 // We support folding of const floating-point types, in order to make
3161 // static const data members of such types (supported as an extension)
3162 // more useful.
3163 if (Info.getLangOpts().CPlusPlus11) {
3164 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3165 Info.Note(VD->getLocation(), diag::note_declared_at);
3166 } else {
3167 Info.CCEDiag(E);
3168 }
George Burgess IVb5316982016-12-27 05:33:20 +00003169 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3170 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3171 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003172 } else {
3173 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003174 if (Info.checkingPotentialConstantExpression() &&
3175 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3176 // The definition of this variable could be constexpr. We can't
3177 // access it right now, but may be able to in future.
3178 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003179 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003180 Info.Note(VD->getLocation(), diag::note_declared_at);
3181 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003182 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003183 }
3184 return CompleteObject();
3185 }
3186 }
3187
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003188 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
Richard Smith3229b742013-05-05 21:17:10 +00003189 return CompleteObject();
3190 } else {
3191 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3192
3193 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003194 if (const MaterializeTemporaryExpr *MTE =
3195 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3196 assert(MTE->getStorageDuration() == SD_Static &&
3197 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003198
Richard Smithe6c01442013-06-05 00:46:14 +00003199 // Per C++1y [expr.const]p2:
3200 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3201 // - a [...] glvalue of integral or enumeration type that refers to
3202 // a non-volatile const object [...]
3203 // [...]
3204 // - a [...] glvalue of literal type that refers to a non-volatile
3205 // object whose lifetime began within the evaluation of e.
3206 //
3207 // C++11 misses the 'began within the evaluation of e' check and
3208 // instead allows all temporaries, including things like:
3209 // int &&r = 1;
3210 // int x = ++r;
3211 // constexpr int k = r;
Richard Smith9defb7d2018-02-21 03:38:30 +00003212 // Therefore we use the C++14 rules in C++11 too.
Richard Smithe6c01442013-06-05 00:46:14 +00003213 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3214 const ValueDecl *ED = MTE->getExtendingDecl();
3215 if (!(BaseType.isConstQualified() &&
3216 BaseType->isIntegralOrEnumerationType()) &&
3217 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003218 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003219 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3220 return CompleteObject();
3221 }
3222
3223 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3224 assert(BaseVal && "got reference to unevaluated temporary");
Richard Smith9defb7d2018-02-21 03:38:30 +00003225 LifetimeStartedInEvaluation = true;
Richard Smithe6c01442013-06-05 00:46:14 +00003226 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003227 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003228 return CompleteObject();
3229 }
3230 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003231 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
Richard Smith08d6a2c2013-07-24 07:11:57 +00003232 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003233 }
Richard Smith3229b742013-05-05 21:17:10 +00003234
3235 // Volatile temporary objects cannot be accessed in constant expressions.
3236 if (BaseType.isVolatileQualified()) {
3237 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003238 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003239 << AK << 0;
3240 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3241 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003242 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003243 }
3244 return CompleteObject();
3245 }
3246 }
3247
Richard Smith7525ff62013-05-09 07:14:00 +00003248 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003249 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003250 // object under construction.
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003251 if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3252 LVal.getLValueCallIndex(),
3253 LVal.getLValueVersion())) {
Richard Smith7525ff62013-05-09 07:14:00 +00003254 BaseType = Info.Ctx.getCanonicalType(BaseType);
3255 BaseType.removeLocalConst();
Richard Smith9defb7d2018-02-21 03:38:30 +00003256 LifetimeStartedInEvaluation = true;
Richard Smith7525ff62013-05-09 07:14:00 +00003257 }
3258
Richard Smith9defb7d2018-02-21 03:38:30 +00003259 // In C++14, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003260 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003261 //
3262 // FIXME: Not all local state is mutable. Allow local constant subobjects
3263 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003264 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3265 Info.EvalStatus.HasSideEffects) ||
3266 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003267 return CompleteObject();
3268
Richard Smith9defb7d2018-02-21 03:38:30 +00003269 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
Richard Smith3229b742013-05-05 21:17:10 +00003270}
3271
Richard Smith243ef902013-05-05 23:31:59 +00003272/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3273/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3274/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003275///
3276/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003277/// \param Conv - The expression for which we are performing the conversion.
3278/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003279/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3280/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003281/// \param LVal - The glvalue on which we are attempting to perform this action.
3282/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003283static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003284 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003285 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003286 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003287 return false;
3288
Richard Smith3229b742013-05-05 21:17:10 +00003289 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003290 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003291 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003292 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3293 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3294 // initializer until now for such expressions. Such an expression can't be
3295 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003296 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003297 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003298 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003299 }
Richard Smith3229b742013-05-05 21:17:10 +00003300 APValue Lit;
3301 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3302 return false;
Richard Smith9defb7d2018-02-21 03:38:30 +00003303 CompleteObject LitObj(&Lit, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003304 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003305 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003306 // We represent a string literal array as an lvalue pointing at the
3307 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003308 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003309 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smith9defb7d2018-02-21 03:38:30 +00003310 CompleteObject StrObj(&Str, Base->getType(), false);
Richard Smith3229b742013-05-05 21:17:10 +00003311 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003312 }
Richard Smith11562c52011-10-28 17:51:58 +00003313 }
3314
Richard Smith3229b742013-05-05 21:17:10 +00003315 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3316 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003317}
3318
3319/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003320static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003321 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003322 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003323 return false;
3324
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003325 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003326 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003327 return false;
3328 }
3329
Richard Smith3229b742013-05-05 21:17:10 +00003330 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003331 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3332}
3333
3334namespace {
3335struct CompoundAssignSubobjectHandler {
3336 EvalInfo &Info;
Richard Smith43e77732013-05-07 04:50:00 +00003337 const Expr *E;
3338 QualType PromotedLHSType;
3339 BinaryOperatorKind Opcode;
3340 const APValue &RHS;
3341
3342 static const AccessKinds AccessKind = AK_Assign;
3343
3344 typedef bool result_type;
3345
3346 bool checkConst(QualType QT) {
3347 // Assigning to a const object has undefined behavior.
3348 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003349 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003350 return false;
3351 }
3352 return true;
3353 }
3354
3355 bool failed() { return false; }
3356 bool found(APValue &Subobj, QualType SubobjType) {
3357 switch (Subobj.getKind()) {
3358 case APValue::Int:
3359 return found(Subobj.getInt(), SubobjType);
3360 case APValue::Float:
3361 return found(Subobj.getFloat(), SubobjType);
3362 case APValue::ComplexInt:
3363 case APValue::ComplexFloat:
3364 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003365 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003366 return false;
3367 case APValue::LValue:
3368 return foundPointer(Subobj, SubobjType);
3369 default:
3370 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003371 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003372 return false;
3373 }
3374 }
3375 bool found(APSInt &Value, QualType SubobjType) {
3376 if (!checkConst(SubobjType))
3377 return false;
3378
3379 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3380 // We don't support compound assignment on integer-cast-to-pointer
3381 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003382 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003383 return false;
3384 }
3385
3386 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3387 SubobjType, Value);
3388 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3389 return false;
3390 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3391 return true;
3392 }
3393 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003394 return checkConst(SubobjType) &&
3395 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3396 Value) &&
3397 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3398 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003399 }
3400 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3401 if (!checkConst(SubobjType))
3402 return false;
3403
3404 QualType PointeeType;
3405 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3406 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003407
3408 if (PointeeType.isNull() || !RHS.isInt() ||
3409 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003410 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003411 return false;
3412 }
3413
Richard Smithd6cc1982017-01-31 02:23:02 +00003414 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003415 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003416 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003417
3418 LValue LVal;
3419 LVal.setFrom(Info.Ctx, Subobj);
3420 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3421 return false;
3422 LVal.moveInto(Subobj);
3423 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003424 }
3425 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3426 llvm_unreachable("shouldn't encounter string elements here");
3427 }
3428};
3429} // end anonymous namespace
3430
3431const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3432
3433/// Perform a compound assignment of LVal <op>= RVal.
3434static bool handleCompoundAssignment(
3435 EvalInfo &Info, const Expr *E,
3436 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3437 BinaryOperatorKind Opcode, const APValue &RVal) {
3438 if (LVal.Designator.Invalid)
3439 return false;
3440
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003441 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003442 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003443 return false;
3444 }
3445
3446 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3447 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3448 RVal };
3449 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3450}
3451
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003452namespace {
3453struct IncDecSubobjectHandler {
3454 EvalInfo &Info;
3455 const UnaryOperator *E;
3456 AccessKinds AccessKind;
3457 APValue *Old;
3458
Richard Smith243ef902013-05-05 23:31:59 +00003459 typedef bool result_type;
3460
3461 bool checkConst(QualType QT) {
3462 // Assigning to a const object has undefined behavior.
3463 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003464 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003465 return false;
3466 }
3467 return true;
3468 }
3469
3470 bool failed() { return false; }
3471 bool found(APValue &Subobj, QualType SubobjType) {
3472 // Stash the old value. Also clear Old, so we don't clobber it later
3473 // if we're post-incrementing a complex.
3474 if (Old) {
3475 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003476 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003477 }
3478
3479 switch (Subobj.getKind()) {
3480 case APValue::Int:
3481 return found(Subobj.getInt(), SubobjType);
3482 case APValue::Float:
3483 return found(Subobj.getFloat(), SubobjType);
3484 case APValue::ComplexInt:
3485 return found(Subobj.getComplexIntReal(),
3486 SubobjType->castAs<ComplexType>()->getElementType()
3487 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3488 case APValue::ComplexFloat:
3489 return found(Subobj.getComplexFloatReal(),
3490 SubobjType->castAs<ComplexType>()->getElementType()
3491 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3492 case APValue::LValue:
3493 return foundPointer(Subobj, SubobjType);
3494 default:
3495 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003496 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003497 return false;
3498 }
3499 }
3500 bool found(APSInt &Value, QualType SubobjType) {
3501 if (!checkConst(SubobjType))
3502 return false;
3503
3504 if (!SubobjType->isIntegerType()) {
3505 // We don't support increment / decrement on integer-cast-to-pointer
3506 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003507 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003508 return false;
3509 }
3510
3511 if (Old) *Old = APValue(Value);
3512
3513 // bool arithmetic promotes to int, and the conversion back to bool
3514 // doesn't reduce mod 2^n, so special-case it.
3515 if (SubobjType->isBooleanType()) {
3516 if (AccessKind == AK_Increment)
3517 Value = 1;
3518 else
3519 Value = !Value;
3520 return true;
3521 }
3522
3523 bool WasNegative = Value.isNegative();
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003524 if (AccessKind == AK_Increment) {
3525 ++Value;
3526
3527 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3528 APSInt ActualValue(Value, /*IsUnsigned*/true);
3529 return HandleOverflow(Info, E, ActualValue, SubobjType);
3530 }
3531 } else {
3532 --Value;
3533
3534 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3535 unsigned BitWidth = Value.getBitWidth();
3536 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3537 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003538 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003539 }
3540 }
3541 return true;
3542 }
3543 bool found(APFloat &Value, QualType SubobjType) {
3544 if (!checkConst(SubobjType))
3545 return false;
3546
3547 if (Old) *Old = APValue(Value);
3548
3549 APFloat One(Value.getSemantics(), 1);
3550 if (AccessKind == AK_Increment)
3551 Value.add(One, APFloat::rmNearestTiesToEven);
3552 else
3553 Value.subtract(One, APFloat::rmNearestTiesToEven);
3554 return true;
3555 }
3556 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3557 if (!checkConst(SubobjType))
3558 return false;
3559
3560 QualType PointeeType;
3561 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3562 PointeeType = PT->getPointeeType();
3563 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003564 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003565 return false;
3566 }
3567
3568 LValue LVal;
3569 LVal.setFrom(Info.Ctx, Subobj);
3570 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3571 AccessKind == AK_Increment ? 1 : -1))
3572 return false;
3573 LVal.moveInto(Subobj);
3574 return true;
3575 }
3576 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3577 llvm_unreachable("shouldn't encounter string elements here");
3578 }
3579};
3580} // end anonymous namespace
3581
3582/// Perform an increment or decrement on LVal.
3583static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3584 QualType LValType, bool IsIncrement, APValue *Old) {
3585 if (LVal.Designator.Invalid)
3586 return false;
3587
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003588 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003589 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003590 return false;
3591 }
Malcolm Parsonsfab36802018-04-16 08:31:08 +00003592
3593 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3594 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3595 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3596 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3597}
3598
Richard Smithe97cbd72011-11-11 04:05:33 +00003599/// Build an lvalue for the object argument of a member function call.
3600static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3601 LValue &This) {
3602 if (Object->getType()->isPointerType())
3603 return EvaluatePointer(Object, This, Info);
3604
3605 if (Object->isGLValue())
3606 return EvaluateLValue(Object, This, Info);
3607
Richard Smithd9f663b2013-04-22 15:31:51 +00003608 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003609 return EvaluateTemporary(Object, This, Info);
3610
Faisal Valie690b7a2016-07-02 22:34:24 +00003611 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003612 return false;
3613}
3614
3615/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3616/// lvalue referring to the result.
3617///
3618/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003619/// \param LV - An lvalue referring to the base of the member pointer.
3620/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003621/// \param IncludeMember - Specifies whether the member itself is included in
3622/// the resulting LValue subobject designator. This is not possible when
3623/// creating a bound member function.
3624/// \return The field or method declaration to which the member pointer refers,
3625/// or 0 if evaluation fails.
3626static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003627 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003628 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003629 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003630 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003631 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003632 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003633 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003634
3635 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3636 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003637 if (!MemPtr.getDecl()) {
3638 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003639 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003640 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003641 }
Richard Smith253c2a32012-01-27 01:14:48 +00003642
Richard Smith027bf112011-11-17 22:56:20 +00003643 if (MemPtr.isDerivedMember()) {
3644 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003645 // The end of the derived-to-base path for the base object must match the
3646 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003647 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003648 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003649 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003650 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003651 }
Richard Smith027bf112011-11-17 22:56:20 +00003652 unsigned PathLengthToMember =
3653 LV.Designator.Entries.size() - MemPtr.Path.size();
3654 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3655 const CXXRecordDecl *LVDecl = getAsBaseClass(
3656 LV.Designator.Entries[PathLengthToMember + I]);
3657 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003658 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003659 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003660 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003661 }
Richard Smith027bf112011-11-17 22:56:20 +00003662 }
3663
3664 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003665 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003666 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003667 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003668 } else if (!MemPtr.Path.empty()) {
3669 // Extend the LValue path with the member pointer's path.
3670 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3671 MemPtr.Path.size() + IncludeMember);
3672
3673 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003674 if (const PointerType *PT = LVType->getAs<PointerType>())
3675 LVType = PT->getPointeeType();
3676 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3677 assert(RD && "member pointer access on non-class-type expression");
3678 // The first class in the path is that of the lvalue.
3679 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3680 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003681 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003682 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003683 RD = Base;
3684 }
3685 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003686 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3687 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003688 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003689 }
3690
3691 // Add the member. Note that we cannot build bound member functions here.
3692 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003693 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003694 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003695 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003696 } else if (const IndirectFieldDecl *IFD =
3697 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003698 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003699 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003700 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003701 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003702 }
Richard Smith027bf112011-11-17 22:56:20 +00003703 }
3704
3705 return MemPtr.getDecl();
3706}
3707
Richard Smith84401042013-06-03 05:03:02 +00003708static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3709 const BinaryOperator *BO,
3710 LValue &LV,
3711 bool IncludeMember = true) {
3712 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3713
3714 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003715 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003716 MemberPtr MemPtr;
3717 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3718 }
Craig Topper36250ad2014-05-12 05:36:57 +00003719 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003720 }
3721
3722 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3723 BO->getRHS(), IncludeMember);
3724}
3725
Richard Smith027bf112011-11-17 22:56:20 +00003726/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3727/// the provided lvalue, which currently refers to the base object.
3728static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3729 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003730 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003731 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003732 return false;
3733
Richard Smitha8105bc2012-01-06 16:39:00 +00003734 QualType TargetQT = E->getType();
3735 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3736 TargetQT = PT->getPointeeType();
3737
3738 // Check this cast lands within the final derived-to-base subobject path.
3739 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003740 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003741 << D.MostDerivedType << TargetQT;
3742 return false;
3743 }
3744
Richard Smith027bf112011-11-17 22:56:20 +00003745 // Check the type of the final cast. We don't need to check the path,
3746 // since a cast can only be formed if the path is unique.
3747 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003748 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3749 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003750 if (NewEntriesSize == D.MostDerivedPathLength)
3751 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3752 else
Richard Smith027bf112011-11-17 22:56:20 +00003753 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003754 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003755 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003756 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003757 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003758 }
Richard Smith027bf112011-11-17 22:56:20 +00003759
3760 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003761 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003762}
3763
Mike Stump876387b2009-10-27 22:09:17 +00003764namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003765enum EvalStmtResult {
3766 /// Evaluation failed.
3767 ESR_Failed,
3768 /// Hit a 'return' statement.
3769 ESR_Returned,
3770 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003771 ESR_Succeeded,
3772 /// Hit a 'continue' statement.
3773 ESR_Continue,
3774 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003775 ESR_Break,
3776 /// Still scanning for 'case' or 'default' statement.
3777 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003778};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003779}
Richard Smith254a73d2011-10-28 22:34:42 +00003780
Richard Smith97fcf4b2016-08-14 23:15:52 +00003781static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3782 // We don't need to evaluate the initializer for a static local.
3783 if (!VD->hasLocalStorage())
3784 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003785
Richard Smith97fcf4b2016-08-14 23:15:52 +00003786 LValue Result;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003787 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
Richard Smithd9f663b2013-04-22 15:31:51 +00003788
Richard Smith97fcf4b2016-08-14 23:15:52 +00003789 const Expr *InitE = VD->getInit();
3790 if (!InitE) {
3791 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3792 << false << VD->getType();
3793 Val = APValue();
3794 return false;
3795 }
Richard Smith51f03172013-06-20 03:00:05 +00003796
Richard Smith97fcf4b2016-08-14 23:15:52 +00003797 if (InitE->isValueDependent())
3798 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003799
Richard Smith97fcf4b2016-08-14 23:15:52 +00003800 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3801 // Wipe out any partially-computed value, to allow tracking that this
3802 // evaluation failed.
3803 Val = APValue();
3804 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003805 }
3806
3807 return true;
3808}
3809
Richard Smith97fcf4b2016-08-14 23:15:52 +00003810static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3811 bool OK = true;
3812
3813 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3814 OK &= EvaluateVarDecl(Info, VD);
3815
3816 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3817 for (auto *BD : DD->bindings())
3818 if (auto *VD = BD->getHoldingVar())
3819 OK &= EvaluateDecl(Info, VD);
3820
3821 return OK;
3822}
3823
3824
Richard Smith4e18ca52013-05-06 05:56:11 +00003825/// Evaluate a condition (either a variable declaration or an expression).
3826static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3827 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003828 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003829 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3830 return false;
3831 return EvaluateAsBooleanCondition(Cond, Result, Info);
3832}
3833
Richard Smith89210072016-04-04 23:29:43 +00003834namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003835/// \brief A location where the result (returned value) of evaluating a
3836/// statement should be stored.
3837struct StmtResult {
3838 /// The APValue that should be filled in with the returned value.
3839 APValue &Value;
3840 /// The location containing the result, if any (used to support RVO).
3841 const LValue *Slot;
3842};
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00003843
3844struct TempVersionRAII {
3845 CallStackFrame &Frame;
3846
3847 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3848 Frame.pushTempVersion();
3849 }
3850
3851 ~TempVersionRAII() {
3852 Frame.popTempVersion();
3853 }
3854};
3855
Richard Smith89210072016-04-04 23:29:43 +00003856}
Richard Smith52a980a2015-08-28 02:43:42 +00003857
3858static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003859 const Stmt *S,
3860 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003861
3862/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003863static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003864 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003865 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003866 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003867 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003868 case ESR_Break:
3869 return ESR_Succeeded;
3870 case ESR_Succeeded:
3871 case ESR_Continue:
3872 return ESR_Continue;
3873 case ESR_Failed:
3874 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003875 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003876 return ESR;
3877 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003878 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003879}
3880
Richard Smith496ddcf2013-05-12 17:32:42 +00003881/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003882static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003883 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003884 BlockScopeRAII Scope(Info);
3885
Richard Smith496ddcf2013-05-12 17:32:42 +00003886 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003887 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003888 {
3889 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003890 if (const Stmt *Init = SS->getInit()) {
3891 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3892 if (ESR != ESR_Succeeded)
3893 return ESR;
3894 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003895 if (SS->getConditionVariable() &&
3896 !EvaluateDecl(Info, SS->getConditionVariable()))
3897 return ESR_Failed;
3898 if (!EvaluateInteger(SS->getCond(), Value, Info))
3899 return ESR_Failed;
3900 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003901
3902 // Find the switch case corresponding to the value of the condition.
3903 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003904 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003905 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3906 SC = SC->getNextSwitchCase()) {
3907 if (isa<DefaultStmt>(SC)) {
3908 Found = SC;
3909 continue;
3910 }
3911
3912 const CaseStmt *CS = cast<CaseStmt>(SC);
3913 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3914 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3915 : LHS;
3916 if (LHS <= Value && Value <= RHS) {
3917 Found = SC;
3918 break;
3919 }
3920 }
3921
3922 if (!Found)
3923 return ESR_Succeeded;
3924
3925 // Search the switch body for the switch case and evaluate it from there.
3926 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3927 case ESR_Break:
3928 return ESR_Succeeded;
3929 case ESR_Succeeded:
3930 case ESR_Continue:
3931 case ESR_Failed:
3932 case ESR_Returned:
3933 return ESR;
3934 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003935 // This can only happen if the switch case is nested within a statement
3936 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003937 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003938 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003939 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003940 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003941}
3942
Richard Smith254a73d2011-10-28 22:34:42 +00003943// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003944static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003945 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003946 if (!Info.nextStep(S))
3947 return ESR_Failed;
3948
Richard Smith496ddcf2013-05-12 17:32:42 +00003949 // If we're hunting down a 'case' or 'default' label, recurse through
3950 // substatements until we hit the label.
3951 if (Case) {
3952 // FIXME: We don't start the lifetime of objects whose initialization we
3953 // jump over. However, such objects must be of class type with a trivial
3954 // default constructor that initialize all subobjects, so must be empty,
3955 // so this almost never matters.
3956 switch (S->getStmtClass()) {
3957 case Stmt::CompoundStmtClass:
3958 // FIXME: Precompute which substatement of a compound statement we
3959 // would jump to, and go straight there rather than performing a
3960 // linear scan each time.
3961 case Stmt::LabelStmtClass:
3962 case Stmt::AttributedStmtClass:
3963 case Stmt::DoStmtClass:
3964 break;
3965
3966 case Stmt::CaseStmtClass:
3967 case Stmt::DefaultStmtClass:
3968 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003969 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003970 break;
3971
3972 case Stmt::IfStmtClass: {
3973 // FIXME: Precompute which side of an 'if' we would jump to, and go
3974 // straight there rather than scanning both sides.
3975 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003976
3977 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3978 // preceded by our switch label.
3979 BlockScopeRAII Scope(Info);
3980
Richard Smith496ddcf2013-05-12 17:32:42 +00003981 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3982 if (ESR != ESR_CaseNotFound || !IS->getElse())
3983 return ESR;
3984 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3985 }
3986
3987 case Stmt::WhileStmtClass: {
3988 EvalStmtResult ESR =
3989 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3990 if (ESR != ESR_Continue)
3991 return ESR;
3992 break;
3993 }
3994
3995 case Stmt::ForStmtClass: {
3996 const ForStmt *FS = cast<ForStmt>(S);
3997 EvalStmtResult ESR =
3998 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3999 if (ESR != ESR_Continue)
4000 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004001 if (FS->getInc()) {
4002 FullExpressionRAII IncScope(Info);
4003 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4004 return ESR_Failed;
4005 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004006 break;
4007 }
4008
4009 case Stmt::DeclStmtClass:
4010 // FIXME: If the variable has initialization that can't be jumped over,
4011 // bail out of any immediately-surrounding compound-statement too.
4012 default:
4013 return ESR_CaseNotFound;
4014 }
4015 }
4016
Richard Smith254a73d2011-10-28 22:34:42 +00004017 switch (S->getStmtClass()) {
4018 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00004019 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004020 // Don't bother evaluating beyond an expression-statement which couldn't
4021 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004022 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004023 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00004024 return ESR_Failed;
4025 return ESR_Succeeded;
4026 }
4027
Faisal Valie690b7a2016-07-02 22:34:24 +00004028 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00004029 return ESR_Failed;
4030
4031 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00004032 return ESR_Succeeded;
4033
Richard Smithd9f663b2013-04-22 15:31:51 +00004034 case Stmt::DeclStmtClass: {
4035 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00004036 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004037 // Each declaration initialization is its own full-expression.
4038 // FIXME: This isn't quite right; if we're performing aggregate
4039 // initialization, each braced subexpression is its own full-expression.
4040 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00004041 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00004042 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004043 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004044 return ESR_Succeeded;
4045 }
4046
Richard Smith357362d2011-12-13 06:39:58 +00004047 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00004048 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00004049 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00004050 if (RetExpr &&
4051 !(Result.Slot
4052 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4053 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00004054 return ESR_Failed;
4055 return ESR_Returned;
4056 }
Richard Smith254a73d2011-10-28 22:34:42 +00004057
4058 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004059 BlockScopeRAII Scope(Info);
4060
Richard Smith254a73d2011-10-28 22:34:42 +00004061 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00004062 for (const auto *BI : CS->body()) {
4063 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00004064 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00004065 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00004066 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00004067 return ESR;
4068 }
Richard Smith496ddcf2013-05-12 17:32:42 +00004069 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00004070 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004071
4072 case Stmt::IfStmtClass: {
4073 const IfStmt *IS = cast<IfStmt>(S);
4074
4075 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004076 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00004077 if (const Stmt *Init = IS->getInit()) {
4078 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4079 if (ESR != ESR_Succeeded)
4080 return ESR;
4081 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004082 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00004083 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00004084 return ESR_Failed;
4085
4086 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4087 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4088 if (ESR != ESR_Succeeded)
4089 return ESR;
4090 }
4091 return ESR_Succeeded;
4092 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004093
4094 case Stmt::WhileStmtClass: {
4095 const WhileStmt *WS = cast<WhileStmt>(S);
4096 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004097 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004098 bool Continue;
4099 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4100 Continue))
4101 return ESR_Failed;
4102 if (!Continue)
4103 break;
4104
4105 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4106 if (ESR != ESR_Continue)
4107 return ESR;
4108 }
4109 return ESR_Succeeded;
4110 }
4111
4112 case Stmt::DoStmtClass: {
4113 const DoStmt *DS = cast<DoStmt>(S);
4114 bool Continue;
4115 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004116 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004117 if (ESR != ESR_Continue)
4118 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004119 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004120
Richard Smith08d6a2c2013-07-24 07:11:57 +00004121 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004122 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4123 return ESR_Failed;
4124 } while (Continue);
4125 return ESR_Succeeded;
4126 }
4127
4128 case Stmt::ForStmtClass: {
4129 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004130 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004131 if (FS->getInit()) {
4132 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4133 if (ESR != ESR_Succeeded)
4134 return ESR;
4135 }
4136 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004137 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004138 bool Continue = true;
4139 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4140 FS->getCond(), Continue))
4141 return ESR_Failed;
4142 if (!Continue)
4143 break;
4144
4145 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4146 if (ESR != ESR_Continue)
4147 return ESR;
4148
Richard Smith08d6a2c2013-07-24 07:11:57 +00004149 if (FS->getInc()) {
4150 FullExpressionRAII IncScope(Info);
4151 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4152 return ESR_Failed;
4153 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004154 }
4155 return ESR_Succeeded;
4156 }
4157
Richard Smith896e0d72013-05-06 06:51:17 +00004158 case Stmt::CXXForRangeStmtClass: {
4159 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004160 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004161
4162 // Initialize the __range variable.
4163 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4164 if (ESR != ESR_Succeeded)
4165 return ESR;
4166
4167 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004168 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4169 if (ESR != ESR_Succeeded)
4170 return ESR;
4171 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004172 if (ESR != ESR_Succeeded)
4173 return ESR;
4174
4175 while (true) {
4176 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004177 {
4178 bool Continue = true;
4179 FullExpressionRAII CondExpr(Info);
4180 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4181 return ESR_Failed;
4182 if (!Continue)
4183 break;
4184 }
Richard Smith896e0d72013-05-06 06:51:17 +00004185
4186 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004187 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004188 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4189 if (ESR != ESR_Succeeded)
4190 return ESR;
4191
4192 // Loop body.
4193 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4194 if (ESR != ESR_Continue)
4195 return ESR;
4196
4197 // Increment: ++__begin
4198 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4199 return ESR_Failed;
4200 }
4201
4202 return ESR_Succeeded;
4203 }
4204
Richard Smith496ddcf2013-05-12 17:32:42 +00004205 case Stmt::SwitchStmtClass:
4206 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4207
Richard Smith4e18ca52013-05-06 05:56:11 +00004208 case Stmt::ContinueStmtClass:
4209 return ESR_Continue;
4210
4211 case Stmt::BreakStmtClass:
4212 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004213
4214 case Stmt::LabelStmtClass:
4215 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4216
4217 case Stmt::AttributedStmtClass:
4218 // As a general principle, C++11 attributes can be ignored without
4219 // any semantic impact.
4220 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4221 Case);
4222
4223 case Stmt::CaseStmtClass:
4224 case Stmt::DefaultStmtClass:
4225 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004226 }
4227}
4228
Richard Smithcc36f692011-12-22 02:22:31 +00004229/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4230/// default constructor. If so, we'll fold it whether or not it's marked as
4231/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4232/// so we need special handling.
4233static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004234 const CXXConstructorDecl *CD,
4235 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004236 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4237 return false;
4238
Richard Smith66e05fe2012-01-18 05:21:49 +00004239 // Value-initialization does not call a trivial default constructor, so such a
4240 // call is a core constant expression whether or not the constructor is
4241 // constexpr.
4242 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004243 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004244 // FIXME: If DiagDecl is an implicitly-declared special member function,
4245 // we should be much more explicit about why it's not constexpr.
4246 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4247 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4248 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004249 } else {
4250 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4251 }
4252 }
4253 return true;
4254}
4255
Richard Smith357362d2011-12-13 06:39:58 +00004256/// CheckConstexprFunction - Check that a function can be called in a constant
4257/// expression.
4258static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4259 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004260 const FunctionDecl *Definition,
4261 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004262 // Potential constant expressions can contain calls to declared, but not yet
4263 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004264 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004265 Declaration->isConstexpr())
4266 return false;
4267
Richard Smith0838f3a2013-05-14 05:18:44 +00004268 // Bail out with no diagnostic if the function declaration itself is invalid.
4269 // We will have produced a relevant diagnostic while parsing it.
4270 if (Declaration->isInvalidDecl())
4271 return false;
4272
Richard Smith357362d2011-12-13 06:39:58 +00004273 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004274 if (Definition && Definition->isConstexpr() &&
4275 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004276 return true;
4277
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004278 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004279 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004280
Richard Smith5179eb72016-06-28 19:03:57 +00004281 // If this function is not constexpr because it is an inherited
4282 // non-constexpr constructor, diagnose that directly.
4283 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4284 if (CD && CD->isInheritingConstructor()) {
4285 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004286 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004287 DiagDecl = CD = Inherited;
4288 }
4289
4290 // FIXME: If DiagDecl is an implicitly-declared special member function
4291 // or an inheriting constructor, we should be much more explicit about why
4292 // it's not constexpr.
4293 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004294 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004295 << CD->getInheritedConstructor().getConstructor()->getParent();
4296 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004297 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004298 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004299 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4300 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004301 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004302 }
4303 return false;
4304}
4305
Richard Smithbe6dd812014-11-19 21:27:17 +00004306/// Determine if a class has any fields that might need to be copied by a
4307/// trivial copy or move operation.
4308static bool hasFields(const CXXRecordDecl *RD) {
4309 if (!RD || RD->isEmpty())
4310 return false;
4311 for (auto *FD : RD->fields()) {
4312 if (FD->isUnnamedBitfield())
4313 continue;
4314 return true;
4315 }
4316 for (auto &Base : RD->bases())
4317 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4318 return true;
4319 return false;
4320}
4321
Richard Smithd62306a2011-11-10 06:34:14 +00004322namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004323typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004324}
4325
4326/// EvaluateArgs - Evaluate the arguments to a function call.
4327static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4328 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004329 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004330 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004331 I != E; ++I) {
4332 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4333 // If we're checking for a potential constant expression, evaluate all
4334 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004335 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004336 return false;
4337 Success = false;
4338 }
4339 }
4340 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004341}
4342
Richard Smith254a73d2011-10-28 22:34:42 +00004343/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004344static bool HandleFunctionCall(SourceLocation CallLoc,
4345 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004346 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004347 EvalInfo &Info, APValue &Result,
4348 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004349 ArgVector ArgValues(Args.size());
4350 if (!EvaluateArgs(Args, ArgValues, Info))
4351 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004352
Richard Smith253c2a32012-01-27 01:14:48 +00004353 if (!Info.CheckCallLimit(CallLoc))
4354 return false;
4355
4356 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004357
4358 // For a trivial copy or move assignment, perform an APValue copy. This is
4359 // essential for unions, where the operations performed by the assignment
4360 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004361 //
4362 // Skip this for non-union classes with no fields; in that case, the defaulted
4363 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004364 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004365 if (MD && MD->isDefaulted() &&
4366 (MD->getParent()->isUnion() ||
4367 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004368 assert(This &&
4369 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4370 LValue RHS;
4371 RHS.setFrom(Info.Ctx, ArgValues[0]);
4372 APValue RHSValue;
4373 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4374 RHS, RHSValue))
4375 return false;
4376 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4377 RHSValue))
4378 return false;
4379 This->moveInto(Result);
4380 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004381 } else if (MD && isLambdaCallOperator(MD)) {
Erik Pilkington11232912018-04-05 00:12:05 +00004382 // We're in a lambda; determine the lambda capture field maps unless we're
4383 // just constexpr checking a lambda's call operator. constexpr checking is
4384 // done before the captures have been added to the closure object (unless
4385 // we're inferring constexpr-ness), so we don't have access to them in this
4386 // case. But since we don't need the captures to constexpr check, we can
4387 // just ignore them.
4388 if (!Info.checkingPotentialConstantExpression())
4389 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4390 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004391 }
4392
Richard Smith52a980a2015-08-28 02:43:42 +00004393 StmtResult Ret = {Result, ResultSlot};
4394 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004395 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004396 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004397 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004398 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004399 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004400 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004401}
4402
Richard Smithd62306a2011-11-10 06:34:14 +00004403/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004404static bool HandleConstructorCall(const Expr *E, const LValue &This,
4405 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004406 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004407 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004408 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004409 if (!Info.CheckCallLimit(CallLoc))
4410 return false;
4411
Richard Smith3607ffe2012-02-13 03:54:03 +00004412 const CXXRecordDecl *RD = Definition->getParent();
4413 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004414 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004415 return false;
4416 }
4417
Erik Pilkington42925492017-10-04 00:18:55 +00004418 EvalInfo::EvaluatingConstructorRAII EvalObj(
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004419 Info, {This.getLValueBase(),
4420 {This.getLValueCallIndex(), This.getLValueVersion()}});
Richard Smith5179eb72016-06-28 19:03:57 +00004421 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004422
Richard Smith52a980a2015-08-28 02:43:42 +00004423 // FIXME: Creating an APValue just to hold a nonexistent return value is
4424 // wasteful.
4425 APValue RetVal;
4426 StmtResult Ret = {RetVal, nullptr};
4427
Richard Smith5179eb72016-06-28 19:03:57 +00004428 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004429 if (Definition->isDelegatingConstructor()) {
4430 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004431 {
4432 FullExpressionRAII InitScope(Info);
4433 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4434 return false;
4435 }
Richard Smith52a980a2015-08-28 02:43:42 +00004436 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004437 }
4438
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004439 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004440 // essential for unions (or classes with anonymous union members), where the
4441 // operations performed by the constructor cannot be represented by
4442 // ctor-initializers.
4443 //
4444 // Skip this for empty non-union classes; we should not perform an
4445 // lvalue-to-rvalue conversion on them because their copy constructor does not
4446 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004447 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004448 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004449 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004450 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004451 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004452 return handleLValueToRValueConversion(
4453 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4454 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004455 }
4456
4457 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004458 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004459 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004460 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004461
John McCalld7bca762012-05-01 00:38:49 +00004462 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004463 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4464
Richard Smith08d6a2c2013-07-24 07:11:57 +00004465 // A scope for temporaries lifetime-extended by reference members.
4466 BlockScopeRAII LifetimeExtendedScope(Info);
4467
Richard Smith253c2a32012-01-27 01:14:48 +00004468 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004469 unsigned BasesSeen = 0;
4470#ifndef NDEBUG
4471 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4472#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004473 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004474 LValue Subobject = This;
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004475 LValue SubobjectParent = This;
Richard Smith253c2a32012-01-27 01:14:48 +00004476 APValue *Value = &Result;
4477
4478 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004479 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004480 if (I->isBaseInitializer()) {
4481 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004482#ifndef NDEBUG
4483 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004484 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004485 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4486 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4487 "base class initializers not in expected order");
4488 ++BaseIt;
4489#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004490 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004491 BaseType->getAsCXXRecordDecl(), &Layout))
4492 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004493 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004494 } else if ((FD = I->getMember())) {
4495 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004496 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004497 if (RD->isUnion()) {
4498 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004499 Value = &Result.getUnionValue();
4500 } else {
4501 Value = &Result.getStructField(FD->getFieldIndex());
4502 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004503 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004504 // Walk the indirect field decl's chain to find the object to initialize,
4505 // and make sure we've initialized every step along it.
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004506 auto IndirectFieldChain = IFD->chain();
4507 for (auto *C : IndirectFieldChain) {
Aaron Ballman13916082014-03-07 18:11:58 +00004508 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004509 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4510 // Switch the union field if it differs. This happens if we had
4511 // preceding zero-initialization, and we're now initializing a union
4512 // subobject other than the first.
4513 // FIXME: In this case, the values of the other subobjects are
4514 // specified, since zero-initialization sets all padding bits to zero.
4515 if (Value->isUninit() ||
4516 (Value->isUnion() && Value->getUnionField() != FD)) {
4517 if (CD->isUnion())
4518 *Value = APValue(FD);
4519 else
4520 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004521 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004522 }
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004523 // Store Subobject as its parent before updating it for the last element
4524 // in the chain.
4525 if (C == IndirectFieldChain.back())
4526 SubobjectParent = Subobject;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004527 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004528 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004529 if (CD->isUnion())
4530 Value = &Value->getUnionValue();
4531 else
4532 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004533 }
Richard Smithd62306a2011-11-10 06:34:14 +00004534 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004535 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004536 }
Richard Smith253c2a32012-01-27 01:14:48 +00004537
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004538 // Need to override This for implicit field initializers as in this case
4539 // This refers to innermost anonymous struct/union containing initializer,
4540 // not to currently constructed class.
4541 const Expr *Init = I->getInit();
4542 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4543 isa<CXXDefaultInitExpr>(Init));
Richard Smith08d6a2c2013-07-24 07:11:57 +00004544 FullExpressionRAII InitScope(Info);
Volodymyr Sapsaie8f1ffb2018-02-23 23:59:20 +00004545 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4546 (FD && FD->isBitField() &&
4547 !truncateBitfieldValue(Info, Init, *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004548 // If we're checking for a potential constant expression, evaluate all
4549 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004550 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004551 return false;
4552 Success = false;
4553 }
Richard Smithd62306a2011-11-10 06:34:14 +00004554 }
4555
Richard Smithd9f663b2013-04-22 15:31:51 +00004556 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004557 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004558}
4559
Richard Smith5179eb72016-06-28 19:03:57 +00004560static bool HandleConstructorCall(const Expr *E, const LValue &This,
4561 ArrayRef<const Expr*> Args,
4562 const CXXConstructorDecl *Definition,
4563 EvalInfo &Info, APValue &Result) {
4564 ArgVector ArgValues(Args.size());
4565 if (!EvaluateArgs(Args, ArgValues, Info))
4566 return false;
4567
4568 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4569 Info, Result);
4570}
4571
Eli Friedman9a156e52008-11-12 09:44:48 +00004572//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004573// Generic Evaluation
4574//===----------------------------------------------------------------------===//
4575namespace {
4576
Aaron Ballman68af21c2014-01-03 19:26:43 +00004577template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004578class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004579 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004580private:
Richard Smith52a980a2015-08-28 02:43:42 +00004581 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004582 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004583 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004584 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004585 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004586 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004587 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004588
Richard Smith17100ba2012-02-16 02:46:34 +00004589 // Check whether a conditional operator with a non-constant condition is a
4590 // potential constant expression. If neither arm is a potential constant
4591 // expression, then the conditional operator is not either.
4592 template<typename ConditionalOperator>
4593 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004594 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004595
4596 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004597 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004598 {
Richard Smith17100ba2012-02-16 02:46:34 +00004599 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004600 StmtVisitorTy::Visit(E->getFalseExpr());
4601 if (Diag.empty())
4602 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004603 }
Richard Smith17100ba2012-02-16 02:46:34 +00004604
George Burgess IV8c892b52016-05-25 22:31:54 +00004605 {
4606 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004607 Diag.clear();
4608 StmtVisitorTy::Visit(E->getTrueExpr());
4609 if (Diag.empty())
4610 return;
4611 }
4612
4613 Error(E, diag::note_constexpr_conditional_never_const);
4614 }
4615
4616
4617 template<typename ConditionalOperator>
4618 bool HandleConditionalOperator(const ConditionalOperator *E) {
4619 bool BoolResult;
4620 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004621 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004622 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004623 return false;
4624 }
4625 if (Info.noteFailure()) {
4626 StmtVisitorTy::Visit(E->getTrueExpr());
4627 StmtVisitorTy::Visit(E->getFalseExpr());
4628 }
Richard Smith17100ba2012-02-16 02:46:34 +00004629 return false;
4630 }
4631
4632 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4633 return StmtVisitorTy::Visit(EvalExpr);
4634 }
4635
Peter Collingbournee9200682011-05-13 03:29:01 +00004636protected:
4637 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004638 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004639 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4640
Richard Smith92b1ce02011-12-12 09:28:41 +00004641 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004642 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004643 }
4644
Aaron Ballman68af21c2014-01-03 19:26:43 +00004645 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004646
4647public:
4648 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4649
4650 EvalInfo &getEvalInfo() { return Info; }
4651
Richard Smithf57d8cb2011-12-09 22:58:01 +00004652 /// Report an evaluation error. This should only be called when an error is
4653 /// first discovered. When propagating an error, just return false.
4654 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004655 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004656 return false;
4657 }
4658 bool Error(const Expr *E) {
4659 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4660 }
4661
Aaron Ballman68af21c2014-01-03 19:26:43 +00004662 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004663 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004664 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004665 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004666 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004667 }
4668
Aaron Ballman68af21c2014-01-03 19:26:43 +00004669 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004670 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004671 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004672 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004673 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004674 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004675 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004676 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004677 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004678 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004679 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004680 { return StmtVisitorTy::Visit(E->getReplacement()); }
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004681 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4682 TempVersionRAII RAII(*Info.CurrentCall);
4683 return StmtVisitorTy::Visit(E->getExpr());
4684 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004685 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004686 TempVersionRAII RAII(*Info.CurrentCall);
Richard Smith17e32462013-09-13 20:51:45 +00004687 // The initializer may not have been parsed yet, or might be erroneous.
4688 if (!E->getExpr())
4689 return Error(E);
4690 return StmtVisitorTy::Visit(E->getExpr());
4691 }
Richard Smith5894a912011-12-19 22:12:41 +00004692 // We cannot create any objects for which cleanups are required, so there is
4693 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004694 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004695 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004696
Aaron Ballman68af21c2014-01-03 19:26:43 +00004697 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004698 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4699 return static_cast<Derived*>(this)->VisitCastExpr(E);
4700 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004701 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004702 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4703 return static_cast<Derived*>(this)->VisitCastExpr(E);
4704 }
4705
Aaron Ballman68af21c2014-01-03 19:26:43 +00004706 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004707 switch (E->getOpcode()) {
4708 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004709 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004710
4711 case BO_Comma:
4712 VisitIgnoredValue(E->getLHS());
4713 return StmtVisitorTy::Visit(E->getRHS());
4714
4715 case BO_PtrMemD:
4716 case BO_PtrMemI: {
4717 LValue Obj;
4718 if (!HandleMemberPointerAccess(Info, E, Obj))
4719 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004720 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004721 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004722 return false;
4723 return DerivedSuccess(Result, E);
4724 }
4725 }
4726 }
4727
Aaron Ballman68af21c2014-01-03 19:26:43 +00004728 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004729 // Evaluate and cache the common expression. We treat it as a temporary,
4730 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004731 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004732 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004733 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004734
Richard Smith17100ba2012-02-16 02:46:34 +00004735 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004736 }
4737
Aaron Ballman68af21c2014-01-03 19:26:43 +00004738 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004739 bool IsBcpCall = false;
4740 // If the condition (ignoring parens) is a __builtin_constant_p call,
4741 // the result is a constant expression if it can be folded without
4742 // side-effects. This is an important GNU extension. See GCC PR38377
4743 // for discussion.
4744 if (const CallExpr *CallCE =
4745 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004746 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004747 IsBcpCall = true;
4748
4749 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4750 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004751 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004752 return false;
4753
Richard Smith6d4c6582013-11-05 22:18:15 +00004754 FoldConstant Fold(Info, IsBcpCall);
4755 if (!HandleConditionalOperator(E)) {
4756 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004757 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004758 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004759
4760 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004761 }
4762
Aaron Ballman68af21c2014-01-03 19:26:43 +00004763 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00004764 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
Richard Smith08d6a2c2013-07-24 07:11:57 +00004765 return DerivedSuccess(*Value, E);
4766
4767 const Expr *Source = E->getSourceExpr();
4768 if (!Source)
4769 return Error(E);
4770 if (Source == E) { // sanity checking.
4771 assert(0 && "OpaqueValueExpr recursively refers to itself");
4772 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004773 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004774 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004775 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004776
Aaron Ballman68af21c2014-01-03 19:26:43 +00004777 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004778 APValue Result;
4779 if (!handleCallExpr(E, Result, nullptr))
4780 return false;
4781 return DerivedSuccess(Result, E);
4782 }
4783
4784 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004785 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004786 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004787 QualType CalleeType = Callee->getType();
4788
Craig Topper36250ad2014-05-12 05:36:57 +00004789 const FunctionDecl *FD = nullptr;
4790 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004791 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004792 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004793
Richard Smithe97cbd72011-11-11 04:05:33 +00004794 // Extract function decl and 'this' pointer from the callee.
4795 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004796 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004797 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4798 // Explicit bound member calls, such as x.f() or p->g();
4799 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004800 return false;
4801 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004802 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004803 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004804 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4805 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004806 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4807 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004808 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004809 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004810 return Error(Callee);
4811
4812 FD = dyn_cast<FunctionDecl>(Member);
4813 if (!FD)
4814 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004815 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004816 LValue Call;
4817 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004818 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004819
Richard Smitha8105bc2012-01-06 16:39:00 +00004820 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004821 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004822 FD = dyn_cast_or_null<FunctionDecl>(
4823 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004824 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004825 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004826 // Don't call function pointers which have been cast to some other type.
4827 // Per DR (no number yet), the caller and callee can differ in noexcept.
4828 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4829 CalleeType->getPointeeType(), FD->getType())) {
4830 return Error(E);
4831 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004832
4833 // Overloaded operator calls to member functions are represented as normal
4834 // calls with '*this' as the first argument.
4835 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4836 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004837 // FIXME: When selecting an implicit conversion for an overloaded
4838 // operator delete, we sometimes try to evaluate calls to conversion
4839 // operators without a 'this' parameter!
4840 if (Args.empty())
4841 return Error(E);
4842
Nick Lewycky13073a62017-06-12 21:15:44 +00004843 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004844 return false;
4845 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004846 Args = Args.slice(1);
Daniel Jasperffdee092017-05-02 19:21:42 +00004847 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004848 // Map the static invoker for the lambda back to the call operator.
4849 // Conveniently, we don't have to slice out the 'this' argument (as is
4850 // being done for the non-static case), since a static member function
4851 // doesn't have an implicit argument passed in.
4852 const CXXRecordDecl *ClosureClass = MD->getParent();
4853 assert(
4854 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4855 "Number of captures must be zero for conversion to function-ptr");
4856
4857 const CXXMethodDecl *LambdaCallOp =
4858 ClosureClass->getLambdaCallOperator();
4859
4860 // Set 'FD', the function that will be called below, to the call
4861 // operator. If the closure object represents a generic lambda, find
4862 // the corresponding specialization of the call operator.
4863
4864 if (ClosureClass->isGenericLambda()) {
4865 assert(MD->isFunctionTemplateSpecialization() &&
4866 "A generic lambda's static-invoker function must be a "
4867 "template specialization");
4868 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4869 FunctionTemplateDecl *CallOpTemplate =
4870 LambdaCallOp->getDescribedFunctionTemplate();
4871 void *InsertPos = nullptr;
4872 FunctionDecl *CorrespondingCallOpSpecialization =
4873 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4874 assert(CorrespondingCallOpSpecialization &&
4875 "We must always have a function call operator specialization "
4876 "that corresponds to our static invoker specialization");
4877 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4878 } else
4879 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004880 }
4881
Daniel Jasperffdee092017-05-02 19:21:42 +00004882
Richard Smithe97cbd72011-11-11 04:05:33 +00004883 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004884 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004885
Richard Smith47b34932012-02-01 02:39:43 +00004886 if (This && !This->checkSubobject(Info, E, CSK_This))
4887 return false;
4888
Richard Smith3607ffe2012-02-13 03:54:03 +00004889 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4890 // calls to such functions in constant expressions.
4891 if (This && !HasQualifier &&
4892 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4893 return Error(E, diag::note_constexpr_virtual_call);
4894
Craig Topper36250ad2014-05-12 05:36:57 +00004895 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004896 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004897
Nick Lewycky13073a62017-06-12 21:15:44 +00004898 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4899 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004900 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004901 return false;
4902
Richard Smith52a980a2015-08-28 02:43:42 +00004903 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004904 }
4905
Aaron Ballman68af21c2014-01-03 19:26:43 +00004906 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004907 return StmtVisitorTy::Visit(E->getInitializer());
4908 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004909 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004910 if (E->getNumInits() == 0)
4911 return DerivedZeroInitialization(E);
4912 if (E->getNumInits() == 1)
4913 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004914 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004915 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004916 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004917 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004918 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004919 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004920 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004921 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004922 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004923 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004924 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004925
Richard Smithd62306a2011-11-10 06:34:14 +00004926 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004927 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004928 assert(!E->isArrow() && "missing call to bound member function?");
4929
Richard Smith2e312c82012-03-03 22:46:17 +00004930 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004931 if (!Evaluate(Val, Info, E->getBase()))
4932 return false;
4933
4934 QualType BaseTy = E->getBase()->getType();
4935
4936 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004937 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004938 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004939 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004940 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4941
Richard Smith9defb7d2018-02-21 03:38:30 +00004942 CompleteObject Obj(&Val, BaseTy, true);
Richard Smitha8105bc2012-01-06 16:39:00 +00004943 SubobjectDesignator Designator(BaseTy);
4944 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004945
Richard Smith3229b742013-05-05 21:17:10 +00004946 APValue Result;
4947 return extractSubobject(Info, E, Obj, Designator, Result) &&
4948 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004949 }
4950
Aaron Ballman68af21c2014-01-03 19:26:43 +00004951 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004952 switch (E->getCastKind()) {
4953 default:
4954 break;
4955
Richard Smitha23ab512013-05-23 00:30:41 +00004956 case CK_AtomicToNonAtomic: {
4957 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004958 // This does not need to be done in place even for class/array types:
4959 // atomic-to-non-atomic conversion implies copying the object
4960 // representation.
4961 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004962 return false;
4963 return DerivedSuccess(AtomicVal, E);
4964 }
4965
Richard Smith11562c52011-10-28 17:51:58 +00004966 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004967 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004968 return StmtVisitorTy::Visit(E->getSubExpr());
4969
4970 case CK_LValueToRValue: {
4971 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004972 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4973 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004974 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004975 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004976 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004977 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004978 return false;
4979 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004980 }
4981 }
4982
Richard Smithf57d8cb2011-12-09 22:58:01 +00004983 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004984 }
4985
Aaron Ballman68af21c2014-01-03 19:26:43 +00004986 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004987 return VisitUnaryPostIncDec(UO);
4988 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004989 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004990 return VisitUnaryPostIncDec(UO);
4991 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004992 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004993 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004994 return Error(UO);
4995
4996 LValue LVal;
4997 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4998 return false;
4999 APValue RVal;
5000 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5001 UO->isIncrementOp(), &RVal))
5002 return false;
5003 return DerivedSuccess(RVal, UO);
5004 }
5005
Aaron Ballman68af21c2014-01-03 19:26:43 +00005006 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00005007 // We will have checked the full-expressions inside the statement expression
5008 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00005009 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00005010 return Error(E);
5011
Richard Smith08d6a2c2013-07-24 07:11:57 +00005012 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00005013 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005014 if (CS->body_empty())
5015 return true;
5016
Richard Smith51f03172013-06-20 03:00:05 +00005017 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5018 BE = CS->body_end();
5019 /**/; ++BI) {
5020 if (BI + 1 == BE) {
5021 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5022 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00005023 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00005024 diag::note_constexpr_stmt_expr_unsupported);
5025 return false;
5026 }
5027 return this->Visit(FinalExpr);
5028 }
5029
5030 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00005031 StmtResult Result = { ReturnValue, nullptr };
5032 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00005033 if (ESR != ESR_Succeeded) {
5034 // FIXME: If the statement-expression terminated due to 'return',
5035 // 'break', or 'continue', it would be nice to propagate that to
5036 // the outer statement evaluation rather than bailing out.
5037 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00005038 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00005039 diag::note_constexpr_stmt_expr_unsupported);
5040 return false;
5041 }
5042 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00005043
5044 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00005045 }
5046
Richard Smith4a678122011-10-24 18:44:57 +00005047 /// Visit a value which is evaluated, but whose value is ignored.
5048 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00005049 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00005050 }
David Majnemere9807b22016-02-26 04:23:19 +00005051
5052 /// Potentially visit a MemberExpr's base expression.
5053 void VisitIgnoredBaseExpression(const Expr *E) {
5054 // While MSVC doesn't evaluate the base expression, it does diagnose the
5055 // presence of side-effecting behavior.
5056 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5057 return;
5058 VisitIgnoredValue(E);
5059 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005060};
5061
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005062}
Peter Collingbournee9200682011-05-13 03:29:01 +00005063
5064//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005065// Common base class for lvalue and temporary evaluation.
5066//===----------------------------------------------------------------------===//
5067namespace {
5068template<class Derived>
5069class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00005070 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00005071protected:
5072 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005073 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00005074 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00005075 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00005076
5077 bool Success(APValue::LValueBase B) {
5078 Result.set(B);
5079 return true;
5080 }
5081
George Burgess IVf9013bf2017-02-10 22:52:29 +00005082 bool evaluatePointer(const Expr *E, LValue &Result) {
5083 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5084 }
5085
Richard Smith027bf112011-11-17 22:56:20 +00005086public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005087 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5088 : ExprEvaluatorBaseTy(Info), Result(Result),
5089 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00005090
Richard Smith2e312c82012-03-03 22:46:17 +00005091 bool Success(const APValue &V, const Expr *E) {
5092 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00005093 return true;
5094 }
Richard Smith027bf112011-11-17 22:56:20 +00005095
Richard Smith027bf112011-11-17 22:56:20 +00005096 bool VisitMemberExpr(const MemberExpr *E) {
5097 // Handle non-static data members.
5098 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005099 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00005100 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005101 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00005102 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00005103 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005104 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00005105 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00005106 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00005107 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00005108 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00005109 BaseTy = E->getBase()->getType();
5110 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005111 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005112 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005113 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005114 Result.setInvalid(E);
5115 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005116 }
Richard Smith027bf112011-11-17 22:56:20 +00005117
Richard Smith1b78b3d2012-01-25 22:15:11 +00005118 const ValueDecl *MD = E->getMemberDecl();
5119 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5120 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5121 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5122 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005123 if (!HandleLValueMember(this->Info, E, Result, FD))
5124 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005125 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005126 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5127 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005128 } else
5129 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005130
Richard Smith1b78b3d2012-01-25 22:15:11 +00005131 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005132 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005133 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005134 RefValue))
5135 return false;
5136 return Success(RefValue, E);
5137 }
5138 return true;
5139 }
5140
5141 bool VisitBinaryOperator(const BinaryOperator *E) {
5142 switch (E->getOpcode()) {
5143 default:
5144 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5145
5146 case BO_PtrMemD:
5147 case BO_PtrMemI:
5148 return HandleMemberPointerAccess(this->Info, E, Result);
5149 }
5150 }
5151
5152 bool VisitCastExpr(const CastExpr *E) {
5153 switch (E->getCastKind()) {
5154 default:
5155 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5156
5157 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005158 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005159 if (!this->Visit(E->getSubExpr()))
5160 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005161
5162 // Now figure out the necessary offset to add to the base LV to get from
5163 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005164 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5165 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005166 }
5167 }
5168};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005169}
Richard Smith027bf112011-11-17 22:56:20 +00005170
5171//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005172// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005173//
5174// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5175// function designators (in C), decl references to void objects (in C), and
5176// temporaries (if building with -Wno-address-of-temporary).
5177//
5178// LValue evaluation produces values comprising a base expression of one of the
5179// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005180// - Declarations
5181// * VarDecl
5182// * FunctionDecl
5183// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005184// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005185// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005186// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005187// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005188// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005189// * ObjCEncodeExpr
5190// * AddrLabelExpr
5191// * BlockExpr
5192// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005193// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005194// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005195// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005196// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5197// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005198// * A MaterializeTemporaryExpr that has static storage duration, with no
5199// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005200// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005201//===----------------------------------------------------------------------===//
5202namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005203class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005204 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005205public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005206 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5207 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005208
Richard Smith11562c52011-10-28 17:51:58 +00005209 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005210 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005211
Peter Collingbournee9200682011-05-13 03:29:01 +00005212 bool VisitDeclRefExpr(const DeclRefExpr *E);
5213 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005214 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005215 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5216 bool VisitMemberExpr(const MemberExpr *E);
5217 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5218 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005219 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005220 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005221 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5222 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005223 bool VisitUnaryReal(const UnaryOperator *E);
5224 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005225 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5226 return VisitUnaryPreIncDec(UO);
5227 }
5228 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5229 return VisitUnaryPreIncDec(UO);
5230 }
Richard Smith3229b742013-05-05 21:17:10 +00005231 bool VisitBinAssign(const BinaryOperator *BO);
5232 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005233
Peter Collingbournee9200682011-05-13 03:29:01 +00005234 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005235 switch (E->getCastKind()) {
5236 default:
Richard Smith027bf112011-11-17 22:56:20 +00005237 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005238
Eli Friedmance3e02a2011-10-11 00:13:24 +00005239 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005240 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005241 if (!Visit(E->getSubExpr()))
5242 return false;
5243 Result.Designator.setInvalid();
5244 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005245
Richard Smith027bf112011-11-17 22:56:20 +00005246 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005247 if (!Visit(E->getSubExpr()))
5248 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005249 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005250 }
5251 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005252};
5253} // end anonymous namespace
5254
Richard Smith11562c52011-10-28 17:51:58 +00005255/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005256/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005257/// * function designators in C, and
5258/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005259/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005260static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5261 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005262 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005263 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005264 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005265}
5266
Peter Collingbournee9200682011-05-13 03:29:01 +00005267bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005268 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005269 return Success(FD);
5270 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005271 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005272 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005273 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005274 return Error(E);
5275}
Richard Smith733237d2011-10-24 23:14:33 +00005276
Faisal Vali0528a312016-11-13 06:09:16 +00005277
Richard Smith11562c52011-10-28 17:51:58 +00005278bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005279
5280 // If we are within a lambda's call operator, check whether the 'VD' referred
5281 // to within 'E' actually represents a lambda-capture that maps to a
5282 // data-member/field within the closure object, and if so, evaluate to the
5283 // field or what the field refers to.
Erik Pilkington11232912018-04-05 00:12:05 +00005284 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5285 isa<DeclRefExpr>(E) &&
5286 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5287 // We don't always have a complete capture-map when checking or inferring if
5288 // the function call operator meets the requirements of a constexpr function
5289 // - but we don't need to evaluate the captures to determine constexprness
5290 // (dcl.constexpr C++17).
5291 if (Info.checkingPotentialConstantExpression())
5292 return false;
5293
Faisal Vali051e3a22017-02-16 04:12:21 +00005294 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005295 // Start with 'Result' referring to the complete closure object...
5296 Result = *Info.CurrentCall->This;
5297 // ... then update it to refer to the field of the closure object
5298 // that represents the capture.
5299 if (!HandleLValueMember(Info, E, Result, FD))
5300 return false;
5301 // And if the field is of reference type, update 'Result' to refer to what
5302 // the field refers to.
5303 if (FD->getType()->isReferenceType()) {
5304 APValue RVal;
5305 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5306 RVal))
5307 return false;
5308 Result.setFrom(Info.Ctx, RVal);
5309 }
5310 return true;
5311 }
5312 }
Craig Topper36250ad2014-05-12 05:36:57 +00005313 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005314 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5315 // Only if a local variable was declared in the function currently being
5316 // evaluated, do we expect to be able to find its value in the current
5317 // frame. (Otherwise it was likely declared in an enclosing context and
5318 // could either have a valid evaluatable value (for e.g. a constexpr
5319 // variable) or be ill-formed (and trigger an appropriate evaluation
5320 // diagnostic)).
5321 if (Info.CurrentCall->Callee &&
5322 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5323 Frame = Info.CurrentCall;
5324 }
5325 }
Richard Smith3229b742013-05-05 21:17:10 +00005326
Richard Smithfec09922011-11-01 16:57:24 +00005327 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005328 if (Frame) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005329 Result.set({VD, Frame->Index,
5330 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
Richard Smithfec09922011-11-01 16:57:24 +00005331 return true;
5332 }
Richard Smithce40ad62011-11-12 22:28:03 +00005333 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005334 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005335
Richard Smith3229b742013-05-05 21:17:10 +00005336 APValue *V;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005337 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005338 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005339 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005340 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005341 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005342 return false;
5343 }
Richard Smith3229b742013-05-05 21:17:10 +00005344 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005345}
5346
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005347bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5348 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005349 // Walk through the expression to find the materialized temporary itself.
5350 SmallVector<const Expr *, 2> CommaLHSs;
5351 SmallVector<SubobjectAdjustment, 2> Adjustments;
5352 const Expr *Inner = E->GetTemporaryExpr()->
5353 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005354
Richard Smith84401042013-06-03 05:03:02 +00005355 // If we passed any comma operators, evaluate their LHSs.
5356 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5357 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5358 return false;
5359
Richard Smithe6c01442013-06-05 00:46:14 +00005360 // A materialized temporary with static storage duration can appear within the
5361 // result of a constant expression evaluation, so we need to preserve its
5362 // value for use outside this evaluation.
5363 APValue *Value;
5364 if (E->getStorageDuration() == SD_Static) {
5365 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005366 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005367 Result.set(E);
5368 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005369 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5370 *Info.CurrentCall);
Richard Smithe6c01442013-06-05 00:46:14 +00005371 }
5372
Richard Smithea4ad5d2013-06-06 08:19:16 +00005373 QualType Type = Inner->getType();
5374
Richard Smith84401042013-06-03 05:03:02 +00005375 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005376 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5377 (E->getStorageDuration() == SD_Static &&
5378 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5379 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005380 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005381 }
Richard Smith84401042013-06-03 05:03:02 +00005382
5383 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005384 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5385 --I;
5386 switch (Adjustments[I].Kind) {
5387 case SubobjectAdjustment::DerivedToBaseAdjustment:
5388 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5389 Type, Result))
5390 return false;
5391 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5392 break;
5393
5394 case SubobjectAdjustment::FieldAdjustment:
5395 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5396 return false;
5397 Type = Adjustments[I].Field->getType();
5398 break;
5399
5400 case SubobjectAdjustment::MemberPointerAdjustment:
5401 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5402 Adjustments[I].Ptr.RHS))
5403 return false;
5404 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5405 break;
5406 }
5407 }
5408
5409 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005410}
5411
Peter Collingbournee9200682011-05-13 03:29:01 +00005412bool
5413LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005414 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5415 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005416 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5417 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005418 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005419}
5420
Richard Smith6e525142011-12-27 12:18:28 +00005421bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005422 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005423 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005424
Faisal Valie690b7a2016-07-02 22:34:24 +00005425 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005426 << E->getExprOperand()->getType()
5427 << E->getExprOperand()->getSourceRange();
5428 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005429}
5430
Francois Pichet0066db92012-04-16 04:08:35 +00005431bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5432 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005433}
Francois Pichet0066db92012-04-16 04:08:35 +00005434
Peter Collingbournee9200682011-05-13 03:29:01 +00005435bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005436 // Handle static data members.
5437 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005438 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005439 return VisitVarDecl(E, VD);
5440 }
5441
Richard Smith254a73d2011-10-28 22:34:42 +00005442 // Handle static member functions.
5443 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5444 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005445 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005446 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005447 }
5448 }
5449
Richard Smithd62306a2011-11-10 06:34:14 +00005450 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005451 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005452}
5453
Peter Collingbournee9200682011-05-13 03:29:01 +00005454bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005455 // FIXME: Deal with vectors as array subscript bases.
5456 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005457 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005458
Nick Lewyckyad888682017-04-27 07:27:36 +00005459 bool Success = true;
5460 if (!evaluatePointer(E->getBase(), Result)) {
5461 if (!Info.noteFailure())
5462 return false;
5463 Success = false;
5464 }
Mike Stump11289f42009-09-09 15:08:12 +00005465
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005466 APSInt Index;
5467 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005468 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005469
Nick Lewyckyad888682017-04-27 07:27:36 +00005470 return Success &&
5471 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005472}
Eli Friedman9a156e52008-11-12 09:44:48 +00005473
Peter Collingbournee9200682011-05-13 03:29:01 +00005474bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005475 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005476}
5477
Richard Smith66c96992012-02-18 22:04:06 +00005478bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5479 if (!Visit(E->getSubExpr()))
5480 return false;
5481 // __real is a no-op on scalar lvalues.
5482 if (E->getSubExpr()->getType()->isAnyComplexType())
5483 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5484 return true;
5485}
5486
5487bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5488 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5489 "lvalue __imag__ on scalar?");
5490 if (!Visit(E->getSubExpr()))
5491 return false;
5492 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5493 return true;
5494}
5495
Richard Smith243ef902013-05-05 23:31:59 +00005496bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005497 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005498 return Error(UO);
5499
5500 if (!this->Visit(UO->getSubExpr()))
5501 return false;
5502
Richard Smith243ef902013-05-05 23:31:59 +00005503 return handleIncDec(
5504 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005505 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005506}
5507
5508bool LValueExprEvaluator::VisitCompoundAssignOperator(
5509 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005510 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005511 return Error(CAO);
5512
Richard Smith3229b742013-05-05 21:17:10 +00005513 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005514
5515 // The overall lvalue result is the result of evaluating the LHS.
5516 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005517 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005518 Evaluate(RHS, this->Info, CAO->getRHS());
5519 return false;
5520 }
5521
Richard Smith3229b742013-05-05 21:17:10 +00005522 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5523 return false;
5524
Richard Smith43e77732013-05-07 04:50:00 +00005525 return handleCompoundAssignment(
5526 this->Info, CAO,
5527 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5528 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005529}
5530
5531bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005532 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005533 return Error(E);
5534
Richard Smith3229b742013-05-05 21:17:10 +00005535 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005536
5537 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005538 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005539 Evaluate(NewVal, this->Info, E->getRHS());
5540 return false;
5541 }
5542
Richard Smith3229b742013-05-05 21:17:10 +00005543 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5544 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005545
5546 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005547 NewVal);
5548}
5549
Eli Friedman9a156e52008-11-12 09:44:48 +00005550//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005551// Pointer Evaluation
5552//===----------------------------------------------------------------------===//
5553
George Burgess IVe3763372016-12-22 02:50:20 +00005554/// \brief Attempts to compute the number of bytes available at the pointer
5555/// returned by a function with the alloc_size attribute. Returns true if we
5556/// were successful. Places an unsigned number into `Result`.
5557///
5558/// This expects the given CallExpr to be a call to a function with an
5559/// alloc_size attribute.
5560static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5561 const CallExpr *Call,
5562 llvm::APInt &Result) {
5563 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5564
Joel E. Denny81508102018-03-13 14:51:22 +00005565 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5566 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005567 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5568 if (Call->getNumArgs() <= SizeArgNo)
5569 return false;
5570
5571 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5572 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5573 return false;
5574 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5575 return false;
5576 Into = Into.zextOrSelf(BitsInSizeT);
5577 return true;
5578 };
5579
5580 APSInt SizeOfElem;
5581 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5582 return false;
5583
Joel E. Denny81508102018-03-13 14:51:22 +00005584 if (!AllocSize->getNumElemsParam().isValid()) {
George Burgess IVe3763372016-12-22 02:50:20 +00005585 Result = std::move(SizeOfElem);
5586 return true;
5587 }
5588
5589 APSInt NumberOfElems;
Joel E. Denny81508102018-03-13 14:51:22 +00005590 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
George Burgess IVe3763372016-12-22 02:50:20 +00005591 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5592 return false;
5593
5594 bool Overflow;
5595 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5596 if (Overflow)
5597 return false;
5598
5599 Result = std::move(BytesAvailable);
5600 return true;
5601}
5602
5603/// \brief Convenience function. LVal's base must be a call to an alloc_size
5604/// function.
5605static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5606 const LValue &LVal,
5607 llvm::APInt &Result) {
5608 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5609 "Can't get the size of a non alloc_size function");
5610 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5611 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5612 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5613}
5614
5615/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5616/// a function with the alloc_size attribute. If it was possible to do so, this
5617/// function will return true, make Result's Base point to said function call,
5618/// and mark Result's Base as invalid.
5619static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5620 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005621 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005622 return false;
5623
5624 // Because we do no form of static analysis, we only support const variables.
5625 //
5626 // Additionally, we can't support parameters, nor can we support static
5627 // variables (in the latter case, use-before-assign isn't UB; in the former,
5628 // we have no clue what they'll be assigned to).
5629 const auto *VD =
5630 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5631 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5632 return false;
5633
5634 const Expr *Init = VD->getAnyInitializer();
5635 if (!Init)
5636 return false;
5637
5638 const Expr *E = Init->IgnoreParens();
5639 if (!tryUnwrapAllocSizeCall(E))
5640 return false;
5641
5642 // Store E instead of E unwrapped so that the type of the LValue's base is
5643 // what the user wanted.
5644 Result.setInvalid(E);
5645
5646 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005647 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005648 return true;
5649}
5650
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005651namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005652class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005653 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005654 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005655 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005656
Peter Collingbournee9200682011-05-13 03:29:01 +00005657 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005658 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005659 return true;
5660 }
George Burgess IVe3763372016-12-22 02:50:20 +00005661
George Burgess IVf9013bf2017-02-10 22:52:29 +00005662 bool evaluateLValue(const Expr *E, LValue &Result) {
5663 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5664 }
5665
5666 bool evaluatePointer(const Expr *E, LValue &Result) {
5667 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5668 }
5669
George Burgess IVe3763372016-12-22 02:50:20 +00005670 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005671public:
Mike Stump11289f42009-09-09 15:08:12 +00005672
George Burgess IVf9013bf2017-02-10 22:52:29 +00005673 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5674 : ExprEvaluatorBaseTy(info), Result(Result),
5675 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005676
Richard Smith2e312c82012-03-03 22:46:17 +00005677 bool Success(const APValue &V, const Expr *E) {
5678 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005679 return true;
5680 }
Richard Smithfddd3842011-12-30 21:15:51 +00005681 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005682 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5683 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005684 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005685 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005686
John McCall45d55e42010-05-07 21:00:08 +00005687 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005688 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005689 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005690 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005691 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005692 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5693 if (Info.noteFailure())
5694 EvaluateIgnoredValue(Info, E->getSubExpr());
5695 return Error(E);
5696 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005697 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005698 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005699 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005700 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005701 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005702 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005703 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005704 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005705 }
Richard Smithd62306a2011-11-10 06:34:14 +00005706 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005707 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005708 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005709 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005710 if (!Info.CurrentCall->This) {
5711 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005712 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005713 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005714 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005715 return false;
5716 }
Richard Smithd62306a2011-11-10 06:34:14 +00005717 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005718 // If we are inside a lambda's call operator, the 'this' expression refers
5719 // to the enclosing '*this' object (either by value or reference) which is
5720 // either copied into the closure object's field that represents the '*this'
5721 // or refers to '*this'.
5722 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5723 // Update 'Result' to refer to the data member/field of the closure object
5724 // that represents the '*this' capture.
5725 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005726 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005727 return false;
5728 // If we captured '*this' by reference, replace the field with its referent.
5729 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5730 ->isPointerType()) {
5731 APValue RVal;
5732 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5733 RVal))
5734 return false;
5735
5736 Result.setFrom(Info.Ctx, RVal);
5737 }
5738 }
Richard Smithd62306a2011-11-10 06:34:14 +00005739 return true;
5740 }
John McCallc07a0c72011-02-17 10:25:35 +00005741
Eli Friedman449fe542009-03-23 04:56:01 +00005742 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005743};
Chris Lattner05706e882008-07-11 18:11:29 +00005744} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005745
George Burgess IVf9013bf2017-02-10 22:52:29 +00005746static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5747 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005748 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005749 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005750}
5751
John McCall45d55e42010-05-07 21:00:08 +00005752bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005753 if (E->getOpcode() != BO_Add &&
5754 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005755 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005756
Chris Lattner05706e882008-07-11 18:11:29 +00005757 const Expr *PExp = E->getLHS();
5758 const Expr *IExp = E->getRHS();
5759 if (IExp->getType()->isPointerType())
5760 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005761
George Burgess IVf9013bf2017-02-10 22:52:29 +00005762 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005763 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005764 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005765
John McCall45d55e42010-05-07 21:00:08 +00005766 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005767 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005768 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005769
Richard Smith96e0c102011-11-04 02:25:55 +00005770 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005771 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005772
Ted Kremenek28831752012-08-23 20:46:57 +00005773 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005774 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005775}
Eli Friedman9a156e52008-11-12 09:44:48 +00005776
John McCall45d55e42010-05-07 21:00:08 +00005777bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005778 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005779}
Mike Stump11289f42009-09-09 15:08:12 +00005780
Peter Collingbournee9200682011-05-13 03:29:01 +00005781bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5782 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005783
Eli Friedman847a2bc2009-12-27 05:43:15 +00005784 switch (E->getCastKind()) {
5785 default:
5786 break;
5787
John McCalle3027922010-08-25 11:45:40 +00005788 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005789 case CK_CPointerToObjCPointerCast:
5790 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005791 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005792 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005793 if (!Visit(SubExpr))
5794 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005795 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5796 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5797 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005798 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005799 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005800 if (SubExpr->getType()->isVoidPointerType())
5801 CCEDiag(E, diag::note_constexpr_invalid_cast)
5802 << 3 << SubExpr->getType();
5803 else
5804 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5805 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005806 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5807 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005808 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005809
Anders Carlsson18275092010-10-31 20:41:46 +00005810 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005811 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005812 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005813 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005814 if (!Result.Base && Result.Offset.isZero())
5815 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005816
Richard Smithd62306a2011-11-10 06:34:14 +00005817 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005818 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005819 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5820 castAs<PointerType>()->getPointeeType(),
5821 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005822
Richard Smith027bf112011-11-17 22:56:20 +00005823 case CK_BaseToDerived:
5824 if (!Visit(E->getSubExpr()))
5825 return false;
5826 if (!Result.Base && Result.Offset.isZero())
5827 return true;
5828 return HandleBaseToDerivedCast(Info, E, Result);
5829
Richard Smith0b0a0b62011-10-29 20:57:55 +00005830 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005831 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005832 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005833
John McCalle3027922010-08-25 11:45:40 +00005834 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005835 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5836
Richard Smith2e312c82012-03-03 22:46:17 +00005837 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005838 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005839 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005840
John McCall45d55e42010-05-07 21:00:08 +00005841 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005842 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5843 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005844 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005845 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005846 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith96e0c102011-11-04 02:25:55 +00005847 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005848 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005849 return true;
5850 } else {
5851 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005852 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005853 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005854 }
5855 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005856
5857 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005858 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005859 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005860 return false;
5861 } else {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00005862 APValue &Value = createTemporary(SubExpr, false, Result,
5863 *Info.CurrentCall);
5864 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005865 return false;
5866 }
Richard Smith96e0c102011-11-04 02:25:55 +00005867 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005868 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5869 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005870 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005871 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005872 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005873 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005874 }
Richard Smithdd785442011-10-31 20:57:44 +00005875
John McCalle3027922010-08-25 11:45:40 +00005876 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005877 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005878
5879 case CK_LValueToRValue: {
5880 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005881 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005882 return false;
5883
5884 APValue RVal;
5885 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5886 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5887 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005888 return InvalidBaseOK &&
5889 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005890 return Success(RVal, E);
5891 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005892 }
5893
Richard Smith11562c52011-10-28 17:51:58 +00005894 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005895}
Chris Lattner05706e882008-07-11 18:11:29 +00005896
Hal Finkel0dd05d42014-10-03 17:18:37 +00005897static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5898 // C++ [expr.alignof]p3:
5899 // When alignof is applied to a reference type, the result is the
5900 // alignment of the referenced type.
5901 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5902 T = Ref->getPointeeType();
5903
5904 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005905 if (T.getQualifiers().hasUnaligned())
5906 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005907 return Info.Ctx.toCharUnitsFromBits(
5908 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5909}
5910
5911static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5912 E = E->IgnoreParens();
5913
5914 // The kinds of expressions that we have special-case logic here for
5915 // should be kept up to date with the special checks for those
5916 // expressions in Sema.
5917
5918 // alignof decl is always accepted, even if it doesn't make sense: we default
5919 // to 1 in those cases.
5920 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5921 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5922 /*RefAsPointee*/true);
5923
5924 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5925 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5926 /*RefAsPointee*/true);
5927
5928 return GetAlignOfType(Info, E->getType());
5929}
5930
George Burgess IVe3763372016-12-22 02:50:20 +00005931// To be clear: this happily visits unsupported builtins. Better name welcomed.
5932bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5933 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5934 return true;
5935
George Burgess IVf9013bf2017-02-10 22:52:29 +00005936 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005937 return false;
5938
5939 Result.setInvalid(E);
5940 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005941 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005942 return true;
5943}
5944
Peter Collingbournee9200682011-05-13 03:29:01 +00005945bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005946 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005947 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005948
Richard Smith6328cbd2016-11-16 00:57:23 +00005949 if (unsigned BuiltinOp = E->getBuiltinCallee())
5950 return VisitBuiltinCallExpr(E, BuiltinOp);
5951
George Burgess IVe3763372016-12-22 02:50:20 +00005952 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005953}
5954
5955bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5956 unsigned BuiltinOp) {
5957 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005958 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005959 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005960 case Builtin::BI__builtin_assume_aligned: {
5961 // We need to be very careful here because: if the pointer does not have the
5962 // asserted alignment, then the behavior is undefined, and undefined
5963 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005964 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005965 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005966
Hal Finkel0dd05d42014-10-03 17:18:37 +00005967 LValue OffsetResult(Result);
5968 APSInt Alignment;
5969 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5970 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005971 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005972
5973 if (E->getNumArgs() > 2) {
5974 APSInt Offset;
5975 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5976 return false;
5977
Richard Smith642a2362017-01-30 23:30:26 +00005978 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005979 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5980 }
5981
5982 // If there is a base object, then it must have the correct alignment.
5983 if (OffsetResult.Base) {
5984 CharUnits BaseAlignment;
5985 if (const ValueDecl *VD =
5986 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5987 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5988 } else {
5989 BaseAlignment =
5990 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5991 }
5992
5993 if (BaseAlignment < Align) {
5994 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005995 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005996 CCEDiag(E->getArg(0),
5997 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005998 << (unsigned)BaseAlignment.getQuantity()
5999 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006000 return false;
6001 }
6002 }
6003
6004 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006005 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00006006 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006007
Richard Smith642a2362017-01-30 23:30:26 +00006008 (OffsetResult.Base
6009 ? CCEDiag(E->getArg(0),
6010 diag::note_constexpr_baa_insufficient_alignment) << 1
6011 : CCEDiag(E->getArg(0),
6012 diag::note_constexpr_baa_value_insufficient_alignment))
6013 << (int)OffsetResult.Offset.getQuantity()
6014 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00006015 return false;
6016 }
6017
6018 return true;
6019 }
Richard Smithe9507952016-11-12 01:39:56 +00006020
6021 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006022 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00006023 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006024 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00006025 if (Info.getLangOpts().CPlusPlus11)
6026 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6027 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00006028 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00006029 else
6030 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006031 LLVM_FALLTHROUGH;
Richard Smithe9507952016-11-12 01:39:56 +00006032 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006033 case Builtin::BI__builtin_wcschr:
6034 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006035 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006036 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00006037 if (!Visit(E->getArg(0)))
6038 return false;
6039 APSInt Desired;
6040 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6041 return false;
6042 uint64_t MaxLength = uint64_t(-1);
6043 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00006044 BuiltinOp != Builtin::BIwcschr &&
6045 BuiltinOp != Builtin::BI__builtin_strchr &&
6046 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00006047 APSInt N;
6048 if (!EvaluateInteger(E->getArg(2), N, Info))
6049 return false;
6050 MaxLength = N.getExtValue();
6051 }
6052
Richard Smith8110c9d2016-11-29 19:45:17 +00006053 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00006054
Richard Smith8110c9d2016-11-29 19:45:17 +00006055 // Figure out what value we're actually looking for (after converting to
6056 // the corresponding unsigned type if necessary).
6057 uint64_t DesiredVal;
6058 bool StopAtNull = false;
6059 switch (BuiltinOp) {
6060 case Builtin::BIstrchr:
6061 case Builtin::BI__builtin_strchr:
6062 // strchr compares directly to the passed integer, and therefore
6063 // always fails if given an int that is not a char.
6064 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6065 E->getArg(1)->getType(),
6066 Desired),
6067 Desired))
6068 return ZeroInitialization(E);
6069 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006070 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006071 case Builtin::BImemchr:
6072 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00006073 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00006074 // memchr compares by converting both sides to unsigned char. That's also
6075 // correct for strchr if we get this far (to cope with plain char being
6076 // unsigned in the strchr case).
6077 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6078 break;
Richard Smithe9507952016-11-12 01:39:56 +00006079
Richard Smith8110c9d2016-11-29 19:45:17 +00006080 case Builtin::BIwcschr:
6081 case Builtin::BI__builtin_wcschr:
6082 StopAtNull = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00006083 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00006084 case Builtin::BIwmemchr:
6085 case Builtin::BI__builtin_wmemchr:
6086 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6087 DesiredVal = Desired.getZExtValue();
6088 break;
6089 }
Richard Smithe9507952016-11-12 01:39:56 +00006090
6091 for (; MaxLength; --MaxLength) {
6092 APValue Char;
6093 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6094 !Char.isInt())
6095 return false;
6096 if (Char.getInt().getZExtValue() == DesiredVal)
6097 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00006098 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00006099 break;
6100 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6101 return false;
6102 }
6103 // Not found: return nullptr.
6104 return ZeroInitialization(E);
6105 }
6106
Richard Smith6cbd65d2013-07-11 02:27:57 +00006107 default:
George Burgess IVe3763372016-12-22 02:50:20 +00006108 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00006109 }
Eli Friedman9a156e52008-11-12 09:44:48 +00006110}
Chris Lattner05706e882008-07-11 18:11:29 +00006111
6112//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006113// Member Pointer Evaluation
6114//===----------------------------------------------------------------------===//
6115
6116namespace {
6117class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006118 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006119 MemberPtr &Result;
6120
6121 bool Success(const ValueDecl *D) {
6122 Result = MemberPtr(D);
6123 return true;
6124 }
6125public:
6126
6127 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6128 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6129
Richard Smith2e312c82012-03-03 22:46:17 +00006130 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006131 Result.setFrom(V);
6132 return true;
6133 }
Richard Smithfddd3842011-12-30 21:15:51 +00006134 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006135 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006136 }
6137
6138 bool VisitCastExpr(const CastExpr *E);
6139 bool VisitUnaryAddrOf(const UnaryOperator *E);
6140};
6141} // end anonymous namespace
6142
6143static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6144 EvalInfo &Info) {
6145 assert(E->isRValue() && E->getType()->isMemberPointerType());
6146 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6147}
6148
6149bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6150 switch (E->getCastKind()) {
6151 default:
6152 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6153
6154 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006155 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006156 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006157
6158 case CK_BaseToDerivedMemberPointer: {
6159 if (!Visit(E->getSubExpr()))
6160 return false;
6161 if (E->path_empty())
6162 return true;
6163 // Base-to-derived member pointer casts store the path in derived-to-base
6164 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6165 // the wrong end of the derived->base arc, so stagger the path by one class.
6166 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6167 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6168 PathI != PathE; ++PathI) {
6169 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6170 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6171 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006172 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006173 }
6174 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6175 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006176 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006177 return true;
6178 }
6179
6180 case CK_DerivedToBaseMemberPointer:
6181 if (!Visit(E->getSubExpr()))
6182 return false;
6183 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6184 PathE = E->path_end(); PathI != PathE; ++PathI) {
6185 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6186 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6187 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006188 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006189 }
6190 return true;
6191 }
6192}
6193
6194bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6195 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6196 // member can be formed.
6197 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6198}
6199
6200//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006201// Record Evaluation
6202//===----------------------------------------------------------------------===//
6203
6204namespace {
6205 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006206 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006207 const LValue &This;
6208 APValue &Result;
6209 public:
6210
6211 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6212 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6213
Richard Smith2e312c82012-03-03 22:46:17 +00006214 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006215 Result = V;
6216 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006217 }
Richard Smithb8348f52016-05-12 22:16:28 +00006218 bool ZeroInitialization(const Expr *E) {
6219 return ZeroInitialization(E, E->getType());
6220 }
6221 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006222
Richard Smith52a980a2015-08-28 02:43:42 +00006223 bool VisitCallExpr(const CallExpr *E) {
6224 return handleCallExpr(E, Result, &This);
6225 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006226 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006227 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006228 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6229 return VisitCXXConstructExpr(E, E->getType());
6230 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006231 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006232 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006233 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006234 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006235 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006236}
Richard Smithd62306a2011-11-10 06:34:14 +00006237
Richard Smithfddd3842011-12-30 21:15:51 +00006238/// Perform zero-initialization on an object of non-union class type.
6239/// C++11 [dcl.init]p5:
6240/// To zero-initialize an object or reference of type T means:
6241/// [...]
6242/// -- if T is a (possibly cv-qualified) non-union class type,
6243/// each non-static data member and each base-class subobject is
6244/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006245static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6246 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006247 const LValue &This, APValue &Result) {
6248 assert(!RD->isUnion() && "Expected non-union class type");
6249 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6250 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006251 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006252
John McCalld7bca762012-05-01 00:38:49 +00006253 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006254 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6255
6256 if (CD) {
6257 unsigned Index = 0;
6258 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006259 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006260 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6261 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006262 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6263 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006264 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006265 Result.getStructBase(Index)))
6266 return false;
6267 }
6268 }
6269
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006270 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006271 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006272 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006273 continue;
6274
6275 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006276 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006277 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006278
David Blaikie2d7c57e2012-04-30 02:36:29 +00006279 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006280 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006281 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006282 return false;
6283 }
6284
6285 return true;
6286}
6287
Richard Smithb8348f52016-05-12 22:16:28 +00006288bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6289 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006290 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006291 if (RD->isUnion()) {
6292 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6293 // object's first non-static named data member is zero-initialized
6294 RecordDecl::field_iterator I = RD->field_begin();
6295 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006296 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006297 return true;
6298 }
6299
6300 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006301 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006302 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006303 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006304 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006305 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006306 }
6307
Richard Smith5d108602012-02-17 00:44:16 +00006308 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006309 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006310 return false;
6311 }
6312
Richard Smitha8105bc2012-01-06 16:39:00 +00006313 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006314}
6315
Richard Smithe97cbd72011-11-11 04:05:33 +00006316bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6317 switch (E->getCastKind()) {
6318 default:
6319 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6320
6321 case CK_ConstructorConversion:
6322 return Visit(E->getSubExpr());
6323
6324 case CK_DerivedToBase:
6325 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006326 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006327 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006328 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006329 if (!DerivedObject.isStruct())
6330 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006331
6332 // Derived-to-base rvalue conversion: just slice off the derived part.
6333 APValue *Value = &DerivedObject;
6334 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6335 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6336 PathE = E->path_end(); PathI != PathE; ++PathI) {
6337 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6338 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6339 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6340 RD = Base;
6341 }
6342 Result = *Value;
6343 return true;
6344 }
6345 }
6346}
6347
Richard Smithd62306a2011-11-10 06:34:14 +00006348bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006349 if (E->isTransparent())
6350 return Visit(E->getInit(0));
6351
Richard Smithd62306a2011-11-10 06:34:14 +00006352 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006353 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006354 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6355
6356 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006357 const FieldDecl *Field = E->getInitializedFieldInUnion();
6358 Result = APValue(Field);
6359 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006360 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006361
6362 // If the initializer list for a union does not contain any elements, the
6363 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006364 // FIXME: The element should be initialized from an initializer list.
6365 // Is this difference ever observable for initializer lists which
6366 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006367 ImplicitValueInitExpr VIE(Field->getType());
6368 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6369
Richard Smithd62306a2011-11-10 06:34:14 +00006370 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006371 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6372 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006373
6374 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6375 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6376 isa<CXXDefaultInitExpr>(InitExpr));
6377
Richard Smithb228a862012-02-15 02:18:13 +00006378 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006379 }
6380
Richard Smith872307e2016-03-08 22:17:41 +00006381 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006382 if (Result.isUninit())
6383 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6384 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006385 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006386 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006387
6388 // Initialize base classes.
6389 if (CXXRD) {
6390 for (const auto &Base : CXXRD->bases()) {
6391 assert(ElementNo < E->getNumInits() && "missing init for base class");
6392 const Expr *Init = E->getInit(ElementNo);
6393
6394 LValue Subobject = This;
6395 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6396 return false;
6397
6398 APValue &FieldVal = Result.getStructBase(ElementNo);
6399 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006400 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006401 return false;
6402 Success = false;
6403 }
6404 ++ElementNo;
6405 }
6406 }
6407
6408 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006409 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006410 // Anonymous bit-fields are not considered members of the class for
6411 // purposes of aggregate initialization.
6412 if (Field->isUnnamedBitfield())
6413 continue;
6414
6415 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006416
Richard Smith253c2a32012-01-27 01:14:48 +00006417 bool HaveInit = ElementNo < E->getNumInits();
6418
6419 // FIXME: Diagnostics here should point to the end of the initializer
6420 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006421 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006422 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006423 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006424
6425 // Perform an implicit value-initialization for members beyond the end of
6426 // the initializer list.
6427 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006428 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006429
Richard Smith852c9db2013-04-20 22:23:05 +00006430 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6431 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6432 isa<CXXDefaultInitExpr>(Init));
6433
Richard Smith49ca8aa2013-08-06 07:09:20 +00006434 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6435 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6436 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006437 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006438 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006439 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006440 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006441 }
6442 }
6443
Richard Smith253c2a32012-01-27 01:14:48 +00006444 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006445}
6446
Richard Smithb8348f52016-05-12 22:16:28 +00006447bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6448 QualType T) {
6449 // Note that E's type is not necessarily the type of our class here; we might
6450 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006451 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006452 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6453
Richard Smithfddd3842011-12-30 21:15:51 +00006454 bool ZeroInit = E->requiresZeroInitialization();
6455 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006456 // If we've already performed zero-initialization, we're already done.
6457 if (!Result.isUninit())
6458 return true;
6459
Richard Smithda3f4fd2014-03-05 23:32:50 +00006460 // We can get here in two different ways:
6461 // 1) We're performing value-initialization, and should zero-initialize
6462 // the object, or
6463 // 2) We're performing default-initialization of an object with a trivial
6464 // constexpr default constructor, in which case we should start the
6465 // lifetimes of all the base subobjects (there can be no data member
6466 // subobjects in this case) per [basic.life]p1.
6467 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006468 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006469 }
6470
Craig Topper36250ad2014-05-12 05:36:57 +00006471 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006472 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006473
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006474 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006475 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006476
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006477 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006478 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006479 if (const MaterializeTemporaryExpr *ME
6480 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6481 return Visit(ME->GetTemporaryExpr());
6482
Richard Smithb8348f52016-05-12 22:16:28 +00006483 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006484 return false;
6485
Craig Topper5fc8fc22014-08-27 06:28:36 +00006486 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006487 return HandleConstructorCall(E, This, Args,
6488 cast<CXXConstructorDecl>(Definition), Info,
6489 Result);
6490}
6491
6492bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6493 const CXXInheritedCtorInitExpr *E) {
6494 if (!Info.CurrentCall) {
6495 assert(Info.checkingPotentialConstantExpression());
6496 return false;
6497 }
6498
6499 const CXXConstructorDecl *FD = E->getConstructor();
6500 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6501 return false;
6502
6503 const FunctionDecl *Definition = nullptr;
6504 auto Body = FD->getBody(Definition);
6505
6506 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6507 return false;
6508
6509 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006510 cast<CXXConstructorDecl>(Definition), Info,
6511 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006512}
6513
Richard Smithcc1b96d2013-06-12 22:31:48 +00006514bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6515 const CXXStdInitializerListExpr *E) {
6516 const ConstantArrayType *ArrayType =
6517 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6518
6519 LValue Array;
6520 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6521 return false;
6522
6523 // Get a pointer to the first element of the array.
6524 Array.addArray(Info, E, ArrayType);
6525
6526 // FIXME: Perform the checks on the field types in SemaInit.
6527 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6528 RecordDecl::field_iterator Field = Record->field_begin();
6529 if (Field == Record->field_end())
6530 return Error(E);
6531
6532 // Start pointer.
6533 if (!Field->getType()->isPointerType() ||
6534 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6535 ArrayType->getElementType()))
6536 return Error(E);
6537
6538 // FIXME: What if the initializer_list type has base classes, etc?
6539 Result = APValue(APValue::UninitStruct(), 0, 2);
6540 Array.moveInto(Result.getStructField(0));
6541
6542 if (++Field == Record->field_end())
6543 return Error(E);
6544
6545 if (Field->getType()->isPointerType() &&
6546 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6547 ArrayType->getElementType())) {
6548 // End pointer.
6549 if (!HandleLValueArrayAdjustment(Info, E, Array,
6550 ArrayType->getElementType(),
6551 ArrayType->getSize().getZExtValue()))
6552 return false;
6553 Array.moveInto(Result.getStructField(1));
6554 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6555 // Length.
6556 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6557 else
6558 return Error(E);
6559
6560 if (++Field != Record->field_end())
6561 return Error(E);
6562
6563 return true;
6564}
6565
Faisal Valic72a08c2017-01-09 03:02:53 +00006566bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6567 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6568 if (ClosureClass->isInvalidDecl()) return false;
6569
6570 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006571
Faisal Vali051e3a22017-02-16 04:12:21 +00006572 const size_t NumFields =
6573 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006574
6575 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6576 E->capture_init_end()) &&
6577 "The number of lambda capture initializers should equal the number of "
6578 "fields within the closure type");
6579
Faisal Vali051e3a22017-02-16 04:12:21 +00006580 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6581 // Iterate through all the lambda's closure object's fields and initialize
6582 // them.
6583 auto *CaptureInitIt = E->capture_init_begin();
6584 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6585 bool Success = true;
6586 for (const auto *Field : ClosureClass->fields()) {
6587 assert(CaptureInitIt != E->capture_init_end());
6588 // Get the initializer for this field
6589 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006590
Faisal Vali051e3a22017-02-16 04:12:21 +00006591 // If there is no initializer, either this is a VLA or an error has
6592 // occurred.
6593 if (!CurFieldInit)
6594 return Error(E);
6595
6596 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6597 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6598 if (!Info.keepEvaluatingAfterFailure())
6599 return false;
6600 Success = false;
6601 }
6602 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006603 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006604 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006605}
6606
Richard Smithd62306a2011-11-10 06:34:14 +00006607static bool EvaluateRecord(const Expr *E, const LValue &This,
6608 APValue &Result, EvalInfo &Info) {
6609 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006610 "can't evaluate expression as a record rvalue");
6611 return RecordExprEvaluator(Info, This, Result).Visit(E);
6612}
6613
6614//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006615// Temporary Evaluation
6616//
6617// Temporaries are represented in the AST as rvalues, but generally behave like
6618// lvalues. The full-object of which the temporary is a subobject is implicitly
6619// materialized so that a reference can bind to it.
6620//===----------------------------------------------------------------------===//
6621namespace {
6622class TemporaryExprEvaluator
6623 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6624public:
6625 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006626 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006627
6628 /// Visit an expression which constructs the value of this temporary.
6629 bool VisitConstructExpr(const Expr *E) {
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00006630 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6631 return EvaluateInPlace(Value, Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006632 }
6633
6634 bool VisitCastExpr(const CastExpr *E) {
6635 switch (E->getCastKind()) {
6636 default:
6637 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6638
6639 case CK_ConstructorConversion:
6640 return VisitConstructExpr(E->getSubExpr());
6641 }
6642 }
6643 bool VisitInitListExpr(const InitListExpr *E) {
6644 return VisitConstructExpr(E);
6645 }
6646 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6647 return VisitConstructExpr(E);
6648 }
6649 bool VisitCallExpr(const CallExpr *E) {
6650 return VisitConstructExpr(E);
6651 }
Richard Smith513955c2014-12-17 19:24:30 +00006652 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6653 return VisitConstructExpr(E);
6654 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006655 bool VisitLambdaExpr(const LambdaExpr *E) {
6656 return VisitConstructExpr(E);
6657 }
Richard Smith027bf112011-11-17 22:56:20 +00006658};
6659} // end anonymous namespace
6660
6661/// Evaluate an expression of record type as a temporary.
6662static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006663 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006664 return TemporaryExprEvaluator(Info, Result).Visit(E);
6665}
6666
6667//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006668// Vector Evaluation
6669//===----------------------------------------------------------------------===//
6670
6671namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006672 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006673 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006674 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006675 public:
Mike Stump11289f42009-09-09 15:08:12 +00006676
Richard Smith2d406342011-10-22 21:10:00 +00006677 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6678 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006679
Craig Topper9798b932015-09-29 04:30:05 +00006680 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006681 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6682 // FIXME: remove this APValue copy.
6683 Result = APValue(V.data(), V.size());
6684 return true;
6685 }
Richard Smith2e312c82012-03-03 22:46:17 +00006686 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006687 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006688 Result = V;
6689 return true;
6690 }
Richard Smithfddd3842011-12-30 21:15:51 +00006691 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006692
Richard Smith2d406342011-10-22 21:10:00 +00006693 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006694 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006695 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006696 bool VisitInitListExpr(const InitListExpr *E);
6697 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006698 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006699 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006700 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006701 };
6702} // end anonymous namespace
6703
6704static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006705 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006706 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006707}
6708
George Burgess IV533ff002015-12-11 00:23:35 +00006709bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006710 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006711 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006712
Richard Smith161f09a2011-12-06 22:44:34 +00006713 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006714 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006715
Eli Friedmanc757de22011-03-25 00:43:55 +00006716 switch (E->getCastKind()) {
6717 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006718 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006719 if (SETy->isIntegerType()) {
6720 APSInt IntResult;
6721 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006722 return false;
6723 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006724 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006725 APFloat FloatResult(0.0);
6726 if (!EvaluateFloat(SE, FloatResult, Info))
6727 return false;
6728 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006729 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006730 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006731 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006732
6733 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006734 SmallVector<APValue, 4> Elts(NElts, Val);
6735 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006736 }
Eli Friedman803acb32011-12-22 03:51:45 +00006737 case CK_BitCast: {
6738 // Evaluate the operand into an APInt we can extract from.
6739 llvm::APInt SValInt;
6740 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6741 return false;
6742 // Extract the elements
6743 QualType EltTy = VTy->getElementType();
6744 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6745 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6746 SmallVector<APValue, 4> Elts;
6747 if (EltTy->isRealFloatingType()) {
6748 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006749 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006750 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006751 FloatEltSize = 80;
6752 for (unsigned i = 0; i < NElts; i++) {
6753 llvm::APInt Elt;
6754 if (BigEndian)
6755 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6756 else
6757 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006758 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006759 }
6760 } else if (EltTy->isIntegerType()) {
6761 for (unsigned i = 0; i < NElts; i++) {
6762 llvm::APInt Elt;
6763 if (BigEndian)
6764 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6765 else
6766 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6767 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6768 }
6769 } else {
6770 return Error(E);
6771 }
6772 return Success(Elts, E);
6773 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006774 default:
Richard Smith11562c52011-10-28 17:51:58 +00006775 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006776 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006777}
6778
Richard Smith2d406342011-10-22 21:10:00 +00006779bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006780VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006781 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006782 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006783 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006784
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006785 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006786 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006787
Eli Friedmanb9c71292012-01-03 23:24:20 +00006788 // The number of initializers can be less than the number of
6789 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006790 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006791 // should be initialized with zeroes.
6792 unsigned CountInits = 0, CountElts = 0;
6793 while (CountElts < NumElements) {
6794 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006795 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006796 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006797 APValue v;
6798 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6799 return Error(E);
6800 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006801 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006802 Elements.push_back(v.getVectorElt(j));
6803 CountElts += vlen;
6804 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006805 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006806 if (CountInits < NumInits) {
6807 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006808 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006809 } else // trailing integer zero.
6810 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6811 Elements.push_back(APValue(sInt));
6812 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006813 } else {
6814 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006815 if (CountInits < NumInits) {
6816 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006817 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006818 } else // trailing float zero.
6819 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6820 Elements.push_back(APValue(f));
6821 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006822 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006823 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006824 }
Richard Smith2d406342011-10-22 21:10:00 +00006825 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006826}
6827
Richard Smith2d406342011-10-22 21:10:00 +00006828bool
Richard Smithfddd3842011-12-30 21:15:51 +00006829VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006830 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006831 QualType EltTy = VT->getElementType();
6832 APValue ZeroElement;
6833 if (EltTy->isIntegerType())
6834 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6835 else
6836 ZeroElement =
6837 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6838
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006839 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006840 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006841}
6842
Richard Smith2d406342011-10-22 21:10:00 +00006843bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006844 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006845 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006846}
6847
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006848//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006849// Array Evaluation
6850//===----------------------------------------------------------------------===//
6851
6852namespace {
6853 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006854 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006855 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006856 APValue &Result;
6857 public:
6858
Richard Smithd62306a2011-11-10 06:34:14 +00006859 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6860 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006861
6862 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006863 assert((V.isArray() || V.isLValue()) &&
6864 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006865 Result = V;
6866 return true;
6867 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006868
Richard Smithfddd3842011-12-30 21:15:51 +00006869 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006870 const ConstantArrayType *CAT =
6871 Info.Ctx.getAsConstantArrayType(E->getType());
6872 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006873 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006874
6875 Result = APValue(APValue::UninitArray(), 0,
6876 CAT->getSize().getZExtValue());
6877 if (!Result.hasArrayFiller()) return true;
6878
Richard Smithfddd3842011-12-30 21:15:51 +00006879 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006880 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006881 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006882 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006883 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006884 }
6885
Richard Smith52a980a2015-08-28 02:43:42 +00006886 bool VisitCallExpr(const CallExpr *E) {
6887 return handleCallExpr(E, Result, &This);
6888 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006889 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006890 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006891 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006892 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6893 const LValue &Subobject,
6894 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006895 };
6896} // end anonymous namespace
6897
Richard Smithd62306a2011-11-10 06:34:14 +00006898static bool EvaluateArray(const Expr *E, const LValue &This,
6899 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006900 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006901 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006902}
6903
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006904// Return true iff the given array filler may depend on the element index.
6905static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
6906 // For now, just whitelist non-class value-initialization and initialization
6907 // lists comprised of them.
6908 if (isa<ImplicitValueInitExpr>(FillerExpr))
6909 return false;
6910 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
6911 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
6912 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
6913 return true;
6914 }
6915 return false;
6916 }
6917 return true;
6918}
6919
Richard Smithf3e9e432011-11-07 09:22:26 +00006920bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6921 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6922 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006923 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006924
Richard Smithca2cfbf2011-12-22 01:07:19 +00006925 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6926 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006927 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006928 LValue LV;
6929 if (!EvaluateLValue(E->getInit(0), LV, Info))
6930 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006931 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006932 LV.moveInto(Val);
6933 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006934 }
6935
Richard Smith253c2a32012-01-27 01:14:48 +00006936 bool Success = true;
6937
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006938 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6939 "zero-initialized array shouldn't have any initialized elts");
6940 APValue Filler;
6941 if (Result.isArray() && Result.hasArrayFiller())
6942 Filler = Result.getArrayFiller();
6943
Richard Smith9543c5e2013-04-22 14:44:29 +00006944 unsigned NumEltsToInit = E->getNumInits();
6945 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006946 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006947
6948 // If the initializer might depend on the array index, run it for each
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006949 // array element.
6950 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
Richard Smith9543c5e2013-04-22 14:44:29 +00006951 NumEltsToInit = NumElts;
6952
Ivan A. Kosarev01df5192018-02-14 13:10:35 +00006953 DEBUG(llvm::dbgs() << "The number of elements to initialize: " <<
6954 NumEltsToInit << ".\n");
6955
Richard Smith9543c5e2013-04-22 14:44:29 +00006956 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006957
6958 // If the array was previously zero-initialized, preserve the
6959 // zero-initialized values.
6960 if (!Filler.isUninit()) {
6961 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6962 Result.getArrayInitializedElt(I) = Filler;
6963 if (Result.hasArrayFiller())
6964 Result.getArrayFiller() = Filler;
6965 }
6966
Richard Smithd62306a2011-11-10 06:34:14 +00006967 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006968 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006969 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6970 const Expr *Init =
6971 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006972 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006973 Info, Subobject, Init) ||
6974 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006975 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006976 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006977 return false;
6978 Success = false;
6979 }
Richard Smithd62306a2011-11-10 06:34:14 +00006980 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006981
Richard Smith9543c5e2013-04-22 14:44:29 +00006982 if (!Result.hasArrayFiller())
6983 return Success;
6984
6985 // If we get here, we have a trivial filler, which we can just evaluate
6986 // once and splat over the rest of the array elements.
6987 assert(FillerExpr && "no array filler for incomplete init list");
6988 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6989 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006990}
6991
Richard Smith410306b2016-12-12 02:53:20 +00006992bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6993 if (E->getCommonExpr() &&
6994 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6995 Info, E->getCommonExpr()->getSourceExpr()))
6996 return false;
6997
6998 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6999
7000 uint64_t Elements = CAT->getSize().getZExtValue();
7001 Result = APValue(APValue::UninitArray(), Elements, Elements);
7002
7003 LValue Subobject = This;
7004 Subobject.addArray(Info, E, CAT);
7005
7006 bool Success = true;
7007 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7008 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7009 Info, Subobject, E->getSubExpr()) ||
7010 !HandleLValueArrayAdjustment(Info, E, Subobject,
7011 CAT->getElementType(), 1)) {
7012 if (!Info.noteFailure())
7013 return false;
7014 Success = false;
7015 }
7016 }
7017
7018 return Success;
7019}
7020
Richard Smith027bf112011-11-17 22:56:20 +00007021bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00007022 return VisitCXXConstructExpr(E, This, &Result, E->getType());
7023}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007024
Richard Smith9543c5e2013-04-22 14:44:29 +00007025bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7026 const LValue &Subobject,
7027 APValue *Value,
7028 QualType Type) {
7029 bool HadZeroInit = !Value->isUninit();
7030
7031 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7032 unsigned N = CAT->getSize().getZExtValue();
7033
7034 // Preserve the array filler if we had prior zero-initialization.
7035 APValue Filler =
7036 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7037 : APValue();
7038
7039 *Value = APValue(APValue::UninitArray(), N, N);
7040
7041 if (HadZeroInit)
7042 for (unsigned I = 0; I != N; ++I)
7043 Value->getArrayInitializedElt(I) = Filler;
7044
7045 // Initialize the elements.
7046 LValue ArrayElt = Subobject;
7047 ArrayElt.addArray(Info, E, CAT);
7048 for (unsigned I = 0; I != N; ++I)
7049 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7050 CAT->getElementType()) ||
7051 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7052 CAT->getElementType(), 1))
7053 return false;
7054
7055 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00007056 }
Richard Smith027bf112011-11-17 22:56:20 +00007057
Richard Smith9543c5e2013-04-22 14:44:29 +00007058 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00007059 return Error(E);
7060
Richard Smithb8348f52016-05-12 22:16:28 +00007061 return RecordExprEvaluator(Info, Subobject, *Value)
7062 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00007063}
7064
Richard Smithf3e9e432011-11-07 09:22:26 +00007065//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007066// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00007067//
7068// As a GNU extension, we support casting pointers to sufficiently-wide integer
7069// types and back in constant folding. Integer values are thus represented
7070// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00007071//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00007072
7073namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007074class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007075 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00007076 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007077public:
Richard Smith2e312c82012-03-03 22:46:17 +00007078 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007079 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00007080
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007081 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007082 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007083 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007084 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007085 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007086 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007087 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007088 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007089 return true;
7090 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007091 bool Success(const llvm::APSInt &SI, const Expr *E) {
7092 return Success(SI, E, Result);
7093 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007094
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007095 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00007096 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007097 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007098 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00007099 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007100 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00007101 Result.getInt().setIsUnsigned(
7102 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007103 return true;
7104 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007105 bool Success(const llvm::APInt &I, const Expr *E) {
7106 return Success(I, E, Result);
7107 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007108
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007109 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00007110 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00007111 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00007112 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007113 return true;
7114 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007115 bool Success(uint64_t Value, const Expr *E) {
7116 return Success(Value, E, Result);
7117 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007118
Ken Dyckdbc01912011-03-11 02:13:43 +00007119 bool Success(CharUnits Size, const Expr *E) {
7120 return Success(Size.getQuantity(), E);
7121 }
7122
Richard Smith2e312c82012-03-03 22:46:17 +00007123 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007124 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00007125 Result = V;
7126 return true;
7127 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007128 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00007129 }
Mike Stump11289f42009-09-09 15:08:12 +00007130
Richard Smithfddd3842011-12-30 21:15:51 +00007131 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00007132
Peter Collingbournee9200682011-05-13 03:29:01 +00007133 //===--------------------------------------------------------------------===//
7134 // Visitor Methods
7135 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007136
Chris Lattner7174bf32008-07-12 00:38:25 +00007137 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007138 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007139 }
7140 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007141 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007142 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007143
7144 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7145 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007146 if (CheckReferencedDecl(E, E->getDecl()))
7147 return true;
7148
7149 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007150 }
7151 bool VisitMemberExpr(const MemberExpr *E) {
7152 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007153 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007154 return true;
7155 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007156
7157 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007158 }
7159
Peter Collingbournee9200682011-05-13 03:29:01 +00007160 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007161 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007162 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007163 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007164 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007165
Peter Collingbournee9200682011-05-13 03:29:01 +00007166 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007167 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007168
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007169 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007170 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007171 }
Mike Stump11289f42009-09-09 15:08:12 +00007172
Ted Kremeneke65b0862012-03-06 20:05:56 +00007173 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7174 return Success(E->getValue(), E);
7175 }
Richard Smith410306b2016-12-12 02:53:20 +00007176
7177 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7178 if (Info.ArrayInitIndex == uint64_t(-1)) {
7179 // We were asked to evaluate this subexpression independent of the
7180 // enclosing ArrayInitLoopExpr. We can't do that.
7181 Info.FFDiag(E);
7182 return false;
7183 }
7184 return Success(Info.ArrayInitIndex, E);
7185 }
Daniel Jasperffdee092017-05-02 19:21:42 +00007186
Richard Smith4ce706a2011-10-11 21:43:33 +00007187 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007188 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007189 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007190 }
7191
Douglas Gregor29c42f22012-02-24 07:38:34 +00007192 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7193 return Success(E->getValue(), E);
7194 }
7195
John Wiegley6242b6a2011-04-28 00:16:57 +00007196 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7197 return Success(E->getValue(), E);
7198 }
7199
John Wiegleyf9f65842011-04-25 06:54:41 +00007200 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7201 return Success(E->getValue(), E);
7202 }
7203
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007204 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007205 bool VisitUnaryImag(const UnaryOperator *E);
7206
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007207 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007208 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007209
Eli Friedman4e7a2412009-02-27 04:45:43 +00007210 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007211};
Chris Lattner05706e882008-07-11 18:11:29 +00007212} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007213
Richard Smith11562c52011-10-28 17:51:58 +00007214/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7215/// produce either the integer value or a pointer.
7216///
7217/// GCC has a heinous extension which folds casts between pointer types and
7218/// pointer-sized integral types. We support this by allowing the evaluation of
7219/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7220/// Some simple arithmetic on such values is supported (they are treated much
7221/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007222static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007223 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007224 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007225 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007226}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007227
Richard Smithf57d8cb2011-12-09 22:58:01 +00007228static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007229 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007230 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007231 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007232 if (!Val.isInt()) {
7233 // FIXME: It would be better to produce the diagnostic for casting
7234 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007235 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007236 return false;
7237 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007238 Result = Val.getInt();
7239 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007240}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007241
Richard Smithf57d8cb2011-12-09 22:58:01 +00007242/// Check whether the given declaration can be directly converted to an integral
7243/// rvalue. If not, no diagnostic is produced; there are other things we can
7244/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007245bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007246 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007247 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007248 // Check for signedness/width mismatches between E type and ECD value.
7249 bool SameSign = (ECD->getInitVal().isSigned()
7250 == E->getType()->isSignedIntegerOrEnumerationType());
7251 bool SameWidth = (ECD->getInitVal().getBitWidth()
7252 == Info.Ctx.getIntWidth(E->getType()));
7253 if (SameSign && SameWidth)
7254 return Success(ECD->getInitVal(), E);
7255 else {
7256 // Get rid of mismatch (otherwise Success assertions will fail)
7257 // by computing a new value matching the type of E.
7258 llvm::APSInt Val = ECD->getInitVal();
7259 if (!SameSign)
7260 Val.setIsSigned(!ECD->getInitVal().isSigned());
7261 if (!SameWidth)
7262 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7263 return Success(Val, E);
7264 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007265 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007266 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007267}
7268
Chris Lattner86ee2862008-10-06 06:40:35 +00007269/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7270/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007271static int EvaluateBuiltinClassifyType(const CallExpr *E,
7272 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007273 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007274 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007275 enum gcc_type_class {
7276 no_type_class = -1,
7277 void_type_class, integer_type_class, char_type_class,
7278 enumeral_type_class, boolean_type_class,
7279 pointer_type_class, reference_type_class, offset_type_class,
7280 real_type_class, complex_type_class,
7281 function_type_class, method_type_class,
7282 record_type_class, union_type_class,
7283 array_type_class, string_type_class,
7284 lang_type_class
7285 };
Mike Stump11289f42009-09-09 15:08:12 +00007286
7287 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007288 // ideal, however it is what gcc does.
7289 if (E->getNumArgs() == 0)
7290 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007291
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007292 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7293 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7294
7295 switch (CanTy->getTypeClass()) {
7296#define TYPE(ID, BASE)
7297#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7298#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7299#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7300#include "clang/AST/TypeNodes.def"
7301 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7302
7303 case Type::Builtin:
7304 switch (BT->getKind()) {
7305#define BUILTIN_TYPE(ID, SINGLETON_ID)
7306#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7307#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7308#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7309#include "clang/AST/BuiltinTypes.def"
7310 case BuiltinType::Void:
7311 return void_type_class;
7312
7313 case BuiltinType::Bool:
7314 return boolean_type_class;
7315
7316 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7317 case BuiltinType::UChar:
7318 case BuiltinType::UShort:
7319 case BuiltinType::UInt:
7320 case BuiltinType::ULong:
7321 case BuiltinType::ULongLong:
7322 case BuiltinType::UInt128:
7323 return integer_type_class;
7324
7325 case BuiltinType::NullPtr:
7326 return pointer_type_class;
7327
7328 case BuiltinType::WChar_U:
Richard Smith3a8244d2018-05-01 05:02:45 +00007329 case BuiltinType::Char8:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007330 case BuiltinType::Char16:
7331 case BuiltinType::Char32:
7332 case BuiltinType::ObjCId:
7333 case BuiltinType::ObjCClass:
7334 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007335#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7336 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007337#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007338 case BuiltinType::OCLSampler:
7339 case BuiltinType::OCLEvent:
7340 case BuiltinType::OCLClkEvent:
7341 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007342 case BuiltinType::OCLReserveID:
7343 case BuiltinType::Dependent:
7344 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7345 };
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007346 break;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007347
7348 case Type::Enum:
7349 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7350 break;
7351
7352 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007353 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007354 break;
7355
7356 case Type::MemberPointer:
7357 if (CanTy->isMemberDataPointerType())
7358 return offset_type_class;
7359 else {
7360 // We expect member pointers to be either data or function pointers,
7361 // nothing else.
7362 assert(CanTy->isMemberFunctionPointerType());
7363 return method_type_class;
7364 }
7365
7366 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007367 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007368
7369 case Type::FunctionNoProto:
7370 case Type::FunctionProto:
7371 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7372
7373 case Type::Record:
7374 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7375 switch (RT->getDecl()->getTagKind()) {
7376 case TagTypeKind::TTK_Struct:
7377 case TagTypeKind::TTK_Class:
7378 case TagTypeKind::TTK_Interface:
7379 return record_type_class;
7380
7381 case TagTypeKind::TTK_Enum:
7382 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7383
7384 case TagTypeKind::TTK_Union:
7385 return union_type_class;
7386 }
7387 }
David Blaikie83d382b2011-09-23 05:06:16 +00007388 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007389
7390 case Type::ConstantArray:
7391 case Type::VariableArray:
7392 case Type::IncompleteArray:
7393 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7394
7395 case Type::BlockPointer:
7396 case Type::LValueReference:
7397 case Type::RValueReference:
7398 case Type::Vector:
7399 case Type::ExtVector:
7400 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007401 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007402 case Type::ObjCObject:
7403 case Type::ObjCInterface:
7404 case Type::ObjCObjectPointer:
7405 case Type::Pipe:
7406 case Type::Atomic:
7407 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7408 }
7409
7410 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007411}
7412
Richard Smith5fab0c92011-12-28 19:48:30 +00007413/// EvaluateBuiltinConstantPForLValue - Determine the result of
7414/// __builtin_constant_p when applied to the given lvalue.
7415///
7416/// An lvalue is only "constant" if it is a pointer or reference to the first
7417/// character of a string literal.
7418template<typename LValue>
7419static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007420 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007421 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7422}
7423
7424/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7425/// GCC as we can manage.
7426static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7427 QualType ArgType = Arg->getType();
7428
7429 // __builtin_constant_p always has one operand. The rules which gcc follows
7430 // are not precisely documented, but are as follows:
7431 //
7432 // - If the operand is of integral, floating, complex or enumeration type,
7433 // and can be folded to a known value of that type, it returns 1.
7434 // - If the operand and can be folded to a pointer to the first character
7435 // of a string literal (or such a pointer cast to an integral type), it
7436 // returns 1.
7437 //
7438 // Otherwise, it returns 0.
7439 //
7440 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7441 // its support for this does not currently work.
7442 if (ArgType->isIntegralOrEnumerationType()) {
7443 Expr::EvalResult Result;
7444 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7445 return false;
7446
7447 APValue &V = Result.Val;
7448 if (V.getKind() == APValue::Int)
7449 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007450 if (V.getKind() == APValue::LValue)
7451 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007452 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7453 return Arg->isEvaluatable(Ctx);
7454 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7455 LValue LV;
7456 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007457 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007458 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7459 : EvaluatePointer(Arg, LV, Info)) &&
7460 !Status.HasSideEffects)
7461 return EvaluateBuiltinConstantPForLValue(LV);
7462 }
7463
7464 // Anything else isn't considered to be sufficiently constant.
7465 return false;
7466}
7467
John McCall95007602010-05-10 23:27:23 +00007468/// Retrieves the "underlying object type" of the given expression,
7469/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007470static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007471 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7472 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007473 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007474 } else if (const Expr *E = B.get<const Expr*>()) {
7475 if (isa<CompoundLiteralExpr>(E))
7476 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007477 }
7478
7479 return QualType();
7480}
7481
George Burgess IV3a03fab2015-09-04 21:28:13 +00007482/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007483/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007484/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007485/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7486///
7487/// Always returns an RValue with a pointer representation.
7488static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7489 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7490
7491 auto *NoParens = E->IgnoreParens();
7492 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007493 if (Cast == nullptr)
7494 return NoParens;
7495
7496 // We only conservatively allow a few kinds of casts, because this code is
7497 // inherently a simple solution that seeks to support the common case.
7498 auto CastKind = Cast->getCastKind();
7499 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7500 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007501 return NoParens;
7502
7503 auto *SubExpr = Cast->getSubExpr();
7504 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7505 return NoParens;
7506 return ignorePointerCastsAndParens(SubExpr);
7507}
7508
George Burgess IVa51c4072015-10-16 01:49:01 +00007509/// Checks to see if the given LValue's Designator is at the end of the LValue's
7510/// record layout. e.g.
7511/// struct { struct { int a, b; } fst, snd; } obj;
7512/// obj.fst // no
7513/// obj.snd // yes
7514/// obj.fst.a // no
7515/// obj.fst.b // no
7516/// obj.snd.a // no
7517/// obj.snd.b // yes
7518///
7519/// Please note: this function is specialized for how __builtin_object_size
7520/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007521///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007522/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7523/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007524static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7525 assert(!LVal.Designator.Invalid);
7526
George Burgess IV4168d752016-06-27 19:40:41 +00007527 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7528 const RecordDecl *Parent = FD->getParent();
7529 Invalid = Parent->isInvalidDecl();
7530 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007531 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007532 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007533 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7534 };
7535
7536 auto &Base = LVal.getLValueBase();
7537 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7538 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007539 bool Invalid;
7540 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7541 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007542 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007543 for (auto *FD : IFD->chain()) {
7544 bool Invalid;
7545 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7546 return Invalid;
7547 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007548 }
7549 }
7550
George Burgess IVe3763372016-12-22 02:50:20 +00007551 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007552 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007553 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007554 // If we don't know the array bound, conservatively assume we're looking at
7555 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007556 ++I;
Alex Lorenz4e246482017-12-20 21:03:38 +00007557 if (BaseType->isIncompleteArrayType())
7558 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7559 else
7560 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
George Burgess IVe3763372016-12-22 02:50:20 +00007561 }
7562
7563 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7564 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007565 if (BaseType->isArrayType()) {
7566 // Because __builtin_object_size treats arrays as objects, we can ignore
7567 // the index iff this is the last array in the Designator.
7568 if (I + 1 == E)
7569 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007570 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7571 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007572 if (Index + 1 != CAT->getSize())
7573 return false;
7574 BaseType = CAT->getElementType();
7575 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007576 const auto *CT = BaseType->castAs<ComplexType>();
7577 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007578 if (Index != 1)
7579 return false;
7580 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007581 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007582 bool Invalid;
7583 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7584 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007585 BaseType = FD->getType();
7586 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007587 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007588 return false;
7589 }
7590 }
7591 return true;
7592}
7593
George Burgess IVe3763372016-12-22 02:50:20 +00007594/// Tests to see if the LValue has a user-specified designator (that isn't
7595/// necessarily valid). Note that this always returns 'true' if the LValue has
7596/// an unsized array as its first designator entry, because there's currently no
7597/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007598static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007599 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007600 return false;
7601
George Burgess IVe3763372016-12-22 02:50:20 +00007602 if (!LVal.Designator.Entries.empty())
7603 return LVal.Designator.isMostDerivedAnUnsizedArray();
7604
George Burgess IVa51c4072015-10-16 01:49:01 +00007605 if (!LVal.InvalidBase)
7606 return true;
7607
George Burgess IVe3763372016-12-22 02:50:20 +00007608 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7609 // the LValueBase.
7610 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7611 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007612}
7613
George Burgess IVe3763372016-12-22 02:50:20 +00007614/// Attempts to detect a user writing into a piece of memory that's impossible
7615/// to figure out the size of by just using types.
7616static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7617 const SubobjectDesignator &Designator = LVal.Designator;
7618 // Notes:
7619 // - Users can only write off of the end when we have an invalid base. Invalid
7620 // bases imply we don't know where the memory came from.
7621 // - We used to be a bit more aggressive here; we'd only be conservative if
7622 // the array at the end was flexible, or if it had 0 or 1 elements. This
7623 // broke some common standard library extensions (PR30346), but was
7624 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7625 // with some sort of whitelist. OTOH, it seems that GCC is always
7626 // conservative with the last element in structs (if it's an array), so our
7627 // current behavior is more compatible than a whitelisting approach would
7628 // be.
7629 return LVal.InvalidBase &&
7630 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7631 Designator.MostDerivedIsArrayElement &&
7632 isDesignatorAtObjectEnd(Ctx, LVal);
7633}
7634
7635/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7636/// Fails if the conversion would cause loss of precision.
7637static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7638 CharUnits &Result) {
7639 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7640 if (Int.ugt(CharUnitsMax))
7641 return false;
7642 Result = CharUnits::fromQuantity(Int.getZExtValue());
7643 return true;
7644}
7645
7646/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7647/// determine how many bytes exist from the beginning of the object to either
7648/// the end of the current subobject, or the end of the object itself, depending
7649/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007650///
George Burgess IVe3763372016-12-22 02:50:20 +00007651/// If this returns false, the value of Result is undefined.
7652static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7653 unsigned Type, const LValue &LVal,
7654 CharUnits &EndOffset) {
7655 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007656
George Burgess IV7fb7e362017-01-03 23:35:19 +00007657 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7658 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7659 return false;
7660 return HandleSizeof(Info, ExprLoc, Ty, Result);
7661 };
7662
George Burgess IVe3763372016-12-22 02:50:20 +00007663 // We want to evaluate the size of the entire object. This is a valid fallback
7664 // for when Type=1 and the designator is invalid, because we're asked for an
7665 // upper-bound.
7666 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7667 // Type=3 wants a lower bound, so we can't fall back to this.
7668 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007669 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007670
7671 llvm::APInt APEndOffset;
7672 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7673 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7674 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7675
7676 if (LVal.InvalidBase)
7677 return false;
7678
7679 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007680 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007681 }
7682
George Burgess IVe3763372016-12-22 02:50:20 +00007683 // We want to evaluate the size of a subobject.
7684 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007685
7686 // The following is a moderately common idiom in C:
7687 //
7688 // struct Foo { int a; char c[1]; };
7689 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7690 // strcpy(&F->c[0], Bar);
7691 //
George Burgess IVe3763372016-12-22 02:50:20 +00007692 // In order to not break too much legacy code, we need to support it.
7693 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7694 // If we can resolve this to an alloc_size call, we can hand that back,
7695 // because we know for certain how many bytes there are to write to.
7696 llvm::APInt APEndOffset;
7697 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7698 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7699 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7700
7701 // If we cannot determine the size of the initial allocation, then we can't
7702 // given an accurate upper-bound. However, we are still able to give
7703 // conservative lower-bounds for Type=3.
7704 if (Type == 1)
7705 return false;
7706 }
7707
7708 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007709 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007710 return false;
7711
George Burgess IVe3763372016-12-22 02:50:20 +00007712 // According to the GCC documentation, we want the size of the subobject
7713 // denoted by the pointer. But that's not quite right -- what we actually
7714 // want is the size of the immediately-enclosing array, if there is one.
7715 int64_t ElemsRemaining;
7716 if (Designator.MostDerivedIsArrayElement &&
7717 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7718 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7719 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7720 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7721 } else {
7722 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7723 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007724
George Burgess IVe3763372016-12-22 02:50:20 +00007725 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7726 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007727}
7728
George Burgess IVe3763372016-12-22 02:50:20 +00007729/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7730/// returns true and stores the result in @p Size.
7731///
7732/// If @p WasError is non-null, this will report whether the failure to evaluate
7733/// is to be treated as an Error in IntExprEvaluator.
7734static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7735 EvalInfo &Info, uint64_t &Size) {
7736 // Determine the denoted object.
7737 LValue LVal;
7738 {
7739 // The operand of __builtin_object_size is never evaluated for side-effects.
7740 // If there are any, but we can determine the pointed-to object anyway, then
7741 // ignore the side-effects.
7742 SpeculativeEvaluationRAII SpeculativeEval(Info);
7743 FoldOffsetRAII Fold(Info);
7744
7745 if (E->isGLValue()) {
7746 // It's possible for us to be given GLValues if we're called via
7747 // Expr::tryEvaluateObjectSize.
7748 APValue RVal;
7749 if (!EvaluateAsRValue(Info, E, RVal))
7750 return false;
7751 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007752 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7753 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007754 return false;
7755 }
7756
7757 // If we point to before the start of the object, there are no accessible
7758 // bytes.
7759 if (LVal.getLValueOffset().isNegative()) {
7760 Size = 0;
7761 return true;
7762 }
7763
7764 CharUnits EndOffset;
7765 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7766 return false;
7767
7768 // If we've fallen outside of the end offset, just pretend there's nothing to
7769 // write to/read from.
7770 if (EndOffset <= LVal.getLValueOffset())
7771 Size = 0;
7772 else
7773 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7774 return true;
John McCall95007602010-05-10 23:27:23 +00007775}
7776
Peter Collingbournee9200682011-05-13 03:29:01 +00007777bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007778 if (unsigned BuiltinOp = E->getBuiltinCallee())
7779 return VisitBuiltinCallExpr(E, BuiltinOp);
7780
7781 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7782}
7783
7784bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7785 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007786 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007787 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007788 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007789
7790 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007791 // The type was checked when we built the expression.
7792 unsigned Type =
7793 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7794 assert(Type <= 3 && "unexpected type");
7795
George Burgess IVe3763372016-12-22 02:50:20 +00007796 uint64_t Size;
7797 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7798 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007799
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007800 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007801 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007802
Richard Smith01ade172012-05-23 04:13:20 +00007803 // Expression had no side effects, but we couldn't statically determine the
7804 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007805 switch (Info.EvalMode) {
7806 case EvalInfo::EM_ConstantExpression:
7807 case EvalInfo::EM_PotentialConstantExpression:
7808 case EvalInfo::EM_ConstantFold:
7809 case EvalInfo::EM_EvaluateForOverflow:
7810 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007811 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007812 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007813 return Error(E);
7814 case EvalInfo::EM_ConstantExpressionUnevaluated:
7815 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007816 // Reduce it to a constant now.
7817 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007818 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007819
7820 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007821 }
7822
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007823 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007824 case Builtin::BI__builtin_bswap32:
7825 case Builtin::BI__builtin_bswap64: {
7826 APSInt Val;
7827 if (!EvaluateInteger(E->getArg(0), Val, Info))
7828 return false;
7829
7830 return Success(Val.byteSwap(), E);
7831 }
7832
Richard Smith8889a3d2013-06-13 06:26:32 +00007833 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007834 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007835
7836 // FIXME: BI__builtin_clrsb
7837 // FIXME: BI__builtin_clrsbl
7838 // FIXME: BI__builtin_clrsbll
7839
Richard Smith80b3c8e2013-06-13 05:04:16 +00007840 case Builtin::BI__builtin_clz:
7841 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007842 case Builtin::BI__builtin_clzll:
7843 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007844 APSInt Val;
7845 if (!EvaluateInteger(E->getArg(0), Val, Info))
7846 return false;
7847 if (!Val)
7848 return Error(E);
7849
7850 return Success(Val.countLeadingZeros(), E);
7851 }
7852
Richard Smith8889a3d2013-06-13 06:26:32 +00007853 case Builtin::BI__builtin_constant_p:
7854 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7855
Richard Smith80b3c8e2013-06-13 05:04:16 +00007856 case Builtin::BI__builtin_ctz:
7857 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007858 case Builtin::BI__builtin_ctzll:
7859 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007860 APSInt Val;
7861 if (!EvaluateInteger(E->getArg(0), Val, Info))
7862 return false;
7863 if (!Val)
7864 return Error(E);
7865
7866 return Success(Val.countTrailingZeros(), E);
7867 }
7868
Richard Smith8889a3d2013-06-13 06:26:32 +00007869 case Builtin::BI__builtin_eh_return_data_regno: {
7870 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7871 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7872 return Success(Operand, E);
7873 }
7874
7875 case Builtin::BI__builtin_expect:
7876 return Visit(E->getArg(0));
7877
7878 case Builtin::BI__builtin_ffs:
7879 case Builtin::BI__builtin_ffsl:
7880 case Builtin::BI__builtin_ffsll: {
7881 APSInt Val;
7882 if (!EvaluateInteger(E->getArg(0), Val, Info))
7883 return false;
7884
7885 unsigned N = Val.countTrailingZeros();
7886 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7887 }
7888
7889 case Builtin::BI__builtin_fpclassify: {
7890 APFloat Val(0.0);
7891 if (!EvaluateFloat(E->getArg(5), Val, Info))
7892 return false;
7893 unsigned Arg;
7894 switch (Val.getCategory()) {
7895 case APFloat::fcNaN: Arg = 0; break;
7896 case APFloat::fcInfinity: Arg = 1; break;
7897 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7898 case APFloat::fcZero: Arg = 4; break;
7899 }
7900 return Visit(E->getArg(Arg));
7901 }
7902
7903 case Builtin::BI__builtin_isinf_sign: {
7904 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007905 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007906 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7907 }
7908
Richard Smithea3019d2013-10-15 19:07:14 +00007909 case Builtin::BI__builtin_isinf: {
7910 APFloat Val(0.0);
7911 return EvaluateFloat(E->getArg(0), Val, Info) &&
7912 Success(Val.isInfinity() ? 1 : 0, E);
7913 }
7914
7915 case Builtin::BI__builtin_isfinite: {
7916 APFloat Val(0.0);
7917 return EvaluateFloat(E->getArg(0), Val, Info) &&
7918 Success(Val.isFinite() ? 1 : 0, E);
7919 }
7920
7921 case Builtin::BI__builtin_isnan: {
7922 APFloat Val(0.0);
7923 return EvaluateFloat(E->getArg(0), Val, Info) &&
7924 Success(Val.isNaN() ? 1 : 0, E);
7925 }
7926
7927 case Builtin::BI__builtin_isnormal: {
7928 APFloat Val(0.0);
7929 return EvaluateFloat(E->getArg(0), Val, Info) &&
7930 Success(Val.isNormal() ? 1 : 0, E);
7931 }
7932
Richard Smith8889a3d2013-06-13 06:26:32 +00007933 case Builtin::BI__builtin_parity:
7934 case Builtin::BI__builtin_parityl:
7935 case Builtin::BI__builtin_parityll: {
7936 APSInt Val;
7937 if (!EvaluateInteger(E->getArg(0), Val, Info))
7938 return false;
7939
7940 return Success(Val.countPopulation() % 2, E);
7941 }
7942
Richard Smith80b3c8e2013-06-13 05:04:16 +00007943 case Builtin::BI__builtin_popcount:
7944 case Builtin::BI__builtin_popcountl:
7945 case Builtin::BI__builtin_popcountll: {
7946 APSInt Val;
7947 if (!EvaluateInteger(E->getArg(0), Val, Info))
7948 return false;
7949
7950 return Success(Val.countPopulation(), E);
7951 }
7952
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007953 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007954 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007955 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007956 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007957 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007958 << /*isConstexpr*/0 << /*isConstructor*/0
7959 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007960 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007961 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00007962 LLVM_FALLTHROUGH;
Richard Smith8110c9d2016-11-29 19:45:17 +00007963 case Builtin::BI__builtin_strlen:
7964 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007965 // As an extension, we support __builtin_strlen() as a constant expression,
7966 // and support folding strlen() to a constant.
7967 LValue String;
7968 if (!EvaluatePointer(E->getArg(0), String, Info))
7969 return false;
7970
Richard Smith8110c9d2016-11-29 19:45:17 +00007971 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7972
Richard Smithe6c19f22013-11-15 02:10:04 +00007973 // Fast path: if it's a string literal, search the string value.
7974 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7975 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007976 // The string literal may have embedded null characters. Find the first
7977 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007978 StringRef Str = S->getBytes();
7979 int64_t Off = String.Offset.getQuantity();
7980 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007981 S->getCharByteWidth() == 1 &&
7982 // FIXME: Add fast-path for wchar_t too.
7983 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007984 Str = Str.substr(Off);
7985
7986 StringRef::size_type Pos = Str.find(0);
7987 if (Pos != StringRef::npos)
7988 Str = Str.substr(0, Pos);
7989
7990 return Success(Str.size(), E);
7991 }
7992
7993 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007994 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007995
7996 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007997 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7998 APValue Char;
7999 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8000 !Char.isInt())
8001 return false;
8002 if (!Char.getInt())
8003 return Success(Strlen, E);
8004 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8005 return false;
8006 }
8007 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008008
Richard Smithe151bab2016-11-11 23:43:35 +00008009 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008010 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008011 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008012 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008013 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008014 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008015 // A call to strlen is not a constant expression.
8016 if (Info.getLangOpts().CPlusPlus11)
8017 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8018 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00008019 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00008020 else
8021 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008022 LLVM_FALLTHROUGH;
Richard Smithe151bab2016-11-11 23:43:35 +00008023 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008024 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00008025 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00008026 case Builtin::BI__builtin_wcsncmp:
8027 case Builtin::BI__builtin_memcmp:
8028 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00008029 LValue String1, String2;
8030 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8031 !EvaluatePointer(E->getArg(1), String2, Info))
8032 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00008033
8034 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8035
Richard Smithe151bab2016-11-11 23:43:35 +00008036 uint64_t MaxLength = uint64_t(-1);
8037 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008038 BuiltinOp != Builtin::BIwcscmp &&
8039 BuiltinOp != Builtin::BI__builtin_strcmp &&
8040 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00008041 APSInt N;
8042 if (!EvaluateInteger(E->getArg(2), N, Info))
8043 return false;
8044 MaxLength = N.getExtValue();
8045 }
8046 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00008047 BuiltinOp != Builtin::BIwmemcmp &&
8048 BuiltinOp != Builtin::BI__builtin_memcmp &&
8049 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Benjamin Kramer33b70922018-04-23 22:04:34 +00008050 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8051 BuiltinOp == Builtin::BIwcsncmp ||
8052 BuiltinOp == Builtin::BIwmemcmp ||
8053 BuiltinOp == Builtin::BI__builtin_wcscmp ||
8054 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8055 BuiltinOp == Builtin::BI__builtin_wmemcmp;
Richard Smithe151bab2016-11-11 23:43:35 +00008056 for (; MaxLength; --MaxLength) {
8057 APValue Char1, Char2;
8058 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
8059 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
8060 !Char1.isInt() || !Char2.isInt())
8061 return false;
Benjamin Kramer33b70922018-04-23 22:04:34 +00008062 if (Char1.getInt() != Char2.getInt()) {
8063 if (IsWide) // wmemcmp compares with wchar_t signedness.
8064 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8065 // memcmp always compares unsigned chars.
8066 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8067 }
Richard Smithe151bab2016-11-11 23:43:35 +00008068 if (StopAtNull && !Char1.getInt())
8069 return Success(0, E);
8070 assert(!(StopAtNull && !Char2.getInt()));
8071 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
8072 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
8073 return false;
8074 }
8075 // We hit the strncmp / memcmp limit.
8076 return Success(0, E);
8077 }
8078
Richard Smith01ba47d2012-04-13 00:45:38 +00008079 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00008080 case Builtin::BI__atomic_is_lock_free:
8081 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00008082 APSInt SizeVal;
8083 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8084 return false;
8085
8086 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8087 // of two less than the maximum inline atomic width, we know it is
8088 // lock-free. If the size isn't a power of two, or greater than the
8089 // maximum alignment where we promote atomics, we know it is not lock-free
8090 // (at least not in the sense of atomic_is_lock_free). Otherwise,
8091 // the answer can only be determined at runtime; for example, 16-byte
8092 // atomics have lock-free implementations on some, but not all,
8093 // x86-64 processors.
8094
8095 // Check power-of-two.
8096 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00008097 if (Size.isPowerOfTwo()) {
8098 // Check against inlining width.
8099 unsigned InlineWidthBits =
8100 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8101 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8102 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8103 Size == CharUnits::One() ||
8104 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8105 Expr::NPC_NeverValueDependent))
8106 // OK, we will inline appropriately-aligned operations of this size,
8107 // and _Atomic(T) is appropriately-aligned.
8108 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008109
Richard Smith01ba47d2012-04-13 00:45:38 +00008110 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8111 castAs<PointerType>()->getPointeeType();
8112 if (!PointeeType->isIncompleteType() &&
8113 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8114 // OK, we will inline operations on this object.
8115 return Success(1, E);
8116 }
8117 }
8118 }
Eli Friedmana4c26022011-10-17 21:44:23 +00008119
Richard Smith01ba47d2012-04-13 00:45:38 +00008120 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8121 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00008122 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00008123 case Builtin::BIomp_is_initial_device:
8124 // We can decide statically which value the runtime would return if called.
8125 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008126 }
Chris Lattner7174bf32008-07-12 00:38:25 +00008127}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00008128
Richard Smith8b3497e2011-10-31 01:37:14 +00008129static bool HasSameBase(const LValue &A, const LValue &B) {
8130 if (!A.getLValueBase())
8131 return !B.getLValueBase();
8132 if (!B.getLValueBase())
8133 return false;
8134
Richard Smithce40ad62011-11-12 22:28:03 +00008135 if (A.getLValueBase().getOpaqueValue() !=
8136 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008137 const Decl *ADecl = GetLValueBaseDecl(A);
8138 if (!ADecl)
8139 return false;
8140 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00008141 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00008142 return false;
8143 }
8144
8145 return IsGlobalLValue(A.getLValueBase()) ||
Akira Hatanaka4e2698c2018-04-10 05:15:01 +00008146 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
8147 A.getLValueVersion() == B.getLValueVersion());
Richard Smith8b3497e2011-10-31 01:37:14 +00008148}
8149
Richard Smithd20f1e62014-10-21 23:01:04 +00008150/// \brief Determine whether this is a pointer past the end of the complete
8151/// object referred to by the lvalue.
8152static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8153 const LValue &LV) {
8154 // A null pointer can be viewed as being "past the end" but we don't
8155 // choose to look at it that way here.
8156 if (!LV.getLValueBase())
8157 return false;
8158
8159 // If the designator is valid and refers to a subobject, we're not pointing
8160 // past the end.
8161 if (!LV.getLValueDesignator().Invalid &&
8162 !LV.getLValueDesignator().isOnePastTheEnd())
8163 return false;
8164
David Majnemerc378ca52015-08-29 08:32:55 +00008165 // A pointer to an incomplete type might be past-the-end if the type's size is
8166 // zero. We cannot tell because the type is incomplete.
8167 QualType Ty = getType(LV.getLValueBase());
8168 if (Ty->isIncompleteType())
8169 return true;
8170
Richard Smithd20f1e62014-10-21 23:01:04 +00008171 // We're a past-the-end pointer if we point to the byte after the object,
8172 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008173 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008174 return LV.getLValueOffset() == Size;
8175}
8176
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008177namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008178
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008179/// \brief Data recursive integer evaluator of certain binary operators.
8180///
8181/// We use a data recursive algorithm for binary operators so that we are able
8182/// to handle extreme cases of chained binary operators without causing stack
8183/// overflow.
8184class DataRecursiveIntBinOpEvaluator {
8185 struct EvalResult {
8186 APValue Val;
8187 bool Failed;
8188
8189 EvalResult() : Failed(false) { }
8190
8191 void swap(EvalResult &RHS) {
8192 Val.swap(RHS.Val);
8193 Failed = RHS.Failed;
8194 RHS.Failed = false;
8195 }
8196 };
8197
8198 struct Job {
8199 const Expr *E;
8200 EvalResult LHSResult; // meaningful only for binary operator expression.
8201 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008202
David Blaikie73726062015-08-12 23:09:24 +00008203 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008204 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008205
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008206 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008207 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008208 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008209
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008210 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008211 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008212 };
8213
8214 SmallVector<Job, 16> Queue;
8215
8216 IntExprEvaluator &IntEval;
8217 EvalInfo &Info;
8218 APValue &FinalResult;
8219
8220public:
8221 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8222 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8223
8224 /// \brief True if \param E is a binary operator that we are going to handle
8225 /// data recursively.
8226 /// We handle binary operators that are comma, logical, or that have operands
8227 /// with integral or enumeration type.
8228 static bool shouldEnqueue(const BinaryOperator *E) {
8229 return E->getOpcode() == BO_Comma ||
8230 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00008231 (E->isRValue() &&
8232 E->getType()->isIntegralOrEnumerationType() &&
8233 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008234 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008235 }
8236
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008237 bool Traverse(const BinaryOperator *E) {
8238 enqueue(E);
8239 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008240 while (!Queue.empty())
8241 process(PrevResult);
8242
8243 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008244
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008245 FinalResult.swap(PrevResult.Val);
8246 return true;
8247 }
8248
8249private:
8250 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8251 return IntEval.Success(Value, E, Result);
8252 }
8253 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8254 return IntEval.Success(Value, E, Result);
8255 }
8256 bool Error(const Expr *E) {
8257 return IntEval.Error(E);
8258 }
8259 bool Error(const Expr *E, diag::kind D) {
8260 return IntEval.Error(E, D);
8261 }
8262
8263 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8264 return Info.CCEDiag(E, D);
8265 }
8266
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008267 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8268 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008269 bool &SuppressRHSDiags);
8270
8271 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8272 const BinaryOperator *E, APValue &Result);
8273
8274 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8275 Result.Failed = !Evaluate(Result.Val, Info, E);
8276 if (Result.Failed)
8277 Result.Val = APValue();
8278 }
8279
Richard Trieuba4d0872012-03-21 23:30:30 +00008280 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008281
8282 void enqueue(const Expr *E) {
8283 E = E->IgnoreParens();
8284 Queue.resize(Queue.size()+1);
8285 Queue.back().E = E;
8286 Queue.back().Kind = Job::AnyExprKind;
8287 }
8288};
8289
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008290}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008291
8292bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008293 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008294 bool &SuppressRHSDiags) {
8295 if (E->getOpcode() == BO_Comma) {
8296 // Ignore LHS but note if we could not evaluate it.
8297 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008298 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008299 return true;
8300 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008301
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008302 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008303 bool LHSAsBool;
8304 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008305 // We were able to evaluate the LHS, see if we can get away with not
8306 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008307 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8308 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008309 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008310 }
8311 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008312 LHSResult.Failed = true;
8313
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008314 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008315 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008316 if (!Info.noteSideEffect())
8317 return false;
8318
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008319 // We can't evaluate the LHS; however, sometimes the result
8320 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8321 // Don't ignore RHS and suppress diagnostics from this arm.
8322 SuppressRHSDiags = true;
8323 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008324
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008325 return true;
8326 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008327
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008328 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8329 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008330
George Burgess IVa145e252016-05-25 22:38:36 +00008331 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008332 return false; // Ignore RHS;
8333
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008334 return true;
8335}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008336
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008337static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8338 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008339 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8340 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8341 // offsets.
8342 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8343 CharUnits &Offset = LVal.getLValueOffset();
8344 uint64_t Offset64 = Offset.getQuantity();
8345 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8346 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8347 : Offset64 + Index64);
8348}
8349
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008350bool DataRecursiveIntBinOpEvaluator::
8351 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8352 const BinaryOperator *E, APValue &Result) {
8353 if (E->getOpcode() == BO_Comma) {
8354 if (RHSResult.Failed)
8355 return false;
8356 Result = RHSResult.Val;
8357 return true;
8358 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008359
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008360 if (E->isLogicalOp()) {
8361 bool lhsResult, rhsResult;
8362 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8363 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008364
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008365 if (LHSIsOK) {
8366 if (RHSIsOK) {
8367 if (E->getOpcode() == BO_LOr)
8368 return Success(lhsResult || rhsResult, E, Result);
8369 else
8370 return Success(lhsResult && rhsResult, E, Result);
8371 }
8372 } else {
8373 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008374 // We can't evaluate the LHS; however, sometimes the result
8375 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8376 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008377 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008378 }
8379 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008380
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008381 return false;
8382 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008383
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008384 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8385 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008386
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008387 if (LHSResult.Failed || RHSResult.Failed)
8388 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008389
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008390 const APValue &LHSVal = LHSResult.Val;
8391 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008392
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008393 // Handle cases like (unsigned long)&a + 4.
8394 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8395 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008396 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008397 return true;
8398 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008399
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008400 // Handle cases like 4 + (unsigned long)&a
8401 if (E->getOpcode() == BO_Add &&
8402 RHSVal.isLValue() && LHSVal.isInt()) {
8403 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008404 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008405 return true;
8406 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008407
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008408 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8409 // Handle (intptr_t)&&A - (intptr_t)&&B.
8410 if (!LHSVal.getLValueOffset().isZero() ||
8411 !RHSVal.getLValueOffset().isZero())
8412 return false;
8413 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8414 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8415 if (!LHSExpr || !RHSExpr)
8416 return false;
8417 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8418 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8419 if (!LHSAddrExpr || !RHSAddrExpr)
8420 return false;
8421 // Make sure both labels come from the same function.
8422 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8423 RHSAddrExpr->getLabel()->getDeclContext())
8424 return false;
8425 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8426 return true;
8427 }
Richard Smith43e77732013-05-07 04:50:00 +00008428
8429 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008430 if (!LHSVal.isInt() || !RHSVal.isInt())
8431 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008432
8433 // Set up the width and signedness manually, in case it can't be deduced
8434 // from the operation we're performing.
8435 // FIXME: Don't do this in the cases where we can deduce it.
8436 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8437 E->getType()->isUnsignedIntegerOrEnumerationType());
8438 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8439 RHSVal.getInt(), Value))
8440 return false;
8441 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008442}
8443
Richard Trieuba4d0872012-03-21 23:30:30 +00008444void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008445 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008446
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008447 switch (job.Kind) {
8448 case Job::AnyExprKind: {
8449 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8450 if (shouldEnqueue(Bop)) {
8451 job.Kind = Job::BinOpKind;
8452 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008453 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008454 }
8455 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008456
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008457 EvaluateExpr(job.E, Result);
8458 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008459 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008460 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008461
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008462 case Job::BinOpKind: {
8463 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008464 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008465 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008466 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008467 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008468 }
8469 if (SuppressRHSDiags)
8470 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008471 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008472 job.Kind = Job::BinOpVisitedLHSKind;
8473 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008474 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008475 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008476
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008477 case Job::BinOpVisitedLHSKind: {
8478 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8479 EvalResult RHS;
8480 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008481 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008482 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008483 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008484 }
8485 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008486
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008487 llvm_unreachable("Invalid Job::Kind!");
8488}
8489
George Burgess IV8c892b52016-05-25 22:31:54 +00008490namespace {
8491/// Used when we determine that we should fail, but can keep evaluating prior to
8492/// noting that we had a failure.
8493class DelayedNoteFailureRAII {
8494 EvalInfo &Info;
8495 bool NoteFailure;
8496
8497public:
8498 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8499 : Info(Info), NoteFailure(NoteFailure) {}
8500 ~DelayedNoteFailureRAII() {
8501 if (NoteFailure) {
8502 bool ContinueAfterFailure = Info.noteFailure();
8503 (void)ContinueAfterFailure;
8504 assert(ContinueAfterFailure &&
8505 "Shouldn't have kept evaluating on failure.");
8506 }
8507 }
8508};
8509}
8510
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008511bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008512 // We don't call noteFailure immediately because the assignment happens after
8513 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008514 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008515 return Error(E);
8516
George Burgess IV8c892b52016-05-25 22:31:54 +00008517 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008518 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8519 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008520
Anders Carlssonacc79812008-11-16 07:17:21 +00008521 QualType LHSTy = E->getLHS()->getType();
8522 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008523
Chandler Carruthb29a7432014-10-11 11:03:30 +00008524 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008525 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008526 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008527 if (E->isAssignmentOp()) {
8528 LValue LV;
8529 EvaluateLValue(E->getLHS(), LV, Info);
8530 LHSOK = false;
8531 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008532 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8533 if (LHSOK) {
8534 LHS.makeComplexFloat();
8535 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8536 }
8537 } else {
8538 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8539 }
George Burgess IVa145e252016-05-25 22:38:36 +00008540 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008541 return false;
8542
Chandler Carruthb29a7432014-10-11 11:03:30 +00008543 if (E->getRHS()->getType()->isRealFloatingType()) {
8544 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8545 return false;
8546 RHS.makeComplexFloat();
8547 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8548 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008549 return false;
8550
8551 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008552 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008553 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008554 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008555 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8556
John McCalle3027922010-08-25 11:45:40 +00008557 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008558 return Success((CR_r == APFloat::cmpEqual &&
8559 CR_i == APFloat::cmpEqual), E);
8560 else {
John McCalle3027922010-08-25 11:45:40 +00008561 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008562 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008563 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008564 CR_r == APFloat::cmpLessThan ||
8565 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008566 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008567 CR_i == APFloat::cmpLessThan ||
8568 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008569 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008570 } else {
John McCalle3027922010-08-25 11:45:40 +00008571 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008572 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8573 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8574 else {
John McCalle3027922010-08-25 11:45:40 +00008575 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008576 "Invalid compex comparison.");
8577 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8578 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8579 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008580 }
8581 }
Mike Stump11289f42009-09-09 15:08:12 +00008582
Anders Carlssonacc79812008-11-16 07:17:21 +00008583 if (LHSTy->isRealFloatingType() &&
8584 RHSTy->isRealFloatingType()) {
8585 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008586
Richard Smith253c2a32012-01-27 01:14:48 +00008587 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008588 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008589 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008590
Richard Smith253c2a32012-01-27 01:14:48 +00008591 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008592 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008593
Anders Carlssonacc79812008-11-16 07:17:21 +00008594 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008595
Anders Carlssonacc79812008-11-16 07:17:21 +00008596 switch (E->getOpcode()) {
8597 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008598 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008599 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008600 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008601 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008602 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008603 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008604 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008605 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008606 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008607 E);
John McCalle3027922010-08-25 11:45:40 +00008608 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008609 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008610 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008611 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008612 || CR == APFloat::cmpLessThan
8613 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008614 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008615 }
Mike Stump11289f42009-09-09 15:08:12 +00008616
Eli Friedmana38da572009-04-28 19:17:36 +00008617 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008618 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008619 LValue LHSValue, RHSValue;
8620
8621 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008622 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008623 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008624
Richard Smith253c2a32012-01-27 01:14:48 +00008625 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008626 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008627
Richard Smith8b3497e2011-10-31 01:37:14 +00008628 // Reject differing bases from the normal codepath; we special-case
8629 // comparisons to null.
8630 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008631 if (E->getOpcode() == BO_Sub) {
8632 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008633 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008634 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008635 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008636 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008637 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008638 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008639 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8640 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8641 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008642 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008643 // Make sure both labels come from the same function.
8644 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8645 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008646 return Error(E);
8647 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008648 }
Richard Smith83c68212011-10-31 05:11:32 +00008649 // Inequalities and subtractions between unrelated pointers have
8650 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008651 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008652 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008653 // A constant address may compare equal to the address of a symbol.
8654 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008655 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008656 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8657 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008658 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008659 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008660 // distinct addresses. In clang, the result of such a comparison is
8661 // unspecified, so it is not a constant expression. However, we do know
8662 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008663 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8664 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008665 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008666 // We can't tell whether weak symbols will end up pointing to the same
8667 // object.
8668 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008669 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008670 // We can't compare the address of the start of one object with the
8671 // past-the-end address of another object, per C++ DR1652.
8672 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8673 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8674 (RHSValue.Base && RHSValue.Offset.isZero() &&
8675 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8676 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008677 // We can't tell whether an object is at the same address as another
8678 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008679 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8680 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008681 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008682 // Pointers with different bases cannot represent the same object.
8683 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008684 }
Eli Friedman64004332009-03-23 04:38:34 +00008685
Richard Smith1b470412012-02-01 08:10:20 +00008686 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8687 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8688
Richard Smith84f6dcf2012-02-02 01:16:57 +00008689 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8690 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8691
John McCalle3027922010-08-25 11:45:40 +00008692 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008693 // C++11 [expr.add]p6:
8694 // Unless both pointers point to elements of the same array object, or
8695 // one past the last element of the array object, the behavior is
8696 // undefined.
8697 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8698 !AreElementsOfSameArray(getType(LHSValue.Base),
8699 LHSDesignator, RHSDesignator))
8700 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8701
Chris Lattner882bdf22010-04-20 17:13:14 +00008702 QualType Type = E->getLHS()->getType();
8703 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008704
Richard Smithd62306a2011-11-10 06:34:14 +00008705 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008706 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008707 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008708
Richard Smith84c6b3d2013-09-10 21:34:14 +00008709 // As an extension, a type may have zero size (empty struct or union in
8710 // C, array of zero length). Pointer subtraction in such cases has
8711 // undefined behavior, so is not constant.
8712 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008713 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008714 << ElementType;
8715 return false;
8716 }
8717
Richard Smith1b470412012-02-01 08:10:20 +00008718 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8719 // and produce incorrect results when it overflows. Such behavior
8720 // appears to be non-conforming, but is common, so perhaps we should
8721 // assume the standard intended for such cases to be undefined behavior
8722 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008723
Richard Smith1b470412012-02-01 08:10:20 +00008724 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8725 // overflow in the final conversion to ptrdiff_t.
8726 APSInt LHS(
8727 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8728 APSInt RHS(
8729 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8730 APSInt ElemSize(
8731 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8732 APSInt TrueResult = (LHS - RHS) / ElemSize;
8733 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8734
Richard Smith0c6124b2015-12-03 01:36:22 +00008735 if (Result.extend(65) != TrueResult &&
8736 !HandleOverflow(Info, E, TrueResult, E->getType()))
8737 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008738 return Success(Result, E);
8739 }
Richard Smithde21b242012-01-31 06:41:30 +00008740
8741 // C++11 [expr.rel]p3:
8742 // Pointers to void (after pointer conversions) can be compared, with a
8743 // result defined as follows: If both pointers represent the same
8744 // address or are both the null pointer value, the result is true if the
8745 // operator is <= or >= and false otherwise; otherwise the result is
8746 // unspecified.
8747 // We interpret this as applying to pointers to *cv* void.
8748 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008749 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008750 CCEDiag(E, diag::note_constexpr_void_comparison);
8751
Richard Smith84f6dcf2012-02-02 01:16:57 +00008752 // C++11 [expr.rel]p2:
8753 // - If two pointers point to non-static data members of the same object,
8754 // or to subobjects or array elements fo such members, recursively, the
8755 // pointer to the later declared member compares greater provided the
8756 // two members have the same access control and provided their class is
8757 // not a union.
8758 // [...]
8759 // - Otherwise pointer comparisons are unspecified.
8760 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8761 E->isRelationalOp()) {
8762 bool WasArrayIndex;
8763 unsigned Mismatch =
8764 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8765 RHSDesignator, WasArrayIndex);
8766 // At the point where the designators diverge, the comparison has a
8767 // specified value if:
8768 // - we are comparing array indices
8769 // - we are comparing fields of a union, or fields with the same access
8770 // Otherwise, the result is unspecified and thus the comparison is not a
8771 // constant expression.
8772 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8773 Mismatch < RHSDesignator.Entries.size()) {
8774 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8775 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8776 if (!LF && !RF)
8777 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8778 else if (!LF)
8779 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8780 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8781 << RF->getParent() << RF;
8782 else if (!RF)
8783 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8784 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8785 << LF->getParent() << LF;
8786 else if (!LF->getParent()->isUnion() &&
8787 LF->getAccess() != RF->getAccess())
8788 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8789 << LF << LF->getAccess() << RF << RF->getAccess()
8790 << LF->getParent();
8791 }
8792 }
8793
Eli Friedman6c31cb42012-04-16 04:30:08 +00008794 // The comparison here must be unsigned, and performed with the same
8795 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008796 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8797 uint64_t CompareLHS = LHSOffset.getQuantity();
8798 uint64_t CompareRHS = RHSOffset.getQuantity();
8799 assert(PtrSize <= 64 && "Unexpected pointer width");
8800 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8801 CompareLHS &= Mask;
8802 CompareRHS &= Mask;
8803
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008804 // If there is a base and this is a relational operator, we can only
8805 // compare pointers within the object in question; otherwise, the result
8806 // depends on where the object is located in memory.
8807 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8808 QualType BaseTy = getType(LHSValue.Base);
8809 if (BaseTy->isIncompleteType())
8810 return Error(E);
8811 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8812 uint64_t OffsetLimit = Size.getQuantity();
8813 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8814 return Error(E);
8815 }
8816
Richard Smith8b3497e2011-10-31 01:37:14 +00008817 switch (E->getOpcode()) {
8818 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008819 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8820 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8821 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8822 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8823 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8824 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008825 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008826 }
8827 }
Richard Smith7bb00672012-02-01 01:42:44 +00008828
8829 if (LHSTy->isMemberPointerType()) {
8830 assert(E->isEqualityOp() && "unexpected member pointer operation");
8831 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8832
8833 MemberPtr LHSValue, RHSValue;
8834
8835 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008836 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008837 return false;
8838
8839 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8840 return false;
8841
8842 // C++11 [expr.eq]p2:
8843 // If both operands are null, they compare equal. Otherwise if only one is
8844 // null, they compare unequal.
8845 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8846 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8847 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8848 }
8849
8850 // Otherwise if either is a pointer to a virtual member function, the
8851 // result is unspecified.
8852 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8853 if (MD->isVirtual())
8854 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8855 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8856 if (MD->isVirtual())
8857 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8858
8859 // Otherwise they compare equal if and only if they would refer to the
8860 // same member of the same most derived object or the same subobject if
8861 // they were dereferenced with a hypothetical object of the associated
8862 // class type.
8863 bool Equal = LHSValue == RHSValue;
8864 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8865 }
8866
Richard Smithab44d9b2012-02-14 22:35:28 +00008867 if (LHSTy->isNullPtrType()) {
8868 assert(E->isComparisonOp() && "unexpected nullptr operation");
8869 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8870 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8871 // are compared, the result is true of the operator is <=, >= or ==, and
8872 // false otherwise.
8873 BinaryOperator::Opcode Opcode = E->getOpcode();
8874 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8875 }
8876
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008877 assert((!LHSTy->isIntegralOrEnumerationType() ||
8878 !RHSTy->isIntegralOrEnumerationType()) &&
8879 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8880 // We can't continue from here for non-integral types.
8881 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008882}
8883
Peter Collingbournee190dee2011-03-11 19:24:49 +00008884/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8885/// a result as the expression's type.
8886bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8887 const UnaryExprOrTypeTraitExpr *E) {
8888 switch(E->getKind()) {
8889 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008890 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008891 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008892 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008893 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008894 }
Eli Friedman64004332009-03-23 04:38:34 +00008895
Peter Collingbournee190dee2011-03-11 19:24:49 +00008896 case UETT_VecStep: {
8897 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008898
Peter Collingbournee190dee2011-03-11 19:24:49 +00008899 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008900 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008901
Peter Collingbournee190dee2011-03-11 19:24:49 +00008902 // The vec_step built-in functions that take a 3-component
8903 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8904 if (n == 3)
8905 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008906
Peter Collingbournee190dee2011-03-11 19:24:49 +00008907 return Success(n, E);
8908 } else
8909 return Success(1, E);
8910 }
8911
8912 case UETT_SizeOf: {
8913 QualType SrcTy = E->getTypeOfArgument();
8914 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8915 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008916 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8917 SrcTy = Ref->getPointeeType();
8918
Richard Smithd62306a2011-11-10 06:34:14 +00008919 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008920 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008921 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008922 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008923 }
Alexey Bataev00396512015-07-02 03:40:19 +00008924 case UETT_OpenMPRequiredSimdAlign:
8925 assert(E->isArgumentType());
8926 return Success(
8927 Info.Ctx.toCharUnitsFromBits(
8928 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8929 .getQuantity(),
8930 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008931 }
8932
8933 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008934}
8935
Peter Collingbournee9200682011-05-13 03:29:01 +00008936bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008937 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008938 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008939 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008940 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008941 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008942 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008943 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008944 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008945 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008946 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008947 APSInt IdxResult;
8948 if (!EvaluateInteger(Idx, IdxResult, Info))
8949 return false;
8950 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8951 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008952 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008953 CurrentType = AT->getElementType();
8954 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8955 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008956 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008957 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008958
James Y Knight7281c352015-12-29 22:31:18 +00008959 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008960 FieldDecl *MemberDecl = ON.getField();
8961 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008962 if (!RT)
8963 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008964 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008965 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008966 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008967 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008968 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008969 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008970 CurrentType = MemberDecl->getType().getNonReferenceType();
8971 break;
8972 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008973
James Y Knight7281c352015-12-29 22:31:18 +00008974 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008975 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008976
James Y Knight7281c352015-12-29 22:31:18 +00008977 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008978 CXXBaseSpecifier *BaseSpec = ON.getBase();
8979 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008980 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008981
8982 // Find the layout of the class whose base we are looking into.
8983 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008984 if (!RT)
8985 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008986 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008987 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008988 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8989
8990 // Find the base class itself.
8991 CurrentType = BaseSpec->getType();
8992 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8993 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008994 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00008995
Douglas Gregord1702062010-04-29 00:18:15 +00008996 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008997 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008998 break;
8999 }
Douglas Gregor882211c2010-04-28 22:16:22 +00009000 }
9001 }
Peter Collingbournee9200682011-05-13 03:29:01 +00009002 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00009003}
9004
Chris Lattnere13042c2008-07-11 19:10:17 +00009005bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009006 switch (E->getOpcode()) {
9007 default:
9008 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9009 // See C99 6.6p3.
9010 return Error(E);
9011 case UO_Extension:
9012 // FIXME: Should extension allow i-c-e extension expressions in its scope?
9013 // If so, we could clear the diagnostic ID.
9014 return Visit(E->getSubExpr());
9015 case UO_Plus:
9016 // The result is just the value.
9017 return Visit(E->getSubExpr());
9018 case UO_Minus: {
9019 if (!Visit(E->getSubExpr()))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00009020 return false;
9021 if (!Result.isInt()) return Error(E);
9022 const APSInt &Value = Result.getInt();
9023 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9024 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9025 E->getType()))
9026 return false;
Richard Smithfe800032012-01-31 04:08:20 +00009027 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009028 }
9029 case UO_Not: {
9030 if (!Visit(E->getSubExpr()))
9031 return false;
9032 if (!Result.isInt()) return Error(E);
9033 return Success(~Result.getInt(), E);
9034 }
9035 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00009036 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00009037 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00009038 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00009039 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00009040 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009041 }
Anders Carlsson9c181652008-07-08 14:35:21 +00009042}
Mike Stump11289f42009-09-09 15:08:12 +00009043
Chris Lattner477c4be2008-07-12 01:15:53 +00009044/// HandleCast - This is used to evaluate implicit or explicit casts where the
9045/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00009046bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9047 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009048 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00009049 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00009050
Eli Friedmanc757de22011-03-25 00:43:55 +00009051 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00009052 case CK_BaseToDerived:
9053 case CK_DerivedToBase:
9054 case CK_UncheckedDerivedToBase:
9055 case CK_Dynamic:
9056 case CK_ToUnion:
9057 case CK_ArrayToPointerDecay:
9058 case CK_FunctionToPointerDecay:
9059 case CK_NullToPointer:
9060 case CK_NullToMemberPointer:
9061 case CK_BaseToDerivedMemberPointer:
9062 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00009063 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00009064 case CK_ConstructorConversion:
9065 case CK_IntegralToPointer:
9066 case CK_ToVoid:
9067 case CK_VectorSplat:
9068 case CK_IntegralToFloating:
9069 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009070 case CK_CPointerToObjCPointerCast:
9071 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009072 case CK_AnyPointerToBlockPointerCast:
9073 case CK_ObjCObjectLValueCast:
9074 case CK_FloatingRealToComplex:
9075 case CK_FloatingComplexToReal:
9076 case CK_FloatingComplexCast:
9077 case CK_FloatingComplexToIntegralComplex:
9078 case CK_IntegralRealToComplex:
9079 case CK_IntegralComplexCast:
9080 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00009081 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009082 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009083 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009084 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009085 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009086 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00009087 llvm_unreachable("invalid cast kind for integral value");
9088
Eli Friedman9faf2f92011-03-25 19:07:11 +00009089 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00009090 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009091 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00009092 case CK_ARCProduceObject:
9093 case CK_ARCConsumeObject:
9094 case CK_ARCReclaimReturnedObject:
9095 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009096 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009097 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009098
Richard Smith4ef685b2012-01-17 21:17:26 +00009099 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00009100 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009101 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00009102 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009103 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009104
9105 case CK_MemberPointerToBoolean:
9106 case CK_PointerToBoolean:
9107 case CK_IntegralToBoolean:
9108 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009109 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00009110 case CK_FloatingComplexToBoolean:
9111 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009112 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00009113 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00009114 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00009115 uint64_t IntResult = BoolResult;
9116 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9117 IntResult = (uint64_t)-1;
9118 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009119 }
9120
Eli Friedmanc757de22011-03-25 00:43:55 +00009121 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00009122 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00009123 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00009124
Eli Friedman742421e2009-02-20 01:15:07 +00009125 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009126 // Allow casts of address-of-label differences if they are no-ops
9127 // or narrowing. (The narrowing case isn't actually guaranteed to
9128 // be constant-evaluatable except in some narrow cases which are hard
9129 // to detect here. We let it through on the assumption the user knows
9130 // what they are doing.)
9131 if (Result.isAddrLabelDiff())
9132 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00009133 // Only allow casts of lvalues if they are lossless.
9134 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9135 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00009136
Richard Smith911e1422012-01-30 22:27:01 +00009137 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9138 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00009139 }
Mike Stump11289f42009-09-09 15:08:12 +00009140
Eli Friedmanc757de22011-03-25 00:43:55 +00009141 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00009142 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9143
John McCall45d55e42010-05-07 21:00:08 +00009144 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00009145 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009146 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009147
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009148 if (LV.getLValueBase()) {
9149 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009150 // FIXME: Allow a larger integer size than the pointer size, and allow
9151 // narrowing back down to pointer width in subsequent integral casts.
9152 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009153 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009154 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009155
Richard Smithcf74da72011-11-16 07:18:12 +00009156 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009157 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009158 return true;
9159 }
9160
Yaxun Liu402804b2016-12-15 08:09:08 +00009161 uint64_t V;
9162 if (LV.isNullPointer())
9163 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9164 else
9165 V = LV.getLValueOffset().getQuantity();
9166
9167 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009168 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009169 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009170
Eli Friedmanc757de22011-03-25 00:43:55 +00009171 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009172 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009173 if (!EvaluateComplex(SubExpr, C, Info))
9174 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009175 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009176 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009177
Eli Friedmanc757de22011-03-25 00:43:55 +00009178 case CK_FloatingToIntegral: {
9179 APFloat F(0.0);
9180 if (!EvaluateFloat(SubExpr, F, Info))
9181 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009182
Richard Smith357362d2011-12-13 06:39:58 +00009183 APSInt Value;
9184 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9185 return false;
9186 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009187 }
9188 }
Mike Stump11289f42009-09-09 15:08:12 +00009189
Eli Friedmanc757de22011-03-25 00:43:55 +00009190 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009191}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009192
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009193bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9194 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009195 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009196 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9197 return false;
9198 if (!LV.isComplexInt())
9199 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009200 return Success(LV.getComplexIntReal(), E);
9201 }
9202
9203 return Visit(E->getSubExpr());
9204}
9205
Eli Friedman4e7a2412009-02-27 04:45:43 +00009206bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009207 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009208 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009209 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9210 return false;
9211 if (!LV.isComplexInt())
9212 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009213 return Success(LV.getComplexIntImag(), E);
9214 }
9215
Richard Smith4a678122011-10-24 18:44:57 +00009216 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009217 return Success(0, E);
9218}
9219
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009220bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9221 return Success(E->getPackLength(), E);
9222}
9223
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009224bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9225 return Success(E->getValue(), E);
9226}
9227
Chris Lattner05706e882008-07-11 18:11:29 +00009228//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009229// Float Evaluation
9230//===----------------------------------------------------------------------===//
9231
9232namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009233class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009234 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009235 APFloat &Result;
9236public:
9237 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009238 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009239
Richard Smith2e312c82012-03-03 22:46:17 +00009240 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009241 Result = V.getFloat();
9242 return true;
9243 }
Eli Friedman24c01542008-08-22 00:06:13 +00009244
Richard Smithfddd3842011-12-30 21:15:51 +00009245 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009246 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9247 return true;
9248 }
9249
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009250 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009251
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009252 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009253 bool VisitBinaryOperator(const BinaryOperator *E);
9254 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009255 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009256
John McCallb1fb0d32010-05-07 22:08:54 +00009257 bool VisitUnaryReal(const UnaryOperator *E);
9258 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009259
Richard Smithfddd3842011-12-30 21:15:51 +00009260 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009261};
9262} // end anonymous namespace
9263
9264static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009265 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009266 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009267}
9268
Jay Foad39c79802011-01-12 09:06:06 +00009269static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009270 QualType ResultTy,
9271 const Expr *Arg,
9272 bool SNaN,
9273 llvm::APFloat &Result) {
9274 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9275 if (!S) return false;
9276
9277 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9278
9279 llvm::APInt fill;
9280
9281 // Treat empty strings as if they were zero.
9282 if (S->getString().empty())
9283 fill = llvm::APInt(32, 0);
9284 else if (S->getString().getAsInteger(0, fill))
9285 return false;
9286
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009287 if (Context.getTargetInfo().isNan2008()) {
9288 if (SNaN)
9289 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9290 else
9291 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9292 } else {
9293 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9294 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9295 // a different encoding to what became a standard in 2008, and for pre-
9296 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9297 // sNaN. This is now known as "legacy NaN" encoding.
9298 if (SNaN)
9299 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9300 else
9301 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9302 }
9303
John McCall16291492010-02-28 13:00:19 +00009304 return true;
9305}
9306
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009307bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009308 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009309 default:
9310 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9311
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009312 case Builtin::BI__builtin_huge_val:
9313 case Builtin::BI__builtin_huge_valf:
9314 case Builtin::BI__builtin_huge_vall:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009315 case Builtin::BI__builtin_huge_valf128:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009316 case Builtin::BI__builtin_inf:
9317 case Builtin::BI__builtin_inff:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009318 case Builtin::BI__builtin_infl:
9319 case Builtin::BI__builtin_inff128: {
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009320 const llvm::fltSemantics &Sem =
9321 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009322 Result = llvm::APFloat::getInf(Sem);
9323 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009324 }
Mike Stump11289f42009-09-09 15:08:12 +00009325
John McCall16291492010-02-28 13:00:19 +00009326 case Builtin::BI__builtin_nans:
9327 case Builtin::BI__builtin_nansf:
9328 case Builtin::BI__builtin_nansl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009329 case Builtin::BI__builtin_nansf128:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009330 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9331 true, Result))
9332 return Error(E);
9333 return true;
John McCall16291492010-02-28 13:00:19 +00009334
Chris Lattner0b7282e2008-10-06 06:31:58 +00009335 case Builtin::BI__builtin_nan:
9336 case Builtin::BI__builtin_nanf:
9337 case Builtin::BI__builtin_nanl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009338 case Builtin::BI__builtin_nanf128:
Mike Stump2346cd22009-05-30 03:56:50 +00009339 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009340 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009341 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9342 false, Result))
9343 return Error(E);
9344 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009345
9346 case Builtin::BI__builtin_fabs:
9347 case Builtin::BI__builtin_fabsf:
9348 case Builtin::BI__builtin_fabsl:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009349 case Builtin::BI__builtin_fabsf128:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009350 if (!EvaluateFloat(E->getArg(0), Result, Info))
9351 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009352
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009353 if (Result.isNegative())
9354 Result.changeSign();
9355 return true;
9356
Richard Smith8889a3d2013-06-13 06:26:32 +00009357 // FIXME: Builtin::BI__builtin_powi
9358 // FIXME: Builtin::BI__builtin_powif
9359 // FIXME: Builtin::BI__builtin_powil
9360
Mike Stump11289f42009-09-09 15:08:12 +00009361 case Builtin::BI__builtin_copysign:
9362 case Builtin::BI__builtin_copysignf:
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009363 case Builtin::BI__builtin_copysignl:
9364 case Builtin::BI__builtin_copysignf128: {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009365 APFloat RHS(0.);
9366 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9367 !EvaluateFloat(E->getArg(1), RHS, Info))
9368 return false;
9369 Result.copySign(RHS);
9370 return true;
9371 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009372 }
9373}
9374
John McCallb1fb0d32010-05-07 22:08:54 +00009375bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009376 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9377 ComplexValue CV;
9378 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9379 return false;
9380 Result = CV.FloatReal;
9381 return true;
9382 }
9383
9384 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009385}
9386
9387bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009388 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9389 ComplexValue CV;
9390 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9391 return false;
9392 Result = CV.FloatImag;
9393 return true;
9394 }
9395
Richard Smith4a678122011-10-24 18:44:57 +00009396 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009397 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9398 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009399 return true;
9400}
9401
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009402bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009403 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009404 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009405 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009406 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009407 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009408 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9409 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009410 Result.changeSign();
9411 return true;
9412 }
9413}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009414
Eli Friedman24c01542008-08-22 00:06:13 +00009415bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009416 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9417 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009418
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009419 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009420 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009421 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009422 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009423 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9424 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009425}
9426
9427bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9428 Result = E->getValue();
9429 return true;
9430}
9431
Peter Collingbournee9200682011-05-13 03:29:01 +00009432bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9433 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009434
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009435 switch (E->getCastKind()) {
9436 default:
Richard Smith11562c52011-10-28 17:51:58 +00009437 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009438
9439 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009440 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009441 return EvaluateInteger(SubExpr, IntResult, Info) &&
9442 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9443 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009444 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009445
9446 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009447 if (!Visit(SubExpr))
9448 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009449 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9450 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009451 }
John McCalld7646252010-11-14 08:17:51 +00009452
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009453 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009454 ComplexValue V;
9455 if (!EvaluateComplex(SubExpr, V, Info))
9456 return false;
9457 Result = V.getComplexFloatReal();
9458 return true;
9459 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009460 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009461}
9462
Eli Friedman24c01542008-08-22 00:06:13 +00009463//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009464// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009465//===----------------------------------------------------------------------===//
9466
9467namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009468class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009469 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009470 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009471
Anders Carlsson537969c2008-11-16 20:27:53 +00009472public:
John McCall93d91dc2010-05-07 17:22:02 +00009473 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009474 : ExprEvaluatorBaseTy(info), Result(Result) {}
9475
Richard Smith2e312c82012-03-03 22:46:17 +00009476 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009477 Result.setFrom(V);
9478 return true;
9479 }
Mike Stump11289f42009-09-09 15:08:12 +00009480
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009481 bool ZeroInitialization(const Expr *E);
9482
Anders Carlsson537969c2008-11-16 20:27:53 +00009483 //===--------------------------------------------------------------------===//
9484 // Visitor Methods
9485 //===--------------------------------------------------------------------===//
9486
Peter Collingbournee9200682011-05-13 03:29:01 +00009487 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009488 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009489 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009490 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009491 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009492};
9493} // end anonymous namespace
9494
John McCall93d91dc2010-05-07 17:22:02 +00009495static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9496 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009497 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009498 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009499}
9500
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009501bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009502 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009503 if (ElemTy->isRealFloatingType()) {
9504 Result.makeComplexFloat();
9505 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9506 Result.FloatReal = Zero;
9507 Result.FloatImag = Zero;
9508 } else {
9509 Result.makeComplexInt();
9510 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9511 Result.IntReal = Zero;
9512 Result.IntImag = Zero;
9513 }
9514 return true;
9515}
9516
Peter Collingbournee9200682011-05-13 03:29:01 +00009517bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9518 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009519
9520 if (SubExpr->getType()->isRealFloatingType()) {
9521 Result.makeComplexFloat();
9522 APFloat &Imag = Result.FloatImag;
9523 if (!EvaluateFloat(SubExpr, Imag, Info))
9524 return false;
9525
9526 Result.FloatReal = APFloat(Imag.getSemantics());
9527 return true;
9528 } else {
9529 assert(SubExpr->getType()->isIntegerType() &&
9530 "Unexpected imaginary literal.");
9531
9532 Result.makeComplexInt();
9533 APSInt &Imag = Result.IntImag;
9534 if (!EvaluateInteger(SubExpr, Imag, Info))
9535 return false;
9536
9537 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9538 return true;
9539 }
9540}
9541
Peter Collingbournee9200682011-05-13 03:29:01 +00009542bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009543
John McCallfcef3cf2010-12-14 17:51:41 +00009544 switch (E->getCastKind()) {
9545 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009546 case CK_BaseToDerived:
9547 case CK_DerivedToBase:
9548 case CK_UncheckedDerivedToBase:
9549 case CK_Dynamic:
9550 case CK_ToUnion:
9551 case CK_ArrayToPointerDecay:
9552 case CK_FunctionToPointerDecay:
9553 case CK_NullToPointer:
9554 case CK_NullToMemberPointer:
9555 case CK_BaseToDerivedMemberPointer:
9556 case CK_DerivedToBaseMemberPointer:
9557 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009558 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009559 case CK_ConstructorConversion:
9560 case CK_IntegralToPointer:
9561 case CK_PointerToIntegral:
9562 case CK_PointerToBoolean:
9563 case CK_ToVoid:
9564 case CK_VectorSplat:
9565 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009566 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009567 case CK_IntegralToBoolean:
9568 case CK_IntegralToFloating:
9569 case CK_FloatingToIntegral:
9570 case CK_FloatingToBoolean:
9571 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009572 case CK_CPointerToObjCPointerCast:
9573 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009574 case CK_AnyPointerToBlockPointerCast:
9575 case CK_ObjCObjectLValueCast:
9576 case CK_FloatingComplexToReal:
9577 case CK_FloatingComplexToBoolean:
9578 case CK_IntegralComplexToReal:
9579 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009580 case CK_ARCProduceObject:
9581 case CK_ARCConsumeObject:
9582 case CK_ARCReclaimReturnedObject:
9583 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009584 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009585 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009586 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009587 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009588 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009589 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009590 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009591 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009592
John McCallfcef3cf2010-12-14 17:51:41 +00009593 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009594 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009595 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009596 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009597
9598 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009599 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009600 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009601 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009602
9603 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009604 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009605 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009606 return false;
9607
John McCallfcef3cf2010-12-14 17:51:41 +00009608 Result.makeComplexFloat();
9609 Result.FloatImag = APFloat(Real.getSemantics());
9610 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009611 }
9612
John McCallfcef3cf2010-12-14 17:51:41 +00009613 case CK_FloatingComplexCast: {
9614 if (!Visit(E->getSubExpr()))
9615 return false;
9616
9617 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9618 QualType From
9619 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9620
Richard Smith357362d2011-12-13 06:39:58 +00009621 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9622 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009623 }
9624
9625 case CK_FloatingComplexToIntegralComplex: {
9626 if (!Visit(E->getSubExpr()))
9627 return false;
9628
9629 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9630 QualType From
9631 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9632 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009633 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9634 To, Result.IntReal) &&
9635 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9636 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009637 }
9638
9639 case CK_IntegralRealToComplex: {
9640 APSInt &Real = Result.IntReal;
9641 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9642 return false;
9643
9644 Result.makeComplexInt();
9645 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9646 return true;
9647 }
9648
9649 case CK_IntegralComplexCast: {
9650 if (!Visit(E->getSubExpr()))
9651 return false;
9652
9653 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9654 QualType From
9655 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9656
Richard Smith911e1422012-01-30 22:27:01 +00009657 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9658 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009659 return true;
9660 }
9661
9662 case CK_IntegralComplexToFloatingComplex: {
9663 if (!Visit(E->getSubExpr()))
9664 return false;
9665
Ted Kremenek28831752012-08-23 20:46:57 +00009666 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009667 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009668 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009669 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009670 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9671 To, Result.FloatReal) &&
9672 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9673 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009674 }
9675 }
9676
9677 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009678}
9679
John McCall93d91dc2010-05-07 17:22:02 +00009680bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009681 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009682 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9683
Chandler Carrutha216cad2014-10-11 00:57:18 +00009684 // Track whether the LHS or RHS is real at the type system level. When this is
9685 // the case we can simplify our evaluation strategy.
9686 bool LHSReal = false, RHSReal = false;
9687
9688 bool LHSOK;
9689 if (E->getLHS()->getType()->isRealFloatingType()) {
9690 LHSReal = true;
9691 APFloat &Real = Result.FloatReal;
9692 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9693 if (LHSOK) {
9694 Result.makeComplexFloat();
9695 Result.FloatImag = APFloat(Real.getSemantics());
9696 }
9697 } else {
9698 LHSOK = Visit(E->getLHS());
9699 }
George Burgess IVa145e252016-05-25 22:38:36 +00009700 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009701 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009702
John McCall93d91dc2010-05-07 17:22:02 +00009703 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009704 if (E->getRHS()->getType()->isRealFloatingType()) {
9705 RHSReal = true;
9706 APFloat &Real = RHS.FloatReal;
9707 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9708 return false;
9709 RHS.makeComplexFloat();
9710 RHS.FloatImag = APFloat(Real.getSemantics());
9711 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009712 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009713
Chandler Carrutha216cad2014-10-11 00:57:18 +00009714 assert(!(LHSReal && RHSReal) &&
9715 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009716 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009717 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009718 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009719 if (Result.isComplexFloat()) {
9720 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9721 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009722 if (LHSReal)
9723 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9724 else if (!RHSReal)
9725 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9726 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009727 } else {
9728 Result.getComplexIntReal() += RHS.getComplexIntReal();
9729 Result.getComplexIntImag() += RHS.getComplexIntImag();
9730 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009731 break;
John McCalle3027922010-08-25 11:45:40 +00009732 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009733 if (Result.isComplexFloat()) {
9734 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9735 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009736 if (LHSReal) {
9737 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9738 Result.getComplexFloatImag().changeSign();
9739 } else if (!RHSReal) {
9740 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9741 APFloat::rmNearestTiesToEven);
9742 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009743 } else {
9744 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9745 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9746 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009747 break;
John McCalle3027922010-08-25 11:45:40 +00009748 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009749 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009750 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009751 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009752 // following naming scheme:
9753 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009754 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009755 APFloat &A = LHS.getComplexFloatReal();
9756 APFloat &B = LHS.getComplexFloatImag();
9757 APFloat &C = RHS.getComplexFloatReal();
9758 APFloat &D = RHS.getComplexFloatImag();
9759 APFloat &ResR = Result.getComplexFloatReal();
9760 APFloat &ResI = Result.getComplexFloatImag();
9761 if (LHSReal) {
9762 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9763 ResR = A * C;
9764 ResI = A * D;
9765 } else if (RHSReal) {
9766 ResR = C * A;
9767 ResI = C * B;
9768 } else {
9769 // In the fully general case, we need to handle NaNs and infinities
9770 // robustly.
9771 APFloat AC = A * C;
9772 APFloat BD = B * D;
9773 APFloat AD = A * D;
9774 APFloat BC = B * C;
9775 ResR = AC - BD;
9776 ResI = AD + BC;
9777 if (ResR.isNaN() && ResI.isNaN()) {
9778 bool Recalc = false;
9779 if (A.isInfinity() || B.isInfinity()) {
9780 A = APFloat::copySign(
9781 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9782 B = APFloat::copySign(
9783 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9784 if (C.isNaN())
9785 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9786 if (D.isNaN())
9787 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9788 Recalc = true;
9789 }
9790 if (C.isInfinity() || D.isInfinity()) {
9791 C = APFloat::copySign(
9792 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9793 D = APFloat::copySign(
9794 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9795 if (A.isNaN())
9796 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9797 if (B.isNaN())
9798 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9799 Recalc = true;
9800 }
9801 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9802 AD.isInfinity() || BC.isInfinity())) {
9803 if (A.isNaN())
9804 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9805 if (B.isNaN())
9806 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9807 if (C.isNaN())
9808 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9809 if (D.isNaN())
9810 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9811 Recalc = true;
9812 }
9813 if (Recalc) {
9814 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9815 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9816 }
9817 }
9818 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009819 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009820 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009821 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009822 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9823 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009824 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009825 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9826 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9827 }
9828 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009829 case BO_Div:
9830 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009831 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009832 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009833 // following naming scheme:
9834 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009835 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009836 APFloat &A = LHS.getComplexFloatReal();
9837 APFloat &B = LHS.getComplexFloatImag();
9838 APFloat &C = RHS.getComplexFloatReal();
9839 APFloat &D = RHS.getComplexFloatImag();
9840 APFloat &ResR = Result.getComplexFloatReal();
9841 APFloat &ResI = Result.getComplexFloatImag();
9842 if (RHSReal) {
9843 ResR = A / C;
9844 ResI = B / C;
9845 } else {
9846 if (LHSReal) {
9847 // No real optimizations we can do here, stub out with zero.
9848 B = APFloat::getZero(A.getSemantics());
9849 }
9850 int DenomLogB = 0;
9851 APFloat MaxCD = maxnum(abs(C), abs(D));
9852 if (MaxCD.isFinite()) {
9853 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009854 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9855 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009856 }
9857 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009858 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9859 APFloat::rmNearestTiesToEven);
9860 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9861 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009862 if (ResR.isNaN() && ResI.isNaN()) {
9863 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9864 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9865 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9866 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9867 D.isFinite()) {
9868 A = APFloat::copySign(
9869 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9870 B = APFloat::copySign(
9871 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9872 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9873 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9874 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9875 C = APFloat::copySign(
9876 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9877 D = APFloat::copySign(
9878 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9879 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9880 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9881 }
9882 }
9883 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009884 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009885 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9886 return Error(E, diag::note_expr_divide_by_zero);
9887
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009888 ComplexValue LHS = Result;
9889 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9890 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9891 Result.getComplexIntReal() =
9892 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9893 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9894 Result.getComplexIntImag() =
9895 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9896 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9897 }
9898 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009899 }
9900
John McCall93d91dc2010-05-07 17:22:02 +00009901 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009902}
9903
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009904bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9905 // Get the operand value into 'Result'.
9906 if (!Visit(E->getSubExpr()))
9907 return false;
9908
9909 switch (E->getOpcode()) {
9910 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009911 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009912 case UO_Extension:
9913 return true;
9914 case UO_Plus:
9915 // The result is always just the subexpr.
9916 return true;
9917 case UO_Minus:
9918 if (Result.isComplexFloat()) {
9919 Result.getComplexFloatReal().changeSign();
9920 Result.getComplexFloatImag().changeSign();
9921 }
9922 else {
9923 Result.getComplexIntReal() = -Result.getComplexIntReal();
9924 Result.getComplexIntImag() = -Result.getComplexIntImag();
9925 }
9926 return true;
9927 case UO_Not:
9928 if (Result.isComplexFloat())
9929 Result.getComplexFloatImag().changeSign();
9930 else
9931 Result.getComplexIntImag() = -Result.getComplexIntImag();
9932 return true;
9933 }
9934}
9935
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009936bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9937 if (E->getNumInits() == 2) {
9938 if (E->getType()->isComplexType()) {
9939 Result.makeComplexFloat();
9940 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9941 return false;
9942 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9943 return false;
9944 } else {
9945 Result.makeComplexInt();
9946 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9947 return false;
9948 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9949 return false;
9950 }
9951 return true;
9952 }
9953 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9954}
9955
Anders Carlsson537969c2008-11-16 20:27:53 +00009956//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009957// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9958// implicit conversion.
9959//===----------------------------------------------------------------------===//
9960
9961namespace {
9962class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009963 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009964 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009965 APValue &Result;
9966public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009967 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9968 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009969
9970 bool Success(const APValue &V, const Expr *E) {
9971 Result = V;
9972 return true;
9973 }
9974
9975 bool ZeroInitialization(const Expr *E) {
9976 ImplicitValueInitExpr VIE(
9977 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009978 // For atomic-qualified class (and array) types in C++, initialize the
9979 // _Atomic-wrapped subobject directly, in-place.
9980 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9981 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009982 }
9983
9984 bool VisitCastExpr(const CastExpr *E) {
9985 switch (E->getCastKind()) {
9986 default:
9987 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9988 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009989 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9990 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009991 }
9992 }
9993};
9994} // end anonymous namespace
9995
Richard Smith64cb9ca2017-02-22 22:09:50 +00009996static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9997 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009998 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009999 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +000010000}
10001
10002//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +000010003// Void expression evaluation, primarily for a cast to void on the LHS of a
10004// comma operator
10005//===----------------------------------------------------------------------===//
10006
10007namespace {
10008class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +000010009 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +000010010public:
10011 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10012
Richard Smith2e312c82012-03-03 22:46:17 +000010013 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +000010014
Richard Smith7cd577b2017-08-17 19:35:50 +000010015 bool ZeroInitialization(const Expr *E) { return true; }
10016
Richard Smith42d3af92011-12-07 00:43:50 +000010017 bool VisitCastExpr(const CastExpr *E) {
10018 switch (E->getCastKind()) {
10019 default:
10020 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10021 case CK_ToVoid:
10022 VisitIgnoredValue(E->getSubExpr());
10023 return true;
10024 }
10025 }
Hal Finkela8443c32014-07-17 14:49:58 +000010026
10027 bool VisitCallExpr(const CallExpr *E) {
10028 switch (E->getBuiltinCallee()) {
10029 default:
10030 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10031 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +000010032 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +000010033 // The argument is not evaluated!
10034 return true;
10035 }
10036 }
Richard Smith42d3af92011-12-07 00:43:50 +000010037};
10038} // end anonymous namespace
10039
10040static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10041 assert(E->isRValue() && E->getType()->isVoidType());
10042 return VoidExprEvaluator(Info).Visit(E);
10043}
10044
10045//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +000010046// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +000010047//===----------------------------------------------------------------------===//
10048
Richard Smith2e312c82012-03-03 22:46:17 +000010049static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +000010050 // In C, function designators are not lvalues, but we evaluate them as if they
10051 // are.
Richard Smitha23ab512013-05-23 00:30:41 +000010052 QualType T = E->getType();
10053 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +000010054 LValue LV;
10055 if (!EvaluateLValue(E, LV, Info))
10056 return false;
10057 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010058 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010059 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +000010060 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010061 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +000010062 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010063 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010064 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +000010065 LValue LV;
10066 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010067 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010068 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010069 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +000010070 llvm::APFloat F(0.0);
10071 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010072 return false;
Richard Smith2e312c82012-03-03 22:46:17 +000010073 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +000010074 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +000010075 ComplexValue C;
10076 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010077 return false;
Richard Smith725810a2011-10-16 21:26:27 +000010078 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +000010079 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +000010080 MemberPtr P;
10081 if (!EvaluateMemberPointer(E, P, Info))
10082 return false;
10083 P.moveInto(Result);
10084 return true;
Richard Smitha23ab512013-05-23 00:30:41 +000010085 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010086 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010087 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010088 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +000010089 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010090 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010091 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +000010092 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010093 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith08d6a2c2013-07-24 07:11:57 +000010094 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +000010095 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +000010096 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +000010097 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010098 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +000010099 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +000010100 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +000010101 if (!EvaluateVoid(E, Info))
10102 return false;
Richard Smitha23ab512013-05-23 00:30:41 +000010103 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +000010104 QualType Unqual = T.getAtomicUnqualifiedType();
10105 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10106 LValue LV;
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010107 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010108 if (!EvaluateAtomic(E, &LV, Value, Info))
10109 return false;
10110 } else {
10111 if (!EvaluateAtomic(E, nullptr, Result, Info))
10112 return false;
10113 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010114 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +000010115 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +000010116 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010117 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +000010118 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +000010119 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010120 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +000010121
Anders Carlsson7b6f0af2008-11-30 16:58:53 +000010122 return true;
10123}
10124
Richard Smithb228a862012-02-15 02:18:13 +000010125/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10126/// cases, the in-place evaluation is essential, since later initializers for
10127/// an object can indirectly refer to subobjects which were initialized earlier.
10128static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +000010129 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +000010130 assert(!E->isValueDependent());
10131
Richard Smith7525ff62013-05-09 07:14:00 +000010132 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +000010133 return false;
10134
10135 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +000010136 // Evaluate arrays and record types in-place, so that later initializers can
10137 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +000010138 QualType T = E->getType();
10139 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +000010140 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010141 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +000010142 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +000010143 else if (T->isAtomicType()) {
10144 QualType Unqual = T.getAtomicUnqualifiedType();
10145 if (Unqual->isArrayType() || Unqual->isRecordType())
10146 return EvaluateAtomic(E, &This, Result, Info);
10147 }
Richard Smithed5165f2011-11-04 05:33:44 +000010148 }
10149
10150 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010151 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010152}
10153
Richard Smithf57d8cb2011-12-09 22:58:01 +000010154/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10155/// lvalue-to-rvalue cast if it is an lvalue.
10156static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010157 if (E->getType().isNull())
10158 return false;
10159
Nick Lewyckyc190f962017-05-02 01:06:16 +000010160 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010161 return false;
10162
Richard Smith2e312c82012-03-03 22:46:17 +000010163 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010164 return false;
10165
10166 if (E->isGLValue()) {
10167 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010168 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010169 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010170 return false;
10171 }
10172
Richard Smith2e312c82012-03-03 22:46:17 +000010173 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010174 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010175}
Richard Smith11562c52011-10-28 17:51:58 +000010176
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010177static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010178 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010179 // Fast-path evaluations of integer literals, since we sometimes see files
10180 // containing vast quantities of these.
10181 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10182 Result.Val = APValue(APSInt(L->getValue(),
10183 L->getType()->isUnsignedIntegerType()));
10184 IsConst = true;
10185 return true;
10186 }
James Dennett0492ef02014-03-14 17:44:10 +000010187
10188 // This case should be rare, but we need to check it before we check on
10189 // the type below.
10190 if (Exp->getType().isNull()) {
10191 IsConst = false;
10192 return true;
10193 }
Daniel Jasperffdee092017-05-02 19:21:42 +000010194
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010195 // FIXME: Evaluating values of large array and record types can cause
10196 // performance problems. Only do so in C++11 for now.
10197 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10198 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010199 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010200 IsConst = false;
10201 return true;
10202 }
10203 return false;
10204}
10205
10206
Richard Smith7b553f12011-10-29 00:50:52 +000010207/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010208/// any crazy technique (that has nothing to do with language standards) that
10209/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010210/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10211/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010212bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010213 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010214 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010215 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +000010216
Richard Smith6d4c6582013-11-05 22:18:15 +000010217 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010218 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010219}
10220
Jay Foad39c79802011-01-12 09:06:06 +000010221bool Expr::EvaluateAsBooleanCondition(bool &Result,
10222 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010223 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010224 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010225 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010226}
10227
Richard Smithce8eca52015-12-08 03:21:47 +000010228static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10229 Expr::SideEffectsKind SEK) {
10230 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10231 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10232}
10233
Richard Smith5fab0c92011-12-28 19:48:30 +000010234bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10235 SideEffectsKind AllowSideEffects) const {
10236 if (!getType()->isIntegralOrEnumerationType())
10237 return false;
10238
Richard Smith11562c52011-10-28 17:51:58 +000010239 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010240 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010241 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010242 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010243
Richard Smith11562c52011-10-28 17:51:58 +000010244 Result = ExprResult.Val.getInt();
10245 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010246}
10247
Richard Trieube234c32016-04-21 21:04:55 +000010248bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10249 SideEffectsKind AllowSideEffects) const {
10250 if (!getType()->isRealFloatingType())
10251 return false;
10252
10253 EvalResult ExprResult;
10254 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10255 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10256 return false;
10257
10258 Result = ExprResult.Val.getFloat();
10259 return true;
10260}
10261
Jay Foad39c79802011-01-12 09:06:06 +000010262bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010263 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010264
John McCall45d55e42010-05-07 21:00:08 +000010265 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010266 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10267 !CheckLValueConstantExpression(Info, getExprLoc(),
10268 Ctx.getLValueReferenceType(getType()), LV))
10269 return false;
10270
Richard Smith2e312c82012-03-03 22:46:17 +000010271 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010272 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010273}
10274
Richard Smithd0b4dd62011-12-19 06:19:21 +000010275bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10276 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010277 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010278 // FIXME: Evaluating initializers for large array and record types can cause
10279 // performance problems. Only do so in C++11 for now.
10280 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010281 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010282 return false;
10283
Richard Smithd0b4dd62011-12-19 06:19:21 +000010284 Expr::EvalStatus EStatus;
10285 EStatus.Diag = &Notes;
10286
Richard Smith0c6124b2015-12-03 01:36:22 +000010287 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10288 ? EvalInfo::EM_ConstantExpression
10289 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010290 InitInfo.setEvaluatingDecl(VD, Value);
10291
10292 LValue LVal;
10293 LVal.set(VD);
10294
Richard Smithfddd3842011-12-30 21:15:51 +000010295 // C++11 [basic.start.init]p2:
10296 // Variables with static storage duration or thread storage duration shall be
10297 // zero-initialized before any other initialization takes place.
10298 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010299 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010300 !VD->getType()->isReferenceType()) {
10301 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010302 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010303 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010304 return false;
10305 }
10306
Richard Smith7525ff62013-05-09 07:14:00 +000010307 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10308 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010309 EStatus.HasSideEffects)
10310 return false;
10311
10312 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10313 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010314}
10315
Richard Smith7b553f12011-10-29 00:50:52 +000010316/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10317/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010318bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010319 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010320 return EvaluateAsRValue(Result, Ctx) &&
10321 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010322}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010323
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010324APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010325 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010326 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010327 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010328 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010329 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010330 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010331 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010332
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010333 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010334}
John McCall864e3962010-05-07 05:32:02 +000010335
Richard Smithe9ff7702013-11-05 22:23:30 +000010336void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010337 bool IsConst;
10338 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010339 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010340 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010341 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10342 }
10343}
10344
Richard Smithe6c01442013-06-05 00:46:14 +000010345bool Expr::EvalResult::isGlobalLValue() const {
10346 assert(Val.isLValue());
10347 return IsGlobalLValue(Val.getLValueBase());
10348}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010349
10350
John McCall864e3962010-05-07 05:32:02 +000010351/// isIntegerConstantExpr - this recursive routine will test if an expression is
10352/// an integer constant expression.
10353
10354/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10355/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010356
10357// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010358// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10359// and a (possibly null) SourceLocation indicating the location of the problem.
10360//
John McCall864e3962010-05-07 05:32:02 +000010361// Note that to reduce code duplication, this helper does no evaluation
10362// itself; the caller checks whether the expression is evaluatable, and
10363// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010364// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010365
Dan Gohman28ade552010-07-26 21:25:24 +000010366namespace {
10367
Richard Smith9e575da2012-12-28 13:25:52 +000010368enum ICEKind {
10369 /// This expression is an ICE.
10370 IK_ICE,
10371 /// This expression is not an ICE, but if it isn't evaluated, it's
10372 /// a legal subexpression for an ICE. This return value is used to handle
10373 /// the comma operator in C99 mode, and non-constant subexpressions.
10374 IK_ICEIfUnevaluated,
10375 /// This expression is not an ICE, and is not a legal subexpression for one.
10376 IK_NotICE
10377};
10378
John McCall864e3962010-05-07 05:32:02 +000010379struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010380 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010381 SourceLocation Loc;
10382
Richard Smith9e575da2012-12-28 13:25:52 +000010383 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010384};
10385
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010386}
Dan Gohman28ade552010-07-26 21:25:24 +000010387
Richard Smith9e575da2012-12-28 13:25:52 +000010388static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10389
10390static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010391
Craig Toppera31a8822013-08-22 07:09:37 +000010392static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010393 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010394 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010395 !EVResult.Val.isInt())
10396 return ICEDiag(IK_NotICE, E->getLocStart());
10397
John McCall864e3962010-05-07 05:32:02 +000010398 return NoDiag();
10399}
10400
Craig Toppera31a8822013-08-22 07:09:37 +000010401static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010402 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010403 if (!E->getType()->isIntegralOrEnumerationType())
10404 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010405
10406 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010407#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010408#define STMT(Node, Base) case Expr::Node##Class:
10409#define EXPR(Node, Base)
10410#include "clang/AST/StmtNodes.inc"
10411 case Expr::PredefinedExprClass:
10412 case Expr::FloatingLiteralClass:
10413 case Expr::ImaginaryLiteralClass:
10414 case Expr::StringLiteralClass:
10415 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010416 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010417 case Expr::MemberExprClass:
10418 case Expr::CompoundAssignOperatorClass:
10419 case Expr::CompoundLiteralExprClass:
10420 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010421 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010422 case Expr::ArrayInitLoopExprClass:
10423 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010424 case Expr::NoInitExprClass:
10425 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010426 case Expr::ImplicitValueInitExprClass:
10427 case Expr::ParenListExprClass:
10428 case Expr::VAArgExprClass:
10429 case Expr::AddrLabelExprClass:
10430 case Expr::StmtExprClass:
10431 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010432 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010433 case Expr::CXXDynamicCastExprClass:
10434 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010435 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010436 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010437 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010438 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010439 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010440 case Expr::CXXThisExprClass:
10441 case Expr::CXXThrowExprClass:
10442 case Expr::CXXNewExprClass:
10443 case Expr::CXXDeleteExprClass:
10444 case Expr::CXXPseudoDestructorExprClass:
10445 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010446 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010447 case Expr::DependentScopeDeclRefExprClass:
10448 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010449 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010450 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010451 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010452 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010453 case Expr::CXXTemporaryObjectExprClass:
10454 case Expr::CXXUnresolvedConstructExprClass:
10455 case Expr::CXXDependentScopeMemberExprClass:
10456 case Expr::UnresolvedMemberExprClass:
10457 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010458 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010459 case Expr::ObjCArrayLiteralClass:
10460 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010461 case Expr::ObjCEncodeExprClass:
10462 case Expr::ObjCMessageExprClass:
10463 case Expr::ObjCSelectorExprClass:
10464 case Expr::ObjCProtocolExprClass:
10465 case Expr::ObjCIvarRefExprClass:
10466 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010467 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010468 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010469 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010470 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010471 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010472 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010473 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010474 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010475 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010476 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010477 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010478 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010479 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010480 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010481 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010482 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010483 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010484 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010485 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010486 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010487 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010488 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010489
Richard Smithf137f932014-01-25 20:50:08 +000010490 case Expr::InitListExprClass: {
10491 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10492 // form "T x = { a };" is equivalent to "T x = a;".
10493 // Unless we're initializing a reference, T is a scalar as it is known to be
10494 // of integral or enumeration type.
10495 if (E->isRValue())
10496 if (cast<InitListExpr>(E)->getNumInits() == 1)
10497 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10498 return ICEDiag(IK_NotICE, E->getLocStart());
10499 }
10500
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010501 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010502 case Expr::GNUNullExprClass:
10503 // GCC considers the GNU __null value to be an integral constant expression.
10504 return NoDiag();
10505
John McCall7c454bb2011-07-15 05:09:51 +000010506 case Expr::SubstNonTypeTemplateParmExprClass:
10507 return
10508 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10509
John McCall864e3962010-05-07 05:32:02 +000010510 case Expr::ParenExprClass:
10511 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010512 case Expr::GenericSelectionExprClass:
10513 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010514 case Expr::IntegerLiteralClass:
10515 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010516 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010517 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010518 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010519 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010520 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010521 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010522 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010523 return NoDiag();
10524 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010525 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010526 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10527 // constant expressions, but they can never be ICEs because an ICE cannot
10528 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010529 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010530 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010531 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010532 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010533 }
Richard Smith6365c912012-02-24 22:12:32 +000010534 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010535 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10536 return NoDiag();
George Burgess IV00f70bd2018-03-01 05:43:23 +000010537 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010538 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010539 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010540 // Parameter variables are never constants. Without this check,
10541 // getAnyInitializer() can find a default argument, which leads
10542 // to chaos.
10543 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010544 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010545
10546 // C++ 7.1.5.1p2
10547 // A variable of non-volatile const-qualified integral or enumeration
10548 // type initialized by an ICE can be used in ICEs.
10549 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010550 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010551 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010552
Richard Smithd0b4dd62011-12-19 06:19:21 +000010553 const VarDecl *VD;
10554 // Look for a declaration of this variable that has an initializer, and
10555 // check whether it is an ICE.
10556 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10557 return NoDiag();
10558 else
Richard Smith9e575da2012-12-28 13:25:52 +000010559 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010560 }
10561 }
Richard Smith9e575da2012-12-28 13:25:52 +000010562 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010563 }
John McCall864e3962010-05-07 05:32:02 +000010564 case Expr::UnaryOperatorClass: {
10565 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10566 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010567 case UO_PostInc:
10568 case UO_PostDec:
10569 case UO_PreInc:
10570 case UO_PreDec:
10571 case UO_AddrOf:
10572 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010573 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010574 // C99 6.6/3 allows increment and decrement within unevaluated
10575 // subexpressions of constant expressions, but they can never be ICEs
10576 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010577 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010578 case UO_Extension:
10579 case UO_LNot:
10580 case UO_Plus:
10581 case UO_Minus:
10582 case UO_Not:
10583 case UO_Real:
10584 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010585 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010586 }
Richard Smith9e575da2012-12-28 13:25:52 +000010587
John McCall864e3962010-05-07 05:32:02 +000010588 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010589 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010590 }
10591 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010592 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10593 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10594 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10595 // compliance: we should warn earlier for offsetof expressions with
10596 // array subscripts that aren't ICEs, and if the array subscripts
10597 // are ICEs, the value of the offsetof must be an integer constant.
10598 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010599 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010600 case Expr::UnaryExprOrTypeTraitExprClass: {
10601 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10602 if ((Exp->getKind() == UETT_SizeOf) &&
10603 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010604 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010605 return NoDiag();
10606 }
10607 case Expr::BinaryOperatorClass: {
10608 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10609 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010610 case BO_PtrMemD:
10611 case BO_PtrMemI:
10612 case BO_Assign:
10613 case BO_MulAssign:
10614 case BO_DivAssign:
10615 case BO_RemAssign:
10616 case BO_AddAssign:
10617 case BO_SubAssign:
10618 case BO_ShlAssign:
10619 case BO_ShrAssign:
10620 case BO_AndAssign:
10621 case BO_XorAssign:
10622 case BO_OrAssign:
Richard Smithc70f1d62017-12-14 15:16:18 +000010623 case BO_Cmp: // FIXME: Re-enable once we can evaluate this.
Richard Smith62f65952011-10-24 22:35:48 +000010624 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10625 // constant expressions, but they can never be ICEs because an ICE cannot
10626 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010627 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010628
John McCalle3027922010-08-25 11:45:40 +000010629 case BO_Mul:
10630 case BO_Div:
10631 case BO_Rem:
10632 case BO_Add:
10633 case BO_Sub:
10634 case BO_Shl:
10635 case BO_Shr:
10636 case BO_LT:
10637 case BO_GT:
10638 case BO_LE:
10639 case BO_GE:
10640 case BO_EQ:
10641 case BO_NE:
10642 case BO_And:
10643 case BO_Xor:
10644 case BO_Or:
10645 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010646 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10647 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010648 if (Exp->getOpcode() == BO_Div ||
10649 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010650 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010651 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010652 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010653 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010654 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010655 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010656 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010657 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010658 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010659 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010660 }
10661 }
10662 }
John McCalle3027922010-08-25 11:45:40 +000010663 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010664 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010665 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10666 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010667 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10668 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010669 } else {
10670 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010671 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010672 }
10673 }
Richard Smith9e575da2012-12-28 13:25:52 +000010674 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010675 }
John McCalle3027922010-08-25 11:45:40 +000010676 case BO_LAnd:
10677 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010678 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10679 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010680 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010681 // Rare case where the RHS has a comma "side-effect"; we need
10682 // to actually check the condition to see whether the side
10683 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010684 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010685 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010686 return RHSResult;
10687 return NoDiag();
10688 }
10689
Richard Smith9e575da2012-12-28 13:25:52 +000010690 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010691 }
10692 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010693 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010694 }
10695 case Expr::ImplicitCastExprClass:
10696 case Expr::CStyleCastExprClass:
10697 case Expr::CXXFunctionalCastExprClass:
10698 case Expr::CXXStaticCastExprClass:
10699 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010700 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010701 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010702 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010703 if (isa<ExplicitCastExpr>(E)) {
10704 if (const FloatingLiteral *FL
10705 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10706 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10707 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10708 APSInt IgnoredVal(DestWidth, !DestSigned);
10709 bool Ignored;
10710 // If the value does not fit in the destination type, the behavior is
10711 // undefined, so we are not required to treat it as a constant
10712 // expression.
10713 if (FL->getValue().convertToInteger(IgnoredVal,
10714 llvm::APFloat::rmTowardZero,
10715 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010716 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010717 return NoDiag();
10718 }
10719 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010720 switch (cast<CastExpr>(E)->getCastKind()) {
10721 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010722 case CK_AtomicToNonAtomic:
10723 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010724 case CK_NoOp:
10725 case CK_IntegralToBoolean:
10726 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010727 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010728 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010729 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010730 }
John McCall864e3962010-05-07 05:32:02 +000010731 }
John McCallc07a0c72011-02-17 10:25:35 +000010732 case Expr::BinaryConditionalOperatorClass: {
10733 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10734 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010735 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010736 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010737 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10738 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10739 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010740 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010741 return FalseResult;
10742 }
John McCall864e3962010-05-07 05:32:02 +000010743 case Expr::ConditionalOperatorClass: {
10744 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10745 // If the condition (ignoring parens) is a __builtin_constant_p call,
10746 // then only the true side is actually considered in an integer constant
10747 // expression, and it is fully evaluated. This is an important GNU
10748 // extension. See GCC PR38377 for discussion.
10749 if (const CallExpr *CallCE
10750 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010751 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010752 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010753 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010754 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010755 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010756
Richard Smithf57d8cb2011-12-09 22:58:01 +000010757 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10758 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010759
Richard Smith9e575da2012-12-28 13:25:52 +000010760 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010761 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010762 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010763 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010764 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010765 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010766 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010767 return NoDiag();
10768 // Rare case where the diagnostics depend on which side is evaluated
10769 // Note that if we get here, CondResult is 0, and at least one of
10770 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010771 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010772 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010773 return TrueResult;
10774 }
10775 case Expr::CXXDefaultArgExprClass:
10776 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010777 case Expr::CXXDefaultInitExprClass:
10778 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010779 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010780 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010781 }
10782 }
10783
David Blaikiee4d798f2012-01-20 21:50:17 +000010784 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010785}
10786
Richard Smithf57d8cb2011-12-09 22:58:01 +000010787/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010788static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010789 const Expr *E,
10790 llvm::APSInt *Value,
10791 SourceLocation *Loc) {
10792 if (!E->getType()->isIntegralOrEnumerationType()) {
10793 if (Loc) *Loc = E->getExprLoc();
10794 return false;
10795 }
10796
Richard Smith66e05fe2012-01-18 05:21:49 +000010797 APValue Result;
10798 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010799 return false;
10800
Richard Smith98710fc2014-11-13 23:03:19 +000010801 if (!Result.isInt()) {
10802 if (Loc) *Loc = E->getExprLoc();
10803 return false;
10804 }
10805
Richard Smith66e05fe2012-01-18 05:21:49 +000010806 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010807 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010808}
10809
Craig Toppera31a8822013-08-22 07:09:37 +000010810bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10811 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010812 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010813 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010814
Richard Smith9e575da2012-12-28 13:25:52 +000010815 ICEDiag D = CheckICE(this, Ctx);
10816 if (D.Kind != IK_ICE) {
10817 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010818 return false;
10819 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010820 return true;
10821}
10822
Craig Toppera31a8822013-08-22 07:09:37 +000010823bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010824 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010825 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010826 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10827
10828 if (!isIntegerConstantExpr(Ctx, Loc))
10829 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010830 // The only possible side-effects here are due to UB discovered in the
10831 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10832 // required to treat the expression as an ICE, so we produce the folded
10833 // value.
10834 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010835 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010836 return true;
10837}
Richard Smith66e05fe2012-01-18 05:21:49 +000010838
Craig Toppera31a8822013-08-22 07:09:37 +000010839bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010840 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010841}
10842
Craig Toppera31a8822013-08-22 07:09:37 +000010843bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010844 SourceLocation *Loc) const {
10845 // We support this checking in C++98 mode in order to diagnose compatibility
10846 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010847 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010848
Richard Smith98a0a492012-02-14 21:38:30 +000010849 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010850 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010851 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010852 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010853 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010854
10855 APValue Scratch;
10856 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10857
10858 if (!Diags.empty()) {
10859 IsConstExpr = false;
10860 if (Loc) *Loc = Diags[0].first;
10861 } else if (!IsConstExpr) {
10862 // FIXME: This shouldn't happen.
10863 if (Loc) *Loc = getExprLoc();
10864 }
10865
10866 return IsConstExpr;
10867}
Richard Smith253c2a32012-01-27 01:14:48 +000010868
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010869bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10870 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010871 ArrayRef<const Expr*> Args,
10872 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010873 Expr::EvalStatus Status;
10874 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10875
George Burgess IV177399e2017-01-09 04:12:14 +000010876 LValue ThisVal;
10877 const LValue *ThisPtr = nullptr;
10878 if (This) {
10879#ifndef NDEBUG
10880 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10881 assert(MD && "Don't provide `this` for non-methods.");
10882 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10883#endif
10884 if (EvaluateObjectArgument(Info, This, ThisVal))
10885 ThisPtr = &ThisVal;
10886 if (Info.EvalStatus.HasSideEffects)
10887 return false;
10888 }
10889
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010890 ArgVector ArgValues(Args.size());
10891 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10892 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010893 if ((*I)->isValueDependent() ||
10894 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010895 // If evaluation fails, throw away the argument entirely.
10896 ArgValues[I - Args.begin()] = APValue();
10897 if (Info.EvalStatus.HasSideEffects)
10898 return false;
10899 }
10900
10901 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010902 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010903 ArgValues.data());
10904 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10905}
10906
Richard Smith253c2a32012-01-27 01:14:48 +000010907bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010908 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010909 PartialDiagnosticAt> &Diags) {
10910 // FIXME: It would be useful to check constexpr function templates, but at the
10911 // moment the constant expression evaluator cannot cope with the non-rigorous
10912 // ASTs which we build for dependent expressions.
10913 if (FD->isDependentContext())
10914 return true;
10915
10916 Expr::EvalStatus Status;
10917 Status.Diag = &Diags;
10918
Richard Smith6d4c6582013-11-05 22:18:15 +000010919 EvalInfo Info(FD->getASTContext(), Status,
10920 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010921
10922 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010923 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010924
Richard Smith7525ff62013-05-09 07:14:00 +000010925 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010926 // is a temporary being used as the 'this' pointer.
10927 LValue This;
10928 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Akira Hatanaka4e2698c2018-04-10 05:15:01 +000010929 This.set({&VIE, Info.CurrentCall->Index});
Richard Smith253c2a32012-01-27 01:14:48 +000010930
Richard Smith253c2a32012-01-27 01:14:48 +000010931 ArrayRef<const Expr*> Args;
10932
Richard Smith2e312c82012-03-03 22:46:17 +000010933 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010934 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10935 // Evaluate the call as a constant initializer, to allow the construction
10936 // of objects of non-literal types.
10937 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010938 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10939 } else {
10940 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010941 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010942 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010943 }
Richard Smith253c2a32012-01-27 01:14:48 +000010944
10945 return Diags.empty();
10946}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010947
10948bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10949 const FunctionDecl *FD,
10950 SmallVectorImpl<
10951 PartialDiagnosticAt> &Diags) {
10952 Expr::EvalStatus Status;
10953 Status.Diag = &Diags;
10954
10955 EvalInfo Info(FD->getASTContext(), Status,
10956 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10957
10958 // Fabricate a call stack frame to give the arguments a plausible cover story.
10959 ArrayRef<const Expr*> Args;
10960 ArgVector ArgValues(0);
10961 bool Success = EvaluateArgs(Args, ArgValues, Info);
10962 (void)Success;
10963 assert(Success &&
10964 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010965 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010966
10967 APValue ResultScratch;
10968 Evaluate(ResultScratch, Info, E);
10969 return Diags.empty();
10970}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010971
10972bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10973 unsigned Type) const {
10974 if (!getType()->isPointerType())
10975 return false;
10976
10977 Expr::EvalStatus Status;
10978 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010979 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010980}